Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
371,000 | def categorize_by_attr(self, attribute):
segmentifodescription
flist = sorted(self, key=attrgetter(attribute), reverse=True)
groups = []
keys = []
for k, g in groupby(flist, attrgetter(attribute)):
groups.append(FileList(... | Function to categorize a FileList by a File object
attribute (eg. 'segment', 'ifo', 'description').
Parameters
-----------
attribute : string
File object attribute to categorize FileList
Returns
--------
keys : list
A list of values for an ... |
371,001 | def new_account(self, label=None):
acc, addr = self._backend.new_account(label=label)
assert acc.index == len(self.accounts)
self.accounts.append(acc)
return acc | Creates new account, appends it to the :class:`Wallet`'s account list and returns it.
:param label: account label as `str`
:rtype: :class:`Account` |
371,002 | def any(self, cond):
if callable(cond):
def _cmp(value):
return is_sequence(value) and any(cond(e) for e in value)
else:
def _cmp(value):
return is_sequence(value) and any(e in cond for e in value)
return self._generate_test(
... | Check if a condition is met by any document in a list,
where a condition can also be a sequence (e.g. list).
>>> Query().f1.any(Query().f2 == 1)
Matches::
{'f1': [{'f2': 1}, {'f2': 0}]}
>>> Query().f1.any([1, 2, 3])
Matches::
{'f1': [1, 2]}
... |
371,003 | def get_attached_pipettes(self):
left_data = {
: ,
: ,
: self.model_by_mount[][],
: self.model_by_mount[][]
}
left_model = left_data.get()
if left_model:
tip_length = pipette_config.load(
... | Gets model names of attached pipettes
:return: :dict with keys 'left' and 'right' and a model string for each
mount, or 'uncommissioned' if no model string available |
371,004 | def get_exception():
trace = ""
exception = ""
exc_list = traceback.format_exception_only(
sys.exc_info()[0], sys.exc_info()[1]
)
for entry in exc_list:
exception += entry
tb_list = traceback.format_tb(sys.exc_info()[2])
for entry in tb_list:
trace += entry
r... | Return full formatted traceback as a string. |
371,005 | def element_info(cls_or_slf, node, siblings, level, value_dims):
info = cls_or_slf.component_type(node)
if len(node.kdims) >= 1:
info += cls_or_slf.tab + % .join(d.name for d in node.kdims)
if value_dims and len(node.vdims) >= 1:
info += cls_or_slf.tab + % .joi... | Return the information summary for an Element. This consists
of the dotted name followed by an value dimension names. |
371,006 | def load_cyassimp(file_obj,
file_type=None,
resolver=None,
**kwargs):
if hasattr(file_obj, ):
with tempfile.NamedTemporaryFile(
suffix=str(file_type)) as file_temp:
file_temp.write(file_obj.read())
... | Load a file using the cyassimp bindings.
The easiest way to install these is with conda:
conda install -c menpo/label/master cyassimp
Parameters
---------
file_obj: str, or file object
File path or object containing mesh data
file_type : str
File extension, aka 'stl'
resolver :... |
371,007 | def rotate_lv(*, device, size, debug, forward):
import augeas
class Augeas(augeas.Augeas):
def get_int(self, key):
return int(self.get(key + ))
def set_int(self, key, val):
return self.set(key + , % val)
def incr(self, key, by=1):
orig = self.... | Rotate a logical volume by a single PE.
If forward:
Move the first physical extent of an LV to the end
else:
Move the last physical extent of a LV to the start
then poke LVM to refresh the mapping. |
371,008 | def is_stationarity(self, tolerance=0.2, sample=None):
keys = self.transition_models.keys()
return_val = True
for k in keys:
transition_mat = np.array([np.array(list(self.transition_models[k][i].values()))
for i in self.tra... | Checks if the given markov chain is stationary and checks the steady state
probablity values for the state are consistent.
Parameters:
-----------
tolerance: float
represents the diff between actual steady state value and the computed value
sample: [State(i,j)]
... |
371,009 | def create_proxy_model(self, model, parent, name, multiplicity=, **kwargs):
if model.category != Category.MODEL:
raise IllegalArgumentError("The model should be of category MODEL")
if parent.category != Category.MODEL:
raise IllegalArgumentError("The parent should be of ... | Add this model as a proxy to another parent model.
This will add a model as a proxy model to another parent model. It ensure that it will copy the
whole sub-assembly to the 'parent' model.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
... |
371,010 | def show_state_usage(queue=False, **kwargs):
*
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
pillar = kwargs.get()
pillar_enc = kwargs.get()
if pillar_enc is None \
and pillar is not None \
and not isinstance(pillar, dict):
... | Retrieve the highstate data from the salt master to analyse used and unused states
Custom Pillar data can be passed with the ``pillar`` kwarg.
CLI Example:
.. code-block:: bash
salt '*' state.show_state_usage |
371,011 | def unitize(vectors,
check_valid=False,
threshold=None):
vectors = np.asanyarray(vectors)
if threshold is None:
threshold = TOL_ZERO
if len(vectors.shape) == 2:
norm = np.sqrt(np.dot(vectors * vectors,
... | Unitize a vector or an array or row- vectors.
Parameters
---------
vectors : (n,m) or (j) float
Vector or vectors to be unitized
check_valid : bool
If set, will return mask of nonzero vectors
threshold : float
Cutoff for a value to be considered zero.
Returns
--------... |
371,012 | def _touch_dir(self, path):
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise | A helper function to create a directory if it doesn't exist.
path: A string containing a full path to the directory to be created. |
371,013 | def _compute_error(comp_cov, covariance_, precision_, score_metric="frobenius"):
if score_metric == "frobenius":
return np.linalg.norm(np.triu(comp_cov - covariance_, 1), ord="fro")
elif score_metric == "spectral":
error = comp_cov - covariance_
return np.amax(np.linalg.svdvals(np.d... | Computes the covariance error vs. comp_cov.
Parameters
----------
comp_cov : array-like, shape = (n_features, n_features)
The precision to compare with.
This should normally be the test sample covariance/precision.
scaling : bool
If True, the squared error norm is divided by n_... |
371,014 | def create_widget(self):
d = self.declaration
self.widget = TextView(self.get_context(), None,
d.style or ) | Create the underlying widget. |
371,015 | def greet(self, name, sleep=0):
print("Manufacturing greeting...")
sleep_for(sleep)
greeting = "Hello %s" % name
return greeting | Optionally sleep <sleep> seconds, then return a greeting to <name> |
371,016 | def Convert(self, metadata, process, token=None):
conn_converter = NetworkConnectionToExportedNetworkConnectionConverter(
options=self.options)
return conn_converter.BatchConvert(
[(metadata, conn) for conn in process.connections], token=token) | Converts Process to ExportedNetworkConnection. |
371,017 | def get_cgi_parameter_int(form: cgi.FieldStorage, key: str) -> Optional[int]:
return get_int_or_none(get_cgi_parameter_str(form, key)) | Extracts an integer parameter from a CGI form, or ``None`` if the key is
absent or the string value is not convertible to ``int``. |
371,018 | def subscribe(self, peer_jid):
self.roster.subscribe(aioxmpp.JID.fromstr(peer_jid).bare()) | Asks for subscription
Args:
peer_jid (str): the JID you ask for subscriptiion |
371,019 | def find_service(self, uuid):
for service in self.list_services():
if service.uuid == uuid:
return service
return None | Return the first child service found that has the specified
UUID. Will return None if no service that matches is found. |
371,020 | def request_instance(vm_=None, call=None):
if call == :
raise SaltCloudSystemExit(
)
location = vm_.get(, get_location(vm_))
spot_config = get_spot_config(vm_)
if spot_config is not None:
if not in spot_config:
raise Sa... | Put together all of the information necessary to request an instance on EC2,
and then fire off the request the instance.
Returns data about the instance |
371,021 | def read_firmware(self):
self.cnxn.xfer([0x12])
sleep(10e-3)
self.firmware[] = self.cnxn.xfer([0x00])[0]
self.firmware[] = self.cnxn.xfer([0x00])[0]
self.firmware[] = float(.format(self.firmware[], self.firmware[]))
sleep(0.1)
return... | Read the firmware version of the OPC-N2. Firmware v18+ only.
:rtype: dict
:Example:
>>> alpha.read_firmware()
{
'major': 18,
'minor': 2,
'version': 18.2
} |
371,022 | def topDownCompute(self, encoded):
scaledResult = self.encoder.topDownCompute(encoded)[0]
scaledValue = scaledResult.value
value = math.pow(10, scaledValue)
return EncoderResult(value=value, scalar=value,
encoding = scaledResult.encoding) | See the function description in base.py |
371,023 | def load_tabular_file(fname, return_meta=False, header=True, index_col=True):
if index_col:
index_col = 0
else:
index_col = None
if header:
header = 0
else:
header = None
df = pd.read_csv(fname, header=header, index_col=index_col, sep=)
if return_meta:
... | Given a file name loads as a pandas data frame
Parameters
----------
fname : str
file name and path. Must be tsv.
return_meta :
header : bool (default True)
if there is a header in the tsv file, true will use first row in file.
index_col : bool (default None)
if there i... |
371,024 | def signing_base(self, request, consumer, token):
sig = % escape(consumer.secret)
if token:
sig = sig + escape(token.secret)
return sig, sig | Concatenates the consumer key and secret with the token's
secret. |
371,025 | def _on_receive(self, msg):
_vv and IOLOG.debug(, self, msg)
self._latch.put(msg)
if self.notify:
self.notify(self) | Callback registered for the handle with :class:`Router`; appends data
to the internal queue. |
371,026 | def get_assessment_section(self, assessment_section_id):
return get_section_util(assessment_section_id, runtime=self._runtime, proxy=self._proxy) | Gets an assessemnts section by ``Id``.
arg: assessment_section_id (osid.id.Id): ``Id`` of the
``AssessmentSection``
return: (osid.assessment.AssessmentSection) - the assessment
section
raise: IllegalState - ``has_assessment_begun()`` is ``false``
rais... |
371,027 | def build(self, **kw):
try:
self.get_executor()(self, **kw)
except SCons.Errors.BuildError as e:
e.node = self
raise | Actually build the node.
This is called by the Taskmaster after it's decided that the
Node is out-of-date and must be rebuilt, and after the prepare()
method has gotten everything, uh, prepared.
This method is called from multiple threads in a parallel build,
so only do thread ... |
371,028 | def __set_unit_price(self, value):
try:
if value < 0:
raise ValueError()
self.__unit_price = Decimal(str(value))
except ValueError:
raise ValueError("Unit Price must be a positive number") | Sets the unit price
@param value:str |
371,029 | def summary(args):
p = OptionParser(summary.__doc__)
p.set_table(sep="|", align=True)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
inputbed, scaffolds = args
pf = inputbed.rsplit(".", 1)[0]
mapbed = pf + ".bed"
chr_agp... | %prog summary input.bed scaffolds.fasta
Print out summary statistics per map, followed by consensus summary of
scaffold anchoring based on multiple maps. |
371,030 | def firmware_download_input_rbridge_id(self, **kwargs):
config = ET.Element("config")
firmware_download = ET.Element("firmware_download")
config = firmware_download
input = ET.SubElement(firmware_download, "input")
rbridge_id = ET.SubElement(input, "rbridge-id")
... | Auto Generated Code |
371,031 | def get_for(self, dynamic_part):
if not hasattr(self, ):
raise ImplementationError()
name = self.get_name_for(dynamic_part)
return self._instance.get_field(name) | Return a variation of the current dynamic field based on the given
dynamic part. Use the "format" attribute to create the final name |
371,032 | def repertoire(self, direction, mechanism, purview):
system = self.system[direction]
node_labels = system.node_labels
if not set(purview).issubset(self.purview_indices(direction)):
raise ValueError(.format(
fmt.fmt_mechanism(purview, node_labels), direction,... | Return the cause or effect repertoire function based on a direction.
Args:
direction (str): The temporal direction, specifiying the cause or
effect repertoire. |
371,033 | def pad(img, padding, fill=0, padding_mode=):
r
if not _is_pil_image(img):
raise TypeError(.format(type(img)))
if not isinstance(padding, (numbers.Number, tuple)):
raise TypeError()
if not isinstance(fill, (numbers.Number, str, tuple)):
raise TypeError()
if not isinstance(pa... | r"""Pad the given PIL Image on all sides with specified padding mode and fill value.
Args:
img (PIL Image): Image to be padded.
padding (int or tuple): Padding on each border. If a single int is provided this
is used to pad all borders. If tuple of length 2 is provided this is the paddi... |
371,034 | def disaggregate_radiation(data_daily,
sun_times=None,
pot_rad=None,
method=,
angstr_a=0.25,
angstr_b=0.5,
bristcamp_a=0.75,
... | general function for radiation disaggregation
Args:
daily_data: daily values
sun_times: daily dataframe including results of the util.sun_times function
pot_rad: hourly dataframe including potential radiation
method: keyword specifying the disaggregation method to be used
... |
371,035 | def StructField(name, field_type):
return type_pb2.StructType.Field(name=name, type=field_type) | Construct a field description protobuf.
:type name: str
:param name: the name of the field
:type field_type: :class:`type_pb2.Type`
:param field_type: the type of the field
:rtype: :class:`type_pb2.StructType.Field`
:returns: the appropriate struct-field-type protobuf |
371,036 | def encode_ipmb_msg(header, data):
msg = array()
msg.fromstring(header.encode())
if data is not None:
a = array()
a.fromstring(data)
msg.extend(a)
msg.append(checksum(msg[3:]))
return msg.tostring() | Encode an IPMB message.
header: IPMB header object
data: IPMI message data as bytestring
Returns the message as bytestring. |
371,037 | def load_job(self, job):
if not isinstance(job, Job):
self.log_exc(u"job is not an instance of Job", None, True, ExecuteJobInputError)
self.job = job | Load the job from the given ``Job`` object.
:param job: the job to load
:type job: :class:`~aeneas.job.Job`
:raises: :class:`~aeneas.executejob.ExecuteJobInputError`: if ``job`` is not an instance of :class:`~aeneas.job.Job` |
371,038 | def get_delivery_notes_per_page(self, per_page=1000, page=1, params=None):
return self._get_resource_per_page(resource=DELIVERY_NOTES, per_page=per_page, page=page, params=params) | Get delivery notes per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list |
371,039 | def Matches(self, file_entry, search_depth):
if self._location_segments is None:
location_match = None
else:
location_match = self._CheckLocation(file_entry, search_depth)
if not location_match:
return False, location_match
if search_depth != self._number_of_location_segmen... | Determines if the file entry matches the find specification.
Args:
file_entry (FileEntry): file entry.
search_depth (int): number of location path segments to compare.
Returns:
tuple: contains:
bool: True if the file entry matches the find specification, False
otherwise.... |
371,040 | def is_terminated(self, retry=False):
retry_num = options.retry_times
while retry_num > 0:
try:
return self.status == Instance.Status.TERMINATED
except (errors.InternalServerError, errors.RequestTimeTooSkewed):
retry_num -= 1
... | If this instance has finished or not.
:return: True if finished else False
:rtype: bool |
371,041 | def init_app(self, app):
app.scoped_session = self
@app.teardown_appcontext
def remove_scoped_session(*args, **kwargs):
app.scoped_session.remove() | Setup scoped sesssion creation and teardown for the passed ``app``.
:param app: a :class:`~flask.Flask` application |
371,042 | def assert_inequivalent(o1, o2):
if not (isinstance(o1, type) and isinstance(o2, type)):
assert o1 is not o2
assert not o1 == o2 and o1 != o2
assert not o2 == o1 and o2 != o1 | Asserts that o1 and o2 are distinct and inequivalent objects |
371,043 | def faz(input_file, variables=None):
logging.debug("input file:\n {0}\n".format(input_file))
tasks = parse_input_file(input_file, variables=variables)
print("Found {0} tasks.".format(len(tasks)))
graph = DependencyGraph(tasks)
graph.show_tasks()
graph.execute() | FAZ entry point. |
371,044 | def collect_snmp(self, device, host, port, community):
self.log.info("Collecting ServerTech PDU statistics from: %s" % device)
timestamp = time.time()
inputFeeds = {}
for gaugeName, gaugeOid in self.PDU_SYSTEM_GAUGES.items():
systemGauge... | Collect stats from device |
371,045 | def encode(self, inputs, states=None, valid_length=None):
return self.encoder(self.src_embed(inputs), states, valid_length) | Encode the input sequence.
Parameters
----------
inputs : NDArray
states : list of NDArrays or None, default None
valid_length : NDArray or None, default None
Returns
-------
outputs : list
Outputs of the encoder. |
371,046 | def get_info(self, security_symbols, info_field_codes):
security_symbols = self._str_or_list(security_symbols)
info_field_codes = self._str_or_list(info_field_codes)
url_path = self._build_url_path(security_symbols,
, info_field_codes)
return self._get_data(url_pat... | Queries data from a /<security_type>/info endpoint.
Args:
security_symbols (list): List of string symbols
info_field_codes (list): List of string info field codes
Returns:
dict of the decoded json from server response.
Notes:
The max length of a... |
371,047 | def adjoint(self):
if not self.is_linear:
raise NotImplementedError(
)
forward_op = self
class ResizingOperatorAdjoint(ResizingOperatorBase):
def _call(self, x, out):
with wri... | Adjoint of this operator. |
371,048 | def block_dot(A, B, diagonal=False):
assert A.dtype is np.dtype(), "Must be a block matrix"
assert B.dtype is np.dtype(), "Must be a block matrix"
assert A.shape == B.shape
def f(C,D):
Cshape = C.shape
Dshape = D.shape
if diagonal and (len(Cshape) == 1 or len(D... | Element wise dot product on block matricies
+------+------+ +------+------+ +-------+-------+
| | | | | | |A11.B11|B12.B12|
| A11 | A12 | | B11 | B12 | | | |
+------+------+ o +------+------| = +-------+-------+
| | | | | | ... |
371,049 | def set_mean(self, col, row, mean):
javabridge.call(self.jobject, "setMean", "(IID)V", col, row, mean) | Sets the mean at this location (if valid location).
:param col: the 0-based column index
:type col: int
:param row: the 0-based row index
:type row: int
:param mean: the mean to set
:type mean: float |
371,050 | def local_manager_target_uids(self):
groups = self.root[].backend
managed_uids = set()
for gid in self.local_manager_target_gids:
group = groups.get(gid)
if group:
managed_uids.update(group.member_ids)
return list(managed_uids) | Target uid's for local manager. |
371,051 | def upload_rpm(rpm_path, repoid, connector, callback=None):
ts = rpm.TransactionSet()
ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES)
info = rpm_info(rpm_path)
pkg_name = info[]
nvrea = info[]
cksum = info[]
size = info[]
package_basename = info[]
juicer.utils.Log.log_notice("Expected... | upload an rpm into pulp
rpm_path: path to an rpm
connector: the connector to use for interacting with pulp
callback: Optional callback to call after an RPM is
uploaded. Callback should accept one argument, the name of the RPM
which was uploaded |
371,052 | def tangent_only_intersections(all_types):
if len(all_types) != 1:
raise ValueError("Unexpected value, types should all match", all_types)
point_type = all_types.pop()
if point_type == CLASSIFICATION_T.OPPOSED:
return [], None
elif point_type == CLASSIFICATION_T.IGNORED_CORNER:
... | Determine intersection in the case of only-tangent intersections.
If the only intersections are tangencies, then either the surfaces
are tangent but don't meet ("kissing" edges) or one surface is
internally tangent to the other.
Thus we expect every intersection to be classified as
:attr:`~.Inters... |
371,053 | def get_function_argspec(func, is_class_method=None):
d
need the class to which the function belongs to be instantiated
and this is not always wanted.
{0} is not a callableCannot inspect argument list for \Cannot inspect argument list for \'.format(func)
... | A small wrapper around getargspec that also supports callable classes
:param is_class_method: Pass True if you are sure that the function being passed
is a class method. The reason for this is that on Python 3
``inspect.ismethod`` only returns ``True`` for bou... |
371,054 | def process_signed_elements(self):
sign_nodes = self.__query()
signed_elements = []
verified_seis = []
verified_ids = []
response_tag = % OneLogin_Saml2_Constants.NS_SAMLP
assertion_tag = % OneLogin_Saml2_Constants.NS_SAML
for sign_node in sign_nodes:... | Verifies the signature nodes:
- Checks that are Response or Assertion
- Check that IDs and reference URI are unique and consistent.
:returns: The signed elements tag names
:rtype: list |
371,055 | def parse(self, limit=None, or_limit=1):
dir_path = Path(self.rawdir)
aeolus_file = dir_path / self.files[][]
aeolus_fh = aeolus_file.open()
count = 0
for line in aeolus_fh.readlines():
if limit is not None and count >= limit:
break
... | Parse mydrug files
:param limit: int limit json docs processed
:param or_limit: int odds ratio limit
:return: None |
371,056 | def _netstat_aix():
ret = []
for addr_family in (,):
cmd = .format(addr_family)
out = __salt__[](cmd, python_shell=True)
for line in out.splitlines():
comps = line.split()
if len(comps) < 5:
continue
proto_seen ... | Return netstat information for SunOS flavors |
371,057 | def _linemagic(cls, options, strict=False, backend=None):
"Deprecated, not expected to be used by any current code"
backends = None if backend is None else [backend]
options, failure = cls._process_magic(options, strict, backends=backends)
if failure: return
with options_policy(s... | Deprecated, not expected to be used by any current code |
371,058 | def logout(self):
ret = False
if self.login_result is True:
ret = self.__get_status_code(self.__request()) == 200
self.login_result = None
return ret | Logout of user.
:returns: ``True``
Successful logout
``False``
Logout failed (mainly because user was not login) |
371,059 | def redirect(location=None, internal=False, code=None, headers={},
add_slash=False, request=None):
request = request or state.request
if add_slash:
if location is None:
split_url = list(urlparse.urlsplit(request.url))
new_proto = request.environ.get(
... | Perform a redirect, either internal or external. An internal redirect
performs the redirect server-side, while the external redirect utilizes
an HTTP 302 status code.
:param location: The HTTP location to redirect to.
:param internal: A boolean indicating whether the redirect should be
... |
371,060 | def results_class_wise_average_metrics(self):
class_wise_results = self.results_class_wise_metrics()
class_wise_eer = []
class_wise_fmeasure = []
class_wise_precision = []
class_wise_recall = []
for class_label in class_wise_results:
if class_wise_... | Class-wise averaged metrics
Returns
-------
dict
results in a dictionary format |
371,061 | def unzip_file(filename):
if filename.endswith():
bz2file = bz2.BZ2File(filename)
fdn, tmpfilepath = tempfile.mkstemp()
with closing(os.fdopen(fdn, )) as ofpt:
try:
ofpt.write(bz2file.read())
except IOError:
import traceback
... | Unzip the file if file is bzipped = ending with 'bz2 |
371,062 | def attribute_changed(self, node, column):
index = self.get_attribute_index(node, column)
if index is not None:
self.dataChanged.emit(index, index)
return True
else:
return False | Calls :meth:`QAbstractItemModel.dataChanged` with given Node attribute index.
:param node: Node.
:type node: AbstractCompositeNode or GraphModelNode
:param column: Attribute column.
:type column: int
:return: Method success.
:rtype: bool |
371,063 | def get_post_authorization_redirect_url(request, canvas=True):
path = request.get_full_path()
if canvas:
if FACEBOOK_APPLICATION_CANVAS_URL:
path = path.replace(urlparse(FACEBOOK_APPLICATION_CANVAS_URL).path, )
redirect_uri = % {
: FACEBOOK_APPLICATION_DOMAIN,
... | Determine the URL users should be redirected to upon authorization the application.
If request is non-canvas use user defined site url if set, else the site hostname. |
371,064 | def shred(key_name: str,
value: t.Any,
field_names: t.Iterable[str] = SHRED_DATA_FIELD_NAMES) -> t.Union[t.Any, str]:
key_name = key_name.lower()
need_shred = False
for data_field_name in field_names:
if data_field_name in key_name:
need_shred = True
... | Replaces sensitive data in ``value`` with ``*`` if ``key_name`` contains something that looks like a secret.
:param field_names: a list of key names that can possibly contain sensitive data
:param key_name: a key name to check
:param value: a value to mask
:return: an unchanged value if nothing to hide... |
371,065 | def anagrams_in_word(word, sowpods=False, start="", end=""):
input_letters, blanks, questions = blank_tiles(word)
for tile in start + end:
input_letters.append(tile)
for word in word_list(sowpods, start, end):
lmap = _letter_map(input_letters)
used_blanks = 0
for lett... | Finds anagrams in word.
Args:
word: the string to base our search off of
sowpods: boolean to declare TWL or SOWPODS words file
start: a string of starting characters to find anagrams based on
end: a string of ending characters to find anagrams based on
Yields:
a tuple o... |
371,066 | def get_location_from_HDX_code(code, locations=None, configuration=None):
if locations is None:
locations = Locations.validlocations(configuration)
for locdict in locations:
if code.upper() == locdict[].upper():
return locdict[]
return No... | Get location from HDX location code
Args:
code (str): code for which to get location name
locations (Optional[List[Dict]]): Valid locations list. Defaults to list downloaded from HDX.
configuration (Optional[Configuration]): HDX configuration. Defaults to global configuratio... |
371,067 | def getmembers(self):
return filter(
lambda m: not m[0].startswith("__") and not inspect.isfunction(m[1]) and not inspect.ismethod(m[1]),
inspect.getmembers(self.__class__)
) | :return: list of members as name, type tuples
:rtype: list |
371,068 | def main():
try:
with open() as config_file:
config_data = json.load(config_file)
except FileNotFoundError:
sys.exit()
tenant_id = config_data[]
app_id = config_data[]
app_secret = config_data[]
subscription_id = config_data[]
access_token = azurerm.ge... | Main routine. |
371,069 | def _handle_successful_job(self, job):
result = job.result
task_id = job.kwargs[]
try:
task = self.registry.get(task_id)
except NotFoundError:
logger.warning("Task %s not found; related job
task_id, job.id)
return... | Handle successufl jobs |
371,070 | def entries(self):
table = self.get_table()
entries_array = self.row_structure * table.num_entries
pointer_type = ctypes.POINTER(entries_array)
return ctypes.cast(table.entries, pointer_type).contents | Using the table structure, return the array of entries based
on the table size. |
371,071 | def _update_variables_shim_with_recalculation_table(self):
if not hasattr(self._executable, "recalculation_table"):
return
for memory_reference, expression in self._executable.recalculation_table.items():
self._variables_shim[memory... | Update self._variables_shim with the final values to be patched into the gate parameters,
according to the arithmetic expressions in the original program.
For example:
DECLARE theta REAL
DECLARE beta REAL
RZ(3 * theta) 0
RZ(beta+theta) 0
gets tr... |
371,072 | def rpm_eval(macro):
try:
value = subprocess.Popen(
[, , macro],
stdout=subprocess.PIPE).communicate()[0].strip()
except OSError:
logger.error(.format(
macro), exc_info=True)
value = b
return console_to_str(value) | Get value of given macro using rpm tool |
371,073 | def bin(self):
bin = self._query((, Integer, Integer), self.idx)
return None if bin == -1 else bin | The bin index of this mark.
:returns: An integer bin index or None if the mark is inactive. |
371,074 | def cmd_wp_undo(self):
if self.undo_wp_idx == -1 or self.undo_wp is None:
print("No undo information")
return
wp = self.undo_wp
if self.undo_type == :
wp.target_system = self.target_system
wp.target_component = self.target_component
... | handle wp undo |
371,075 | def view(self, photo, options=None, **kwds):
option_string = self._build_option_string(options)
result = self._client.get("/photo/%s%s/view.json" %
(self._extract_id(photo), option_string),
**kwds)["result"]
return Phot... | Endpoint: /photo/<id>[/<options>]/view.json
Requests all properties of a photo.
Can be used to obtain URLs for the photo at a particular size,
by using the "returnSizes" parameter.
Returns the requested photo object.
The options parameter can be used to pass in additional opti... |
371,076 | def const_rand(size, seed=23980):
old_seed = np.random.seed()
np.random.seed(seed)
out = np.random.rand(size)
np.random.seed(old_seed)
return out | Generate a random array with a fixed seed. |
371,077 | def convert(self, string, preprocess = None):
string = unicode(preprocess(string) if preprocess else string, encoding="utf-8")
if self.regex:
return self.regex.sub(lambda x: self.substitutes[x.group()], string).encode()
else:
return string | Swap characters from a script to transliteration and vice versa.
Optionally sanitize string by using preprocess function.
:param preprocess:
:param string:
:return: |
371,078 | def authenticate(self, provider):
callback_url = url_for(".callback", provider=provider, _external=True)
provider = self.get_provider(provider)
session[] = request.args.get() or
return provider.authorize(callback_url) | Starts OAuth authorization flow, will redirect to 3rd party site. |
371,079 | def parse_response(self, byte_stream, response_class):
log.debug("
log.debug("Payload class: %s" % response_class)
len_bytes = byte_stream.read(4)
total_length = struct.unpack("!I", len_bytes)[0]
log.debug("Total response length: %s" % total_length)
h... | Parses a Hadoop RPC response.
The RpcResponseHeaderProto contains a status field that marks SUCCESS or ERROR.
The Hadoop RPC protocol looks like the diagram below for receiving SUCCESS requests.
+-----------------------------------------------------------+
| Length of the RPC resonse (... |
371,080 | def d2Sbr_dV2(self, Cbr, Ybr, V, lam):
nb = len(V)
nl = len(lam)
ib = range(nb)
il = range(nl)
diaglam = csr_matrix((lam, (il, il)))
diagV = csr_matrix((V, (ib, ib)))
A = Ybr.H * diaglam * Cbr
B = conj(diagV) * A * diagV
D = csr_matrix( ... | Based on d2Sbr_dV2.m from MATPOWER by Ray Zimmerman, developed
at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for
more information.
@rtype: tuple
@return: The 2nd derivatives of complex power flow w.r.t. voltage. |
371,081 | def _deserialize(self, stream):
readline = stream.readline
self.tree = Tree(self.repo, hex_to_bin(readline().split()[1]), Tree.tree_id << 12, )
self.parents = []
next_line = None
while True:
parent_line = readline()
if not parent_line.startswith(... | :param from_rev_list: if true, the stream format is coming from the rev-list command
Otherwise it is assumed to be a plain data stream from our object |
371,082 | def rules(self):
rules = [.format(self.__minlength)]
if self.__requireUppercase:
rules.append()
if self.__requireLowercase:
rules.append()
if self.__requireNumber:
rules.append()
if self.__requireWildcard:
rules.append()
... | Returns the rules for this password based on the configured
options.
:return: <str> |
371,083 | def find_file(search_dir, file_pattern):
for root, dirnames, fnames in os.walk(search_dir):
for fname in fnames:
if fnmatch.fnmatch(fname, file_pattern):
return os.path.join(root, fname)
return "" | Search for a file in a directory, and return the first match.
If the file is not found return an empty string
Args:
search_dir: The root directory to search in
file_pattern: A unix-style wildcard pattern representing
the file to find
Returns:
The path to the file if it ... |
371,084 | def disconnect(self, cback):
"See signal"
return self.signal.disconnect(cback,
subscribers=self.subscribers,
instance=self.instance) | See signal |
371,085 | def from_bytes(cls, xbytes: bytes) -> :
logger = logging.getLogger(__name__)
logger.debug("BlsEntity::from_bytes: >>>")
c_instance = c_void_p()
do_call(cls.from_bytes_handler, xbytes, len(xbytes), byref(c_instance))
res = cls(c_instance)
logger.debug("BlsEntit... | Creates and Bls entity from bytes representation.
:param xbytes: Bytes representation of Bls entity
:return: BLS entity intance |
371,086 | def is_a_string(var, allow_none=False):
return isinstance(var, six.string_types) or (var is None and allow_none) | Returns True if var is a string (ascii or unicode)
Result py-2 py-3
----------------- ----- -----
b'bytes literal' True False
'string literal' True True
u'unicode literal' True True
Also returns True if the var is a numpy string (numpy.string_, nump... |
371,087 | def toposort(data):
if len(data) == 0:
return
data = data.copy()
for k, v in data.items():
v.discard(k)
) | Dependencies are expressed as a dictionary whose keys are items
and whose values are a set of dependent items. Output is a list of
sets in topological order. The first set consists of items with no
dependences, each subsequent set consists of items that depend upon
items in the preceeding sets. |
371,088 | def no_type_check(arg):
if isinstance(arg, type):
arg_attrs = arg.__dict__.copy()
for attr, val in arg.__dict__.items():
if val in arg.__bases__ + (arg,):
arg_attrs.pop(attr)
for obj in arg_attrs.values():
if isinstance(obj, types.FunctionType):
... | Decorator to indicate that annotations are not type hints.
The argument must be a class or function; if it is a class, it
applies recursively to all methods and classes defined in that class
(but not to methods defined in its superclasses or subclasses).
This mutates the function(s) or class(es) in pl... |
371,089 | def makedoedict(str1):
blocklist = str1.split()
blocklist = blocklist[:-1]
blockdict = {}
belongsdict = {}
for num in range(0, len(blocklist)):
blocklist[num] = blocklist[num].strip()
linelist = blocklist[num].split(os.linesep)
aline = linelist[0]
alinelist = ali... | makedoedict |
371,090 | def est_credible_region(self, level=0.95, return_outside=False, modelparam_slice=None):
s_ = np.s_[modelparam_slice] if modelparam_slice is not None else np.s_[:]
mps = self.particle_locations[:, s_]
id_sort = np.argsort(self.particle_weights)[::-1]... | Returns an array containing particles inside a credible region of a
given level, such that the described region has probability mass
no less than the desired level.
Particles in the returned region are selected by including the highest-
weight particles first until the desired credibili... |
371,091 | def GetFileEntryByPathSpec(self, path_spec):
return data_range_file_entry.DataRangeFileEntry(
self._resolver_context, self, path_spec, is_root=True, is_virtual=True) | Retrieves a file entry for a path specification.
Args:
path_spec (PathSpec): a path specification.
Returns:
DataRangeFileEntry: a file entry or None if not available. |
371,092 | def stop_data_fetch(self):
if self._data_fetcher:
self._data_fetcher.stop.set()
self._data_fetcher = None | Stops the thread that fetches data from the Streams view server. |
371,093 | def tempdir(*args, **kwargs):
d = tempfile.mkdtemp(*args, **kwargs)
try:
yield d
finally:
shutil.rmtree(d) | A contextmanager to work in an auto-removed temporary directory
Arguments are passed through to tempfile.mkdtemp
example:
>>> with tempdir() as path:
... pass |
371,094 | def receive(self, data):
if not data:
data = END
self._recv_buffer += data
self._recv_buffer = self._recv_buffer.lstrip(END)
if self._recv_buffer:
... | receive(data) -> List of decoded messages.
Processes :obj:`data`, which must be a bytes-like object,
and returns a (possibly empty) list with :class:`bytes` objects,
each containing a decoded message.
Any non-terminated SLIP packets in :obj:`data`
are buffered, and process... |
371,095 | def get_secret(self, filename, secret, type_=None):
if filename not in self.data:
return None
if type_:
tmp_secret = PotentialSecret(type_, filename, secret=)
tmp_secret.secret_hash = secret
if tmp_secret in self.data[f... | Checks to see whether a secret is found in the collection.
:type filename: str
:param filename: the file to search in.
:type secret: str
:param secret: secret hash of secret to search for.
:type type_: str
:param type_: type of secret, if known.
:rtype: Potent... |
371,096 | def requestMapIdentity(self, subject, vendorSpecific=None):
response = self.requestMapIdentityResponse(subject, vendorSpecific)
return self._read_boolean_response(response) | See Also: requestMapIdentityResponse()
Args:
subject:
vendorSpecific:
Returns: |
371,097 | def get_scores(self, *args):
t used, since this information is taken
directly from the corpus categories.
Returns
-------
np.array, scores
category namenot category namecatncat')
return scores | In this case, args aren't used, since this information is taken
directly from the corpus categories.
Returns
-------
np.array, scores |
371,098 | def link(self, link, title, text):
if self.anonymous_references:
underscore =
else:
underscore =
if title:
return self._raw_html(
.format(
link=link, title=title, text=text
)
)
... | Rendering a given link with content and title.
:param link: href link for ``<a>`` tag.
:param title: title content for `title` attribute.
:param text: text content for description. |
371,099 | def _include_environment_variables(self, program, executor_vars):
env_vars = {
: self.settings_actual.get(, ),
}
set_env = self.settings_actual.get(, {}).get(, {})
env_vars.update(executor_vars)
env_vars.update(set_env)
export_commands = [.format(ke... | Define environment variables. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.