Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
345,700 | def display_image_bytes(b, filename=None, inline=1, width=,
height=, preserve_aspect_ratio=None):
sys.stdout.buffer.write(image_bytes(b, filename=filename, inline=inline,
width=width, height=height, preserve_aspect_ratio=preserve_aspect_ratio))
sys.stdout.write() | Display the image given by the bytes b in the terminal.
If filename=None the filename defaults to "Unnamed file".
width and height are strings, following the format
N: N character cells.
Npx: N pixels.
N%: N percent of the session's width or height.
'auto': The image's inhe... |
345,701 | def enable_aliases_autocomplete_interactive(_, **kwargs):
subtree = kwargs.get(, None)
if not subtree or not hasattr(subtree, ):
return
for alias, alias_command in filter_aliases(get_alias_table()):
if subtree.in_tree(alias_command.split()):
subtree.add_child(Comma... | Enable aliases autocomplete on interactive mode by injecting aliases in the command tree. |
345,702 | def showref():
refdata = getref()
for k, v in refdata.items():
print("%10s: %s" % (k,v)) | Like :func:`getref` but print results to screen instead of returning
a dictionary. |
345,703 | def as_dict(self):
d = {"@module": self.__class__.__module__,
"@class": self.__class__.__name__}
d["structure"] = self.structure
d["energy"] = self.energy
d["miller_index"] = self.miller_index
d["label"] = self.label
d["coverage"] = self.coverage
... | Returns dict which contains Slab Entry data. |
345,704 | def items_purchased(self, category=None):
return self._items(commerce.Cart.STATUS_PAID, category=category) | Aggregates the items that this user has purchased.
Arguments:
category (Optional[models.inventory.Category]): the category
of items to restrict to.
Returns:
[ProductAndQuantity, ...]: A list of product-quantity pairs,
aggregating like products fr... |
345,705 | def get_last_or_frame_exception():
try:
if inspect.istraceback(sys.last_traceback):
return sys.last_type, sys.last_value, sys.last_traceback
except AttributeError:
pass
return sys.exc_info() | Intended to be used going into post mortem routines. If
sys.last_traceback is set, we will return that and assume that
this is what post-mortem will want. If sys.last_traceback has not
been set, then perhaps we *about* to raise an error and are
fielding an exception. So assume that sys.exc_info()[2]
... |
345,706 | def convert_sent_to_conll(sent_ls: List[Extraction]):
assert(len(set([ex.sent for ex in sent_ls])) == 1)
toks = sent_ls[0].sent.split()
return safe_zip(*[range(len(toks)),
toks] + \
[extraction_to_conll(ex)
for ex in sent_ls]) | Given a list of extractions for a single sentence -
convert it to conll representation. |
345,707 | def _wrap_callback_parse_time_info(subscription, on_data, message):
if message.type == message.REPLY:
time_response = web_pb2.TimeSubscriptionResponse()
time_response.ParseFromString(message.reply.data)
time = parse_isostring(time_response.timeInfo.currentTimeUTC)
subsc... | Wraps a user callback to parse TimeInfo
from a WebSocket data message |
345,708 | def git_branch_rename(new_name):
curr_name = git.current_branch(refresh=True).name
if curr_name not in git.protected_branches():
log.info("Renaming branch from <33>{}<32> to <33>{}".format(
curr_name, new_name
))
shell.run(.format(new_name)) | Rename the current branch
Args:
new_name (str):
New name for the current branch. |
345,709 | def rels_xml_for(self, source_uri):
try:
rels_xml = self.blob_for(source_uri.rels_uri)
except IOError:
rels_xml = None
return rels_xml | Return rels item XML for source with *source_uri*, or None if the
item has no rels item. |
345,710 | def get_true_anomaly(self):
self.f = _rsky._getf(self.t_supersample, self.t0, self.per, self.a,
self.inc*pi/180., self.ecc, self.w*pi/180.,
self.transittype, self.nthreads)
return self.f | Return the true anomaly at each time |
345,711 | def check_temperature_sensors():
env_temp = walk_data(sess, oid_env_temp, helper)[0]
env_temp_thresh = walk_data(sess, oid_env_temp_thres, helper)[0]
env_temp_zipped = zip(env_temp, env_temp_thresh)
for x, data in enumerate(env_temp_zipped, 1):
if not in data and not i... | Check all temperature sensors of the server
All sensors with the value or threshold is -99 or 0 are ignored |
345,712 | def prepare_object(obj, using="default"):
model = obj.__class__
unified_index = connections[using].get_unified_index()
index = unified_index.get_index(model)
prepped_data = index.full_prepare(obj)
final_data = {}
for key, value in prepped_data.items():
final_data[key] = connections[... | Returns a Python dictionary representation of the given object, expected to
be a Model object with an associated SearchIndex. The optional argument
`using` specifies the backend to use from the Haystack connections list. |
345,713 | def valid(self, value, level=[]):
self.validation_failures = []
if value is None and self._optional:
return True
for i in range(len(self._nodes)):
return False | Valid
Checks if a value is valid based on the instance's values
Arguments:
value {mixed} -- The value to validate
Returns:
bool |
345,714 | def tcmap(self):
tcmap = dd(list)
for concept in self.__concept_map.values():
for w in concept.tokens:
tcmap[w].append(concept)
return tcmap | Create a tokens-concepts map |
345,715 | def launch_browser(self, soup):
with tempfile.NamedTemporaryFile(delete=False, suffix=) as file:
file.write(soup.encode())
webbrowser.open( + file.name) | Launch a browser to display a page, for debugging purposes.
:param: soup: Page contents to display, supplied as a bs4 soup object. |
345,716 | def authorize(self, cidr_ip=None, ec2_group=None):
if isinstance(ec2_group, SecurityGroup):
group_name = ec2_group.name
group_owner_id = ec2_group.owner_id
else:
group_name = None
group_owner_id = None
return self.connection.authorize_dbse... | Add a new rule to this DBSecurity group.
You need to pass in either a CIDR block to authorize or
and EC2 SecurityGroup.
@type cidr_ip: string
@param cidr_ip: A valid CIDR IP range to authorize
@type ec2_group: :class:`boto.ec2.securitygroup.SecurityGroup>`
@rtype: bool... |
345,717 | def fetch(self, country_code=values.unset, type=values.unset,
add_ons=values.unset, add_ons_data=values.unset):
params = values.of({
: country_code,
: serialize.map(type, lambda e: e),
: serialize.map(add_ons, lambda e: e),
})
params.up... | Fetch a PhoneNumberInstance
:param unicode country_code: The ISO country code of the phone number
:param unicode type: The type of information to return
:param unicode add_ons: The unique_name of an Add-on you would like to invoke
:param dict add_ons_data: Data specific to the add-on yo... |
345,718 | def detect_and_decorate(decorator, args, kwargs):
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
return decorator(args[0])
elif len(args) != 0:
raise ValueError("this decorator cannot take positional args")
else:
... | Helper for applying a decorator when it is applied directly, and also
applying it when it is given arguments and then applied to a function. |
345,719 | def _low_level_execute_command(self, cmd, sudoable=True, in_data=None,
executable=None,
encoding_errors=,
chdir=None):
LOG.debug(,
cmd, type(in_data), executable, chdir)
if... | Override the base implementation by simply calling
target.exec_command() in the target context. |
345,720 | def relative_ref(*parts):
def relative_ref(_value, context, **_params):
return reference.Relative(*(parts + (context["key"], )))
return relative_ref | Create a reference builder with specified relative location.
using getter.relative_ref("some", "submodel") to get a value with key
"toto" will gives reference.Relative("some", "submodel", "toto") |
345,721 | def on_rapidjson_dumps(self, rapidjson, config, dictionary, **kwargs):
return rapidjson.dumps(dictionary, **kwargs) | The `rapidjson <https://pypi.org/project/python-rapidjson/>`_ dumps method.
:param module rapidjson: The ``rapidjson`` module
:param class config: The instance's config class
:param dict dictionary: The dictionary instance to serialize
:param int indent: The amount of spaces to use for ... |
345,722 | def map_df(self, df):
if (len(df) == 0) or (len(self) == 0):
return df
for sc in self:
df = sc.map_df(df)
return df | Map values from a dataframe.
Returns dataframe |
345,723 | def _rescale(vector):
min_val = min(vector)
vector = [v - min_val for v in vector]
max_val = float(max(vector))
try:
return [v / max_val for v in vector]
except ZeroDivisionError:
return [1.0] * len(vector) | Scale values in vector to the range [0, 1].
Args:
vector: A list of real values. |
345,724 | def _set_periodic_transmission_machine_state(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u... | Setter method for periodic_transmission_machine_state, mapped from YANG variable /brocade_lag_rpc/get_portchannel_info_by_intf/output/lacp/periodic_transmission_machine_state (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_periodic_transmission_machine_state is con... |
345,725 | def calculate_angular_momentum(self):
clibrebound.reb_tools_angular_momentum.restype = reb_vec3d
L = clibrebound.reb_tools_angular_momentum(byref(self))
return [L.x, L.y, L.z] | Returns a list of the three (x,y,z) components of the total angular momentum of all particles in the simulation. |
345,726 | def _get_indices(self, element, labels=, mode=):
r
element = self._parse_element(element, single=True)
labels = self._parse_labels(labels=labels, element=element)
if element+ not in self.keys():
raise Exception(.format(element))
if mode in [, , ]:
... | r"""
This is the actual method for getting indices, but should not be called
directly. Use ``pores`` or ``throats`` instead. |
345,727 | def _compute_focal_depth_term(self, C, rup):
if rup.hypo_depth > 120.0:
z_h = 120.0
else:
z_h = rup.hypo_depth
return C[] * (z_h - 60.) | Computes the hypocentral depth scaling term - as indicated by
equation (3) |
345,728 | def __walk_rec(self, top, rec):
if not rec or os.path.islink(top) or not os.path.isdir(top):
yield top
else:
for root, dirs, files in os.walk(top):
yield root | Yields each subdirectories of top, doesn't follow symlinks.
If rec is false, only yield top.
@param top: root directory.
@type top: string
@param rec: recursive flag.
@type rec: bool
@return: path of one subdirectory.
@rtype: string |
345,729 | def download(self, filename, action=, x_filename=, x_sendfile=None, real_filename=):
from uliweb import request
from uliweb.utils.common import safe_str
from uliweb.utils.filedown import filedown
s = settings.GLOBAL
action = request.GET.get(, action)
... | action will be "download", "inline"
and if the request.GET has 'action', then the action will be replaced by it. |
345,730 | def umi_transform(data):
fq1 = data["files"][0]
umi_dir = os.path.join(dd.get_work_dir(data), "umis")
safe_makedir(umi_dir)
transform = dd.get_umi_type(data)
if not transform:
logger.info("No UMI transform specified, assuming pre-transformed data.")
if is_transformed(fq1):
... | transform each read by identifying the barcode and UMI for each read
and putting the information in the read name |
345,731 | def d2attrs(*args, **kwargs):
(d, self), args = args[:2], args[2:]
if args[0] == :
assert len(args) == 1
for k in d: setattr(self, k, d[k])
else:
if len(args) != len(set(args)) or set(kwargs) & set(args):
raise ValueError( %
list(notUniqu... | Utility function to remove ``**kwargs`` parsing boiler-plate in
``__init__``:
>>> kwargs = dict(name='Bill', age=51, income=1e7)
>>> self = ezstruct(); d2attrs(kwargs, self, 'income', 'name'); self
ezstruct(income=10000000.0, name='Bill')
>>> self = ezstruct(); d2attrs(kwargs, se... |
345,732 | def extract_prefix(self, prefix):
field = re.match(PREFIX_REG, prefix if prefix else )
return (prefix,) if not field else field.group(1, 2, 3) | It extracts an irc msg prefix chunk |
345,733 | def switch_psm_to_peptable_fields(oldheader):
return {old: new for old, new in zip([mzidtsvdata.HEADER_PEPTIDE,
mzidtsvdata.HEADER_PROTEIN,
mzidtsvdata.HEADER_PEPTIDE_Q,
mzidtsvdata.HEA... | Returns a dict map with old to new header fields |
345,734 | def close(self):
self.read_queue.put(QueueClosed)
self.write_queue.put(QueueClosed) | Close the queue, signalling that no more data can be put into the queue. |
345,735 | def pull(self, remote="origin", ref=None):
return git_pull(self.repo_dir, remote=remote, ref=ref) | Do a git pull of `ref` from `remote`. |
345,736 | def right_model_factory(*, validator=validators.is_right_model,
ld_type=, **kwargs):
return _model_factory(validator=validator, ld_type=ld_type, **kwargs) | Generate a Right model.
Expects ``data``, ``validator``, ``model_cls``, ``ld_type``, and
``ld_context`` as keyword arguments. |
345,737 | def pre_delete_title(instance, **kwargs):
if instance.article.languages:
languages = instance.article.languages.split()
else:
languages = []
if instance.language in languages:
languages.remove(instance.language)
instance.article.languages = .join(languages)
insta... | Update article.languages |
345,738 | def singlecat(data, sample, bseeds, sidx, nloci):
LOGGER.info("in single cat here")
isref = in data.paramsdict["assembly_method"]
with h5py.File(bseeds, ) as io5:
hits = io5["uarr"][:]
hits = hits[hits[:, 1] == sidx, :]
seeds = io5["seedsa... | Orders catg data for each sample into the final locus order. This allows
all of the individual catgs to simply be combined later. They are also in
the same order as the indels array, so indels are inserted from the indel
array that is passed in. |
345,739 | def _setup_xauth(self):
handle, filename = tempfile.mkstemp(prefix=,
suffix=)
self._xauth_filename = filename
os.close(handle)
self._old_xauth = {}
self._old_xauth[] = os.getenv()
self._old_xauth[] = os.getenv(... | Set up the Xauthority file and the XAUTHORITY environment variable. |
345,740 | def from_path(path):
if os.path.isdir(path):
return DirectoryInfo(path)
if os.path.isfile(path):
return FileInfo(path)
return None | create from path.
return `None` if path is not exists. |
345,741 | def tyn_calus(target, VA, VB, sigma_A, sigma_B, temperature=,
viscosity=):
r
T = target[temperature]
mu = target[viscosity]
A = 8.93e-8*(VB*1e6)**0.267/(VA*1e6)**0.433*T
B = (sigma_B/sigma_A)**0.15/(mu*1e3)
value = A*B
return value | r"""
Uses Tyn_Calus model to estimate diffusion coefficient in a dilute liquid
solution of A in B from first principles at conditions of interest
Parameters
----------
target : OpenPNM Object
The object for which these values are being calculated. This
controls the length of the ca... |
345,742 | def set_message_ref(self, value):
if value is None:
self.__message_ref = value
if not isinstance(value, str):
raise TypeError("MessageRef must be set to a String")
else:
self.__message_ref = value | Setter for 'message_ref' field.
:param value - a new value of 'message_ref' field. Must be either None (message_ref is optional according to
BPMN 2.0 XML Schema) or String. |
345,743 | def build_graph(self, image, label):
image = tf.expand_dims(image, 3)
image = image * 2 - 1
with argscope(Conv2D, kernel_size=3, activation=tf.nn.relu, filters=32):
logits = (LinearWrap(image)
.Conv2D()
... | This function should build the model which takes the input variables
and return cost at the end |
345,744 | def drop_all(self, check_first: bool = True):
self._metadata.drop_all(self.engine, checkfirst=check_first)
self._store_drop() | Drop all tables from the database.
:param bool check_first: Defaults to True, only issue DROPs for tables confirmed to be
present in the target database. Defers to :meth:`sqlalchemy.sql.schema.MetaData.drop_all` |
345,745 | def parse_verilog(text):
lex = VerilogLexer
name = None
kind = None
saved_type = None
mode =
ptype =
metacomments = []
parameters = []
param_items = []
generics = []
ports = collections.OrderedDict()
sections = []
port_param_index = 0
last_item = None
array_range_start_pos = 0
o... | Parse a text buffer of Verilog code
Args:
text (str): Source code to parse
Returns:
List of parsed objects. |
345,746 | def delete_config(self, media):
if not isinstance(media, list):
raise TypeError("media can only be an instance of type list")
for a in media[:10]:
if not isinstance(a, IMedium):
raise TypeError(
"array can only contain objects of t... | Deletes the files associated with this machine from disk. If medium objects are passed
in with the @a aMedia argument, they are closed and, if closing was successful, their
storage files are deleted as well. For convenience, this array of media files can be
the same as the one returned from a pr... |
345,747 | def createRecordSensor(network, name, dataSource):
regionType = "py.RecordSensor"
regionParams = json.dumps({"verbosity": _VERBOSITY})
network.addRegion(name, regionType, regionParams)
sensorRegion = network.regions[name].getSelf()
sensorRegion.encoder = createEncoder()
network.region... | Creates a RecordSensor region that allows us to specify a file record
stream as the input source. |
345,748 | def command(self, request_type, uri, payload):
self.command_count += 1
if payload is None:
payload = {}
message = {
: "{}_{}".format(type, self.command_count),
: request_type,
: "ssap://{}".format(uri),
: payload,
}
... | Build and send a command. |
345,749 | def path(self, include_root=False):
path = % (self.tagname, self.index or 0)
p = self.parent
while p is not None:
if p.parent or include_root:
path = % (p.tagname, p.index or 0, path)
p = p.parent
return path | Returns a canonical path to this element, relative to the root node.
:param include_root: If ``True``, include the root node in the path. Defaults to ``False``. |
345,750 | def _register_extensions(self, namespace):
extmanager = ExtensionManager(
.format(namespace),
propagate_map_exceptions=True
)
if extmanager.extensions:
extmanager.map(util.register_extension_class, base=self)
extmanager = ... | Register any extensions under the given namespace. |
345,751 | def from_bytes(cls, bitstream):
packet = cls()
if not isinstance(bitstream, ConstBitStream):
if isinstance(bitstream, Bits):
bitstream = ConstBitStream(auto=bitstream)
else:
bitstream = ConstBitStream(bytes=bitstream)
... | Parse the given packet and update properties accordingly |
345,752 | def list_jobs(self, project):
url = self._build_url(constants.LIST_JOBS_ENDPOINT)
params = {: project}
jobs = self.client.get(url, params=params, timeout=self.timeout)
return jobs | Lists all known jobs for a project. First class, maps to Scrapyd's
list jobs endpoint. |
345,753 | def imbalance_check(P):
p_list = list(P.values())
max_value = max(p_list)
min_value = min(p_list)
if min_value > 0:
balance_ratio = max_value / min_value
else:
balance_ratio = max_value
is_imbalanced = False
if balance_ratio > BALANCE_RATIO_THRESHOLD:
is_imbalanc... | Check if the dataset is imbalanced.
:param P: condition positive
:type P : dict
:return: is_imbalanced as bool |
345,754 | def link_to_dashboard(self, dashboard_id=None, panel_id=None, **kwargs):
r
KerviComponent.link_to_dashboard(
self,
dashboard_id,
panel_id,
**kwargs
) | r"""
Links this value to a dashboard panel.
:param dashboard_id:
Id of the dashboard to link to.
:type dashboard_id: str
:param panel_id:
Id of the panel on the dashboard to link to.
:type panel_id: str
:param \**kwargs:
Use ... |
345,755 | def _insertions(self, result, dimension, dimension_index):
def iter_insertions():
for anchor_idx, addend_idxs in dimension.hs_indices:
insertion_idx = (
-1
if anchor_idx == "top"
else result.shape[dimension_index] ... | Return list of (idx, sum) pairs representing subtotals.
*idx* is the int offset at which to insert the ndarray subtotal
in *sum*. |
345,756 | def write_tmp_i3status_config(self, tmpfile):
for module in self.py3_config["i3s_modules"]:
self.write_in_tmpfile( % module, tmpfile)
self.write_in_tmpfile("\n", tmpfile)
for section_name in ["general"] + self.py3_config["i3s_modules"]:
section ... | Given a temporary file descriptor, write a valid i3status config file
based on the parsed one from 'i3status_config_path'. |
345,757 | def re_pipe(FlowRate, Diam, Nu):
ut.check_range([FlowRate, ">0", "Flow rate"], [Diam, ">0", "Diameter"],
[Nu, ">0", "Nu"])
return (4 * FlowRate) / (np.pi * Diam * Nu) | Return the Reynolds Number for a pipe. |
345,758 | def __get_ssh_credentials(vm_):
ssh_user = config.get_cloud_config_value(
, vm_, __opts__, default=os.getenv())
ssh_key = config.get_cloud_config_value(
, vm_, __opts__,
default=os.path.expanduser())
return ssh_user, ssh_key | Get configured SSH credentials. |
345,759 | def runtimepath(self):
if self._runtimepath is None:
self._runtimepath = runtimepath.RuntimePath(self)
return self._runtimepath | :return: runtime path of *Vim*
:rtype: runtimepath.RuntimePath |
345,760 | def data_period_start_day(self, value=None):
if value is not None:
try:
value = str(value)
except ValueError:
raise ValueError(
.format(value))
if in value:
raise ValueError(
... | Corresponds to IDD Field `data_period_start_day`
Args:
value (str): value for IDD Field `data_period_start_day`
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value... |
345,761 | def rasterize(self,
pitch,
origin,
resolution=None,
fill=True,
width=None,
**kwargs):
image = raster.rasterize(self,
pitch=pitch,
... | Rasterize a Path2D object into a boolean image ("mode 1").
Parameters
------------
pitch: float, length in model space of a pixel edge
origin: (2,) float, origin position in model space
resolution: (2,) int, resolution in pixel space
fill: bool, if True wi... |
345,762 | def contains_text_tokens(self, text_tokens):
id_run = []
for token in text_tokens:
id = self.word_list.get(token, None)
if id is None:
return False
id_run.append(id)
return self.contains_tokens(id_run) | Returns true if a phrase in the dictionary matches the list of text tokens
:param text_tokens: a list of tokens. Each token a string of text.
:return: True/False |
345,763 | def audit(**kwargs):
def wrap(fn):
@functools.wraps(fn)
def advice(parent_object, *args, **kw):
request = parent_object.request
wijziging = request.audit_manager.create_revision()
result = fn(parent_object, *args, **kw)
if hasattr(request, ) a... | use this decorator to audit an operation |
345,764 | def create_maintenance_window(self, **kwargs):
kwargs[] = True
if kwargs.get():
return self.create_maintenance_window_with_http_info(**kwargs)
else:
(data) = self.create_maintenance_window_with_http_info(**kwargs)
return data | Create a maintenance window # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_maintenance_window(async_req=True)
>>> result = thread.get()
:param... |
345,765 | def get_event(self, name, default=_sentinel):
if name not in self.events:
if self.create_events_on_access:
self.add_event(name)
elif default is not _sentinel:
return default
return self.events[name] | Lookup an event by name.
:param str item: Event name
:return Event: Event instance under key |
345,766 | def generate_or_read_from_file(key_file=, key_length=64):
abspath = os.path.abspath(key_file)
if os.path.exists(key_file):
key = read_from_file(key_file)
return key
lock = lockutils.external_lock(key_file + ".lock",
lock_path=os.path.di... | Multiprocess-safe secret key file generator.
Useful to replace the default (and thus unsafe) SECRET_KEY in settings.py
upon first start. Save to use, i.e. when multiple Python interpreters
serve the dashboard Django application (e.g. in a mod_wsgi + daemonized
environment). Also checks if file permiss... |
345,767 | def median(items):
items.sort()
k = len(items)//2
if len(items) % 2 == 0:
return (items[k] + items[k - 1]) / 2
else:
return items[k] | Note: modifies the input list! |
345,768 | def iter_issues(self,
milestone=None,
state=None,
assignee=None,
mentioned=None,
labels=None,
sort=None,
direction=None,
since=None,
number=... | Iterate over issues on this repo based upon parameters passed.
.. versionchanged:: 0.9.0
The ``state`` parameter now accepts 'all' in addition to 'open'
and 'closed'.
:param int milestone: (optional), 'none', or '*'
:param str state: (optional), accepted values: ('all'... |
345,769 | def _create_graph(self, return_target_sources=None):
if return_target_sources is None:
return_target_sources = defaultdict(list)
cfg = networkx.DiGraph()
if len(self._nodes) == 1:
cfg.add_node(self._nodes[next(iter(self._nodes.... | Create a DiGraph out of the existing edge map.
:param return_target_sources: Used for making up those missing returns
:returns: A networkx.DiGraph() object |
345,770 | def edit(ctx, file_to_edit, previous_file):
timesheet_collection = None
autofill = not bool(file_to_edit) and previous_file == 0
if not file_to_edit:
file_to_edit = ctx.obj[].get_entries_file_path(False)
expanded_file_to_edit = list(timesheet_files)[previous_file]
editor = ctx.o... | Opens your timesheet file in your favourite editor.
The PREVIOUS_FILE argument can be used to specify which nth previous file
to edit. A value of 1 will edit the previous file, 2 will edit the
second-previous file, etc. |
345,771 | def get_function_from_config(item):
config = get_configuration()
func_path = config.get(item)
module_path, func_name = func_path.rsplit(".", 1)
module = importlib.import_module(module_path)
func = getattr(module, func_name)
return func | Import the function to get profile by handle. |
345,772 | def get_path(element):
path = {}
path[] = element[]
grouped_list = groupby(element[])
path[] = [group[0] for group in grouped_list]
if in element:
for useful_tag in settings.useful_tags_path:
if useful_tag in element[]:
path[useful_tag] = element[][u... | Convert an OSM way element into the format for a networkx graph path.
Parameters
----------
element : dict
an OSM way element
Returns
-------
dict |
345,773 | def get_kde_contour(self, xax="area_um", yax="deform", xacc=None,
yacc=None, kde_type="histogram", kde_kwargs={},
xscale="linear", yscale="linear"):
xax = xax.lower()
yax = yax.lower()
kde_type = kde_type.lower()
if kde_type not in... | Evaluate the kernel density estimate for contour plots
Parameters
----------
xax: str
Identifier for X axis (e.g. "area_um", "aspect", "deform")
yax: str
Identifier for Y axis
xacc: float
Contour accuracy in x direction
yacc: float
... |
345,774 | def chgid(name, gid):
*
pre_gid = __salt__[](name)
if gid == pre_gid:
return True
cmd = .format(gid, name)
__salt__[](cmd, python_shell=False)
post_gid = __salt__[](name)
if post_gid != pre_gid:
return post_gid == gid
return False | Change the gid for a named group
CLI Example:
.. code-block:: bash
salt '*' group.chgid foo 4376 |
345,775 | def substitute_array(a, d):
a = np.asarray(a, order="C")
return np.array([substitute(v, d) for v in a.flat]).reshape(a.shape) | Apply ``substitute`` to all elements of an array ``a`` and return the resulting array.
:param Union[np.array,List] a: The expression array to substitute.
:param Dict[Parameter,Union[int,float]] d: Numerical substitutions for parameters.
:return: An array of partially substituted Expressions or numbers.
... |
345,776 | def _use_private_key(
self,
client_certchain_file: str,
client_key_file: str,
client_key_type: OpenSslFileTypeEnum,
client_key_password: str
) -> None:
with open(client_certchain_file):
pass
with open(client_ke... | The certificate chain file must be in PEM format. Private method because it should be set via the
constructor. |
345,777 | def classify(self, dataset, missing_value_action=):
return super(LogisticClassifier, self).classify(dataset,
missing_value_action=missing_value_action) | Return a classification, for each example in the ``dataset``, using the
trained logistic regression model. The output SFrame contains predictions
as both class labels (0 or 1) as well as probabilities that the predicted
value is the associated label.
Parameters
----------
... |
345,778 | def toy_linear_1d_classification_laplace(seed=default_seed, optimize=True, plot=True):
try:import pods
except ImportError:print()
data = pods.datasets.toy_linear_1d_classification(seed=seed)
Y = data[][:, 0:1]
Y[Y.flatten() == -1] = 0
likelihood = GPy.likelihoods.Bernoulli()
laplace_i... | Simple 1D classification example using Laplace approximation
:param seed: seed value for data generation (default is 4).
:type seed: int |
345,779 | def get_metadata_as_csv(fname):
q = chr(34)
d = ","
res = q + fname + q + d
res = res + q + os.path.basename(fname) + q + d
res = res + q + os.path.dirname(fname) + q + d
try:
res = res + q + str(os.path.getsize(fname)) + q + d
img = Image.open(fname)
return res | Gets all metadata and puts into CSV format |
345,780 | def ints2str(self, int_values):
if not self._encoder:
raise ValueError(
"Text.ints2str is not available because encoder hasn't been defined.")
return self._encoder.decode(int_values) | Conversion list[int] => decoded string. |
345,781 | def _elidable_end(self, word):
if str(word[-1]).endswith():
return True
elif str(word[-1][-1]) in self.long_vowels:
return True
elif str(word[-1][-2] + word[-1][-1]) in self.diphthongs:
return True
elif str(word[-1][-1]) in self.vowels:
... | Check word ending to see if it is elidable. Elidable endings include:
1) A word ends with 'm'
2) A word ends with a vowel
3) A word ends with a diphthong
:param word: syllabified/'qu' fixed word
:return: True if the ending of the word is elidable, otherwise False
:rtype :... |
345,782 | def Client(version=__version__, resource=None, provider=None, **kwargs):
versions = _CLIENTS.keys()
if version not in versions:
raise exceptions.UnsupportedVersion(
)
if provider is None:
raise exceptions.ProviderNotDefined(
)
support_ty... | Initialize client object based on given version.
:params version: version of CAL, define at setup.cfg
:params resource: resource type
(network, compute, object_storage, block_storage)
:params provider: provider object
:params cloud_config: cloud auth config
:params **kwargs: sp... |
345,783 | def slug(self):
identifier = ""
millis = int(time.time() * 1000)
millis_string = _to_base36(millis)
identifier += millis_string[-2:]
count = _pad(_to_base36(self.counter), 1)
identifier += count
identifier += self.fingerprint[0]... | Generate a short (7-character) cuid as a bytestring.
While this is a convenient shorthand, this is much less likely
to be unique and should not be relied on. Prefer full-size
cuids where possible. |
345,784 | def draw_pegasus_embedding(G, *args, **kwargs):
crosses = kwargs.pop("crosses", False)
draw_embedding(G, pegasus_layout(G, crosses=crosses), *args, **kwargs) | Draws an embedding onto the pegasus graph G, according to layout.
If interaction_edges is not None, then only display the couplers in that
list. If embedded_graph is not None, the only display the couplers between
chains with intended couplings according to embedded_graph.
Parameters
----------
... |
345,785 | def get_model_columns(model, fields=None, meta=):
from copy import deepcopy
fields = fields or []
model = functions.get_model(model)
if not fields:
if hasattr(model, meta):
fields = getattr(model, meta).fields
else:
fields = [x for x, y in model.... | Get fields info according model class, the fields just like ListView fields definition
:param fields: A list
:param meta: if no fields, it'll use meta |
345,786 | def getProperty(self, key, strip=True):
self.__checkTransport()
import collections
MAP_PROPS = collections.OrderedDict([
(re.compile(), self.__getDisplayWidth),
(re.compile(), self.__getDisplayHeight),
(re.compile(), self.__getDisplayDensity),
... | Gets the property value for key |
345,787 | def signed_session(self, session=None):
from sfctl.config import (aad_metadata, aad_cache)
if session:
session = super(AdalAuthentication, self).signed_session(session)
else:
session = super(AdalAuthentication, self).signed_session()
if self.no_verify:... | Create requests session with AAD auth headers
:rtype: requests.Session. |
345,788 | def tty(tty_reload):
tty_script = os.path.join(CACHE_DIR, "colors-tty.sh")
term = os.environ.get("TERM")
if tty_reload and term == "linux":
subprocess.Popen(["sh", tty_script]) | Load colors in tty. |
345,789 | def try_component(self, entity: int, component_type: Type):
if component_type in self._entities[entity]:
yield self._entities[entity][component_type]
else:
return None | Try to get a single component type for an Entity.
This method will return the requested Component if it exists, but
will pass silently if it does not. This allows a way to access optional
Components that may or may not exist.
:param entity: The Entity ID to ... |
345,790 | def det(matrix):
d version
size = len(matrix)
if size == 1:
return matrix[0]
elif size == 2:
(a, b), (c, d) = matrix
return a*d - c*b
elif size == 3:
(a, b, c), (d, e, f), (g, h, i) = matrix
return a*(e*i - h*f) - d*(b*i - h*c) + g*(b*f - e*c)
elif size ==... | Seem sto work fine.
>> from sympy import *
>> from sympy.abc import *
>> Matrix([[a, b], [c, d]]).det()
a*d - b*c
>> Matrix([[a, b, c], [d, e, f], [g, h, i]]).det()
a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g
A few terms can be slightly factored out of the 3x dim.
>> Mat... |
345,791 | def t_asm_CONTINUE(self, t):
r
t.lexer.lineno += 1
t.value = t.value[1:]
return t | r'[\\_]\r?\n |
345,792 | def create_destination(flowable, container, at_top_of_container=False):
vertical_position = 0 if at_top_of_container else container.cursor
ids = flowable.get_ids(container.document)
destination = NamedDestination(*(str(id) for id in ids))
container.canvas.annotate(destination, 0, vertical_position,... | Create a destination anchor in the `container` to direct links to
`flowable` to. |
345,793 | def _cleanup(self):
self._ack_listener = None
self._nack_listener = None
self._broker_cancel_cb_map = None
super(RabbitBasicClass, self)._cleanup() | Cleanup all the local data. |
345,794 | def _guessEncoding(self, path):
if os.path.exists(path) and path.lower().endswith():
encoding = None
if encoding is not None:
if encoding.startswith():
encoding = encoding.replace(, )
encoding = encoding.replace(,... | Opens a file from the given `path` and checks the file encoding.
The file must exists on the file system and end with the extension
`.csv`. The file is read line by line until the encoding could be
guessed.
On a successfull identification, the widgets of this dialog will be
upda... |
345,795 | def sendLocalFiles(
self, file_paths, message=None, thread_id=None, thread_type=ThreadType.USER
):
file_paths = require_list(file_paths)
with get_files_from_paths(file_paths) as x:
files = self._upload(x)
return self._sendFiles(
files=files, message=m... | Sends local files to a thread
:param file_paths: Paths of files to upload and send
:param message: Additional message
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:r... |
345,796 | def describe_delta(delta):
s = delta.total_seconds()
s = abs(s)
hours, remainder = divmod(s, 3600)
minutes, seconds = divmod(remainder, 60)
if hours:
return % (hours, minutes)
if minutes:
return % (minutes, seconds)
return % seconds | Describe this timedelta in human-readable terms.
:param delta: datetime.timedelta object
:returns: str, describing this delta |
345,797 | def profile_tf_runningmeanstd():
import time
from baselines.common import tf_util
tf_util.get_session( config=tf.ConfigProto(
inter_op_parallelism_threads=1,
intra_op_parallelism_threads=1,
allow_soft_placement=True
))
x = np.random.random((376,))
n_trials = 10000
... | options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) #pylint: disable=E1101
run_metadata = tf.RunMetadata()
profile_opts = dict(options=options, run_metadata=run_metadata)
from tensorflow.python.client import timeline
fetched_timeline = timeline.Timeline(run_metadata.step_stats) #pylint: dis... |
345,798 | def get_tilting(self, oplane):
surf_atom1, surf_atom2, surf_atom3, surf_atom4 = oplane
compare = [surf_atom2, surf_atom3, surf_atom4]
distance_map = []
for i in range(0, 3):
distance_map.append([ compare[i], self.virtual_atoms.get_distance(surf_atom1, comp... | Main procedure |
345,799 | def smtp_connection(c):
if c.smtp_ssl:
klass = smtplib.SMTP_SSL
else:
klass = smtplib.SMTP
conn = klass(c.smtp_host, c.smtp_port, timeout=c.smtp_timeout)
if not c.smtp_ssl:
conn.ehlo()
conn.starttls()
conn.ehlo()
if c.smtp_username:
conn.login(c.s... | Create an SMTP connection from a Config object |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.