Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
354,900 | def export(self, output_folder):
if not os.path.exists(output_folder):
os.makedirs(output_folder)
self._interact_with_folder(output_folder, ) | Export matrices as ``*.npy`` files to an output folder. |
354,901 | def _remote_github_url_to_string(remote_url):
match = re.search(, remote_url)
if not match:
raise EnvironmentError()
identifier = match.group(1)
return re.sub(, , identifier) | Parse out the repository identifier from a github URL. |
354,902 | def getexptimeimg(self,chip):
sci_chip = self._image[self.scienceExt,chip]
if sci_chip._wtscl_par == :
wtscl = sci_chip._exptime*sci_chip._exptime
else:
wtscl = sci_chip._exptime
return np.ones(sci_chip.image_shape,dtype=sci_chip.image_dtype)*wtscl | Notes
=====
Return an array representing the exposure time per pixel for the detector.
This method will be overloaded for IR detectors which have their own
EXP arrays, namely, WFC3/IR and NICMOS images.
:units:
None
Returns
=======
exptimeimg :... |
354,903 | def mass_within_ellipse_in_units(self, major_axis, unit_mass=, kpc_per_arcsec=None, critical_surface_density=None):
if self.has_mass_profile:
return sum(map(lambda p: p.mass_within_ellipse_in_units(major_axis=major_axis, unit_mass=unit_mass,
... | Compute the total angular mass of the galaxy's mass profiles within an ellipse of specified major_axis.
See *profiles.mass_profiles.angualr_mass_within_ellipse* for details of how this is performed.
Parameters
----------
major_axis : float
The major-axis radius of the ellip... |
354,904 | def exists_orm(session: Session,
ormclass: DeclarativeMeta,
*criteria: Any) -> bool:
q = session.query(ormclass)
for criterion in criteria:
q = q.filter(criterion)
exists_clause = q.exists()
return bool_from_exists_clause(session=session,
... | Detects whether a database record exists for the specified ``ormclass``
and ``criteria``.
Example usage:
.. code-block:: python
bool_exists = exists_orm(session, MyClass, MyClass.myfield == value) |
354,905 | def __create_password():
salt = b64encode(API.__generate_string(32))
password = b64encode(API.__generate_string(64))
return b64encode(sha1(password + salt).digest()) | Create a password for the user. |
354,906 | def from_tuple(cls, components: tuple) -> :
component_ref = ComponentRef(name=components[0], child=[])
c = component_ref
for component in components[1:]:
c.child.append(ComponentRef(name=component, child=[]))
c = c.child[0]
return component_ref | Convert the tuple pointing to a component to
a component reference.
:param components: tuple of components name
:return: ComponentRef |
354,907 | def to_python(self, data):
try:
return super(BatmanParser, self).to_python(data)
except ConversionException as e:
return self._txtinfo_to_python(e.data) | Adds support for txtinfo format |
354,908 | def footnote_ref(self, key, index):
html = (
) % (escape(key), escape(key), index)
return html | Rendering the ref anchor of a footnote.
:param key: identity key for the footnote.
:param index: the index count of current footnote. |
354,909 | def custom_result(self, **options):
rslt = Result(self.all_docs, **options)
yield rslt
del rslt | Provides a context manager that can be used to customize the
``_all_docs`` behavior and wrap the output as a
:class:`~cloudant.result.Result`.
:param bool descending: Return documents in descending key order.
:param endkey: Stop returning records at this specified key.
Not v... |
354,910 | def flatten(self) :
if len(self.children) > 1 :
children = self.children
self.emptyChildren()
children[0].emptyChildren()
x1 = children[0].x1
x2 = children[0].x2
refObjs = [children[0].referedObject]
name = children[0].name
for i in range(1, len(children)) :
children[i].emptyChi... | Flattens the tree. The tree become a tree of depth 1 where overlapping regions have been merged together |
354,911 | def _new_pool(self, scheme, host, port, request_context=None):
pool_cls = self.pool_classes_by_scheme[scheme]
if request_context is None:
request_context = self.connection_pool_kw.copy()
for key in (, , ):
request_context.pop(... | Create a new :class:`ConnectionPool` based on host, port, scheme, and
any additional pool keyword arguments.
If ``request_context`` is provided, it is provided as keyword arguments
to the pool class used. This method is used to actually create the
connection pools handed out by :meth:`c... |
354,912 | def check_is_admin(context):
init()
credentials = context.to_policy_values()
target = credentials
return _ENFORCER.authorize(, target, credentials) | Check if roles contains 'admin' role according to policy settings. |
354,913 | def _find_frame_imports(name, frame):
imports = frame.nodes_of_class((astroid.Import, astroid.ImportFrom))
for import_node in imports:
for import_name, import_alias in import_node.names:
if import_alias:
if import_alias == name:
... | Detect imports in the frame, with the required
*name*. Such imports can be considered assignments.
Returns True if an import for the given name was found. |
354,914 | def ports(val, **kwargs):
udp
if not isinstance(val, list):
try:
val = helpers.split(val)
except AttributeError:
if isinstance(val, six.integer_types):
val = [val]
else:
raise SaltInvocationError(
{0}\.form... | Like cap_add, cap_drop, etc., this option can be specified multiple times,
and each time can be a port number or port range. Ultimately, the API
expects a list, but elements in the list are ints when the port is TCP, and
a tuple (port_num, 'udp') when the port is UDP. |
354,915 | def getproject_cmd(argv):
parser = argparse.ArgumentParser(
description="Print an environmentenvname?VIRTUAL_ENVThe name of the environment to return the project directory for. If omitted, will use the currently active environment.ERROR: no virtualenv active{0}{0}'"
.format(args.... | Print a virtualenv's project directory, if set.
If called without providing a virtualenv name as argument, print the
current virtualenv's project directory. |
354,916 | def get_package_version(self, package):
name = "{0}{1}".format(
pelix.remote.PROP_ENDPOINT_PACKAGE_VERSION_, package
)
try:
version = self.__properties[name]
return tuple(version.split("."))
except KeyError:... | Provides the version of the given package name.
:param package: The name of the package
:return: The version of the specified package as a tuple or (0,0,0) |
354,917 | def add_devs_custom_views(custom_view_name, dev_list, auth, url):
view_id = get_custom_views(auth, url, name=custom_view_name)[0][]
add_devs_custom_views_url = +str(view_id)
payload = + json.dumps(dev_list) +
f_url = url + add_devs_custom_views_url
r = requests.put(f_url, data = payload, auth=... | function takes a list of devIDs from devices discovered in the HPE IMC platform and and issues a RESTFUL call to
add the list of devices to a specific custom views from HPE IMC.
:param dev_list: list containing the devID of all devices to be contained in this custom view.
:param auth: requests auth objec... |
354,918 | def installed(name, user, admin_user, admin_password, admin_email, title, url):
s Awesome Blog
- user: apache
- admin_user: dwallace
- admin_email: dwallace@example.com
- admin_password: password123
- url: https://blog.dwallace.com
namechangescommentre... | Run the initial setup of wordpress
name
path to the wordpress installation
user
user that owns the files for the wordpress installation
admin_user
username for wordpress website administrator user
admin_password
password for wordpress website administrator user
a... |
354,919 | def analyze_modules(project, task_handle=taskhandle.NullTaskHandle()):
resources = project.get_python_files()
job_set = task_handle.create_jobset(, len(resources))
for resource in resources:
job_set.started_job(resource.path)
analyze_module(project, resource)
job_set.finished_jo... | Perform static object analysis on all python files in the project
Note that this might be really time consuming. |
354,920 | def chop(self, begin, end, datafunc=None):
insertions = set()
begin_hits = [iv for iv in self.at(begin) if iv.begin < begin]
end_hits = [iv for iv in self.at(end) if iv.end > end]
if datafunc:
for iv in begin_hits:
insertions.add(Interval(iv.begin, b... | Like remove_envelop(), but trims back Intervals hanging into
the chopped area so that nothing overlaps. |
354,921 | def get_device_access_interfaces(auth, url, devid=None, devip=None):
if devip is not None:
devid = get_dev_details(devip, auth, url)[]
get_access_interface_vlan_url = "/imcrs/vlan/access?devId=" + str(devid) + \
"&start=1&size=500&total=false"
f_url = url + g... | Function takes devid pr devip as input to RESTFUL call to HP IMC platform
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:param devid: str requires devid of the target device
... |
354,922 | def symbol(currency, *, native=True):
currency = validate_currency(currency)
if native:
return _currencies[currency][]
return _currencies[currency][] | return symbol of currency |
354,923 | def __gather_avail(self):
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail | Gather the lists of available sls data from the master |
354,924 | def getDepth(pair, connection=None, info=None):
if info is not None:
info.validate_pair(pair)
if connection is None:
connection = common.BTCEConnection()
response = connection.makeJSONRequest("/api/3/depth/%s" % pair)
if type(response) is not dict:
raise TypeError("The re... | Retrieve the depth for the given pair. Returns a tuple (asks, bids);
each of these is a list of (price, volume) tuples. |
354,925 | def projects(self, task, params={}, **options):
path = "/tasks/%s/projects" % (task)
return self.client.get_collection(path, params, **options) | Returns a compact representation of all of the projects the task is in.
Parameters
----------
task : {Id} The task to get projects on.
[params] : {Object} Parameters for the request |
354,926 | def split_window(self, attach=False, vertical=True, start_directory=None):
return self.window.split_window(
target=self.get(),
start_directory=start_directory,
attach=attach,
vertical=vertical,
) | Split window at pane and return newly created :class:`Pane`.
Parameters
----------
attach : bool, optional
Attach / select pane after creation.
vertical : bool, optional
split vertically
start_directory : str, optional
specifies the working di... |
354,927 | def yum_update(self, allow_reboot=False):
self.run()
self.run(,
ignore_error=True)
self.run()
self.run(, retry=3)
if allow_reboot:
self.run()
default_kernel = self.run()[0].rstrip()
cur_kernel = self.run()[0].... | Do a yum update on the system.
:param allow_reboot: If True and if a new kernel has been installed,
the system will be rebooted |
354,928 | def _create_topk_unique(inputs, k):
height = inputs.shape[0]
width = inputs.shape[1]
neg_inf_r0 = tf.constant(-np.inf, dtype=tf.float32)
ones = tf.ones([height, width], dtype=tf.float32)
neg_inf_r2 = ones * neg_inf_r0
inputs = tf.where(tf.is_nan(inputs), neg_inf_r2, inputs)
tmp = inputs
top... | Creates the top k values in sorted order with indices.
Args:
inputs: A tensor with rank of 2. [batch_size, original_size].
k: An integer, number of top elements to select.
Returns:
topk_r2: A tensor, the k largest elements. [batch_size, k].
topk_indices_r2: A tensor, indices of the top k values. [... |
354,929 | def establish_scp_conn(self):
ssh_connect_params = self.ssh_ctl_chan._connect_params_dict()
self.scp_conn = self.ssh_ctl_chan._build_ssh_client()
self.scp_conn.connect(**ssh_connect_params)
self.scp_client = scp.SCPClient(self.scp_conn.get_transport()) | Establish the secure copy connection. |
354,930 | def _get_file_handlers(self, dsid):
ds_info = self.ids[dsid]
filetype = self._preferred_filetype(ds_info[])
if filetype is None:
logger.warning("Required file type not found or loaded for "
"", ds_info[], dsid.name)
else:
retu... | Get the file handler to load this dataset. |
354,931 | def save(self, path):
path_dir = os.path.split(path)[0]
if not os.path.exists(path_dir):
try:
os.makedirs(path_dir)
except OSError:
pass
with open(path, ) as out:
out.write(self._bytes_body if self._bytes_body is not ... | Save response body to file. |
354,932 | def report(self):
aggregations = dict(
(test, Counter().rollup(values))
for test, values in self.socket_warnings.items()
)
total = sum(
len(warnings)
for warnings in self.socket_warnings.values()
)
def format_test_statisti... | Performs rollups, prints report of sockets opened. |
354,933 | def _calculate_position(self, at_line=None, at_position=None,
at_point=None):
if [at_line, at_position, at_point].count(None) < 2:
raise Exception()
if at_position is None:
at_position = self.get_position()
... | Calculate a global point position `QPoint(x, y)`, for a given
line, local cursor position, or local point. |
354,934 | def deployed(name, sourcepath, apppool=, hostheader=, ipaddress=, port=80, protocol=, preload=):
*
ret = {: name,
: {},
: None,
: }
current_sites = __salt__[]()
if name in current_sites:
ret[] = .format(name)
ret[] = True
elif __opts__[]:
re... | Ensure the website has been deployed.
.. note:
This function only validates against the site name, and will return True even
if the site already exists with a different configuration. It will not modify
the configuration of an existing site.
:param str name: The IIS site name.
:pa... |
354,935 | def _set(self, ctx, table_name, record_id, column_values):
vsctl_table = self._get_table(table_name)
ovsrec_row = ctx.must_get_row(vsctl_table, record_id)
for column, value in column_values:
ctx.set_column(ovsrec_row, column, value)
ctx.invalidate_cache() | :type column_values: list of (column, value_json) |
354,936 | def process_args():
parser = argparse.ArgumentParser(description="A script for plotting files containing spike time data")
parser.add_argument(,
type=str,
metavar=,
help=,
nargs=)
... | Parse command-line arguments. |
354,937 | def add_master_user_mysql(database: str,
root_user: str,
root_password: str,
new_user: str,
new_password: str,
server: str = "localhost",
port: int = 3306,
... | Connects via PyMySQL/MySQLdb and creates a database superuser. |
354,938 | def add_file(self, filename, overwrite=False):
with open(filename, ) as fin:
self.add(fin.read(), overwrite) | Open given file and add its data by guessing its format. The format
must be Motorola S-Records, Intel HEX or TI-TXT. Set `overwrite` to
``True`` to allow already added data to be overwritten. |
354,939 | def _cnf(lexer, varname):
_expect_token(lexer, {KW_p})
_expect_token(lexer, {KW_cnf})
nvars = _expect_token(lexer, {IntegerToken}).value
nclauses = _expect_token(lexer, {IntegerToken}).value
return _cnf_formula(lexer, varname, nvars, nclauses) | Return a DIMACS CNF. |
354,940 | def _pfp__build(self, stream=None, save_offset=False):
max_size = -1
if stream is None:
core_stream = six.BytesIO()
new_stream = bitwrap.BitwrappedStream(core_stream)
else:
new_stream = stream
for child in self._pfp__children:
cur... | Build the union and write the result into the stream.
:stream: None
:returns: None |
354,941 | def zscore(self, weighted=True, prune=False, hs_dims=None):
counts = self.as_array(weighted=weighted)
total = self.margin(weighted=weighted)
colsum = self.margin(axis=0, weighted=weighted)
rowsum = self.margin(axis=1, weighted=weighted)
zscore = self._calculate_std_res(c... | Return ndarray with slices's standardized residuals (Z-scores).
(Only applicable to a 2D contingency tables.) The Z-score or
standardized residual is the difference between observed and expected
cell counts if row and column variables were independent divided
by the residual cell varian... |
354,942 | def create_namespaced_pod(self, namespace, body, **kwargs):
kwargs[] = True
if kwargs.get():
return self.create_namespaced_pod_with_http_info(namespace, body, **kwargs)
else:
(data) = self.create_namespaced_pod_with_http_info(namespace, body, **kwargs)
... | create a Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_pod(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str names... |
354,943 | def send_quick_chat(self, team_only, quick_chat):
if quick_chat == QuickChats.CHAT_NONE or quick_chat is None:
return
self.__quick_chat_func(team_only, quick_chat) | Sends a quick chat to the other bots.
If it is QuickChats.CHAT_NONE or None it does not send a quick chat to other bots.
:param team_only: either True or False, this says if the quick chat should only go to team members.
:param quick_chat: The quick chat selection, available chats are defined in... |
354,944 | def table_chains(self, table="filter"):
return dict((c["name"], self.get_chain(c["name"], table)) for c in self.get_table(table)) | Get a dict where the keys are all the chains for the given table
and each value is the set of rules defined for the given chain.
Args:
table (str): table name, defaults to ``filter``
Returns:
dict: chains with set of defined rules |
354,945 | def trades(self, base_asset_code=None, counter_asset_code=None, base_asset_issuer=None, counter_asset_issuer=None,
offer_id=None, cursor=None, order=, limit=10):
base_asset = Asset(base_asset_code, base_asset_issuer)
counter_asset = Asset(counter_asset_code, counter_asset_issuer)... | Load a list of trades, optionally filtered by an orderbook.
See the below docs for more information on required and optional
parameters for further specifying your search.
`GET /trades
<https://www.stellar.org/developers/horizon/reference/endpoints/trades.html>`_
:param str ba... |
354,946 | def lreg(self, xcol, ycol, name="Regression"):
try:
x = self.df[xcol].values.reshape(-1, 1)
y = self.df[ycol]
lm = linear_model.LinearRegression()
lm.fit(x, y)
predictions = lm.predict(x)
self.df[name] = predictions
except ... | Add a column to the main dataframe populted with
the model's linear regression for a column |
354,947 | def update_job(name, config):
<config yaml>
if not in config:
config[] = name
data = salt.utils.json.dumps(config)
try:
response = salt.utils.http.query(
"{0}/scheduler/iso8601".format(_base_url()),
method=,
data=data,
header_dict={
... | Update the specified job with the given configuration.
CLI Example:
.. code-block:: bash
salt chronos-minion-id chronos.update_job my-job '<config yaml>' |
354,948 | def resource(url_prefix_or_resource_cls: Union[str, Type[Resource]],
resource_cls: Optional[Type[Resource]] = None,
*,
member_param: Optional[str] = None,
unique_member_param: Optional[str] = None,
rules: Optional[Iterable[Union[Route, RouteGenerator]]] =... | This function is used to register a :class:`Resource`'s routes.
Example usage::
routes = lambda: [
prefix('/api/v1', [
resource('/products', ProductResource),
])
]
Or with the optional prefix argument::
routes = lambda: [
resource('... |
354,949 | def _set_nameserver_fc4s(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_dict={: u, : [u]}), is_leaf=True, yang_name="nameserver-fc4s", rest_name="nameserver-fc4s", parent=self, path_helper=self._path... | Setter method for nameserver_fc4s, mapped from YANG variable /brocade_nameserver_rpc/get_nameserver_detail/output/show_nameserver/nameserver_fc4s (nameserver-fc4s-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_nameserver_fc4s is considered as a private
method. Backend... |
354,950 | def read(self, entity=None, attrs=None, ignore=None, params=None):
if attrs is None:
attrs = self.read_json()
attrs[] = attrs.pop()
).update_json([])[attr]
return super(DiscoveryRule, self).read(entity, attrs, ignore, params) | Work around a bug. Rename ``search`` to ``search_``.
For more information on the bug, see `Bugzilla #1257255
<https://bugzilla.redhat.com/show_bug.cgi?id=1257255>`_. |
354,951 | def get_args():
ap = argparse.ArgumentParser(description="Create frames for a movie that can be compiled using ffmpeg")
ap.add_argument("start", help="date string as start time")
ap.add_argument("end", help="date string as end time")
ap.add_argument("step", type=float, help="fraction of a day to st... | request the arguments for running |
354,952 | def body(circuit, settings):
qubit_instruction_mapping = {}
for inst in circuit:
if isinstance(inst, Measurement):
inst.qubits = [inst.qubit]
inst.name = "MEASURE"
else:
qubits = inst.qubits
for qubit in qubits:
qubit_instruction... | Return the body of the Latex document, including the entire circuit in
TikZ format.
:param Program circuit: The circuit to be drawn, represented as a pyquil program.
:param dict settings:
:return: Latex string to draw the entire circuit.
:rtype: string |
354,953 | def set_network_settings(self, mtu, sock_snd, sock_rcv, tcp_wnd_snd, tcp_wnd_rcv):
if not isinstance(mtu, baseinteger):
raise TypeError("mtu can only be an instance of type baseinteger")
if not isinstance(sock_snd, baseinteger):
raise TypeError("sock_snd can only be an i... | Sets network configuration of the NAT engine.
in mtu of type int
MTU (maximum transmission unit) of the NAT engine in bytes.
in sock_snd of type int
Capacity of the socket send buffer in bytes when creating a new socket.
in sock_rcv of type int
Capacity of ... |
354,954 | def simulate_phases(self, phase_map: Dict[Tuple[int, ...], float]):
self._pool.map(_clear_scratch, self._shard_num_args())
for indices, half_turns in phase_map.items():
args = self._shard_num_args(
{: indices, : half_turns})
if len(indices) == 1:... | Simulate a set of phase gates on the xmon architecture.
Args:
phase_map: A map from a tuple of indices to a value, one for each
phase gate being simulated. If the tuple key has one index, then
this is a Z phase gate on the index-th qubit with a rotation
... |
354,955 | def from_times(cls, times, delta_t=DEFAULT_OBSERVATION_TIME):
times_arr = np.asarray(times.jd * TimeMOC.DAY_MICRO_SEC, dtype=int)
intervals_arr = np.vstack((times_arr, times_arr + 1)).T
order = TimeMOC.time_resolution_to_order(delta_t)
return TimeMOC(IntervalSet(interv... | Create a TimeMOC from a `astropy.time.Time`
Parameters
----------
times : `astropy.time.Time`
astropy observation times
delta_t : `astropy.time.TimeDelta`, optional
the duration of one observation. It is set to 30 min by default. This data is used to compute the
... |
354,956 | def set_logging_formatter(self):
for handler in (RuntimeGlobals.logging_console_handler,
RuntimeGlobals.logging_file_handler,
RuntimeGlobals.logging_session_handler):
handler and handler.setFormatter(
RuntimeGlobals.logging_fo... | Sets the logging formatter. |
354,957 | def parse(self):
plt = Plot(name_from_filename(self.pltfilename))
with open(self.pltfilename, ) as pltfile:
segment = None
for line in pltfile:
if not line:
continue
c, val = line[:1], line[1:]
if c ... | Parse our .PLT file and return :class:`Plot` object or raise :exc:`ParseException`. |
354,958 | def build_wheel(platform):
if platform in [, ]:
system =
else:
system =
setuptools.sandbox.run_setup(
,
[, , , , , .format(system, platform)]
) | Create a wheel |
354,959 | def get_nbt(self,x,z):
rx,cx = divmod(x,32)
rz,cz = divmod(z,32)
if (rx,rz) not in self.regions and (rx,rz) not in self.regionfiles:
raise InconceivedChunk("Chunk %s,%s is not present in world" % (x,z))
nbt = self.get_region(rx,rz).get_nbt(cx,cz)
assert nbt !... | Return a NBT specified by the chunk coordinates x,z. Raise InconceivedChunk
if the NBT file is not yet generated. To get a Chunk object, use get_chunk. |
354,960 | def build_interpolators(self):
self.phi_continuous = []
for xi, phii in zip(self.ace.x, self.ace.x_transforms):
self.phi_continuous.append(interp1d(xi, phii))
self.inverse_theta_continuous = interp1d(self.ace.y_transform, self.ace.y) | Compute 1-D interpolation functions for all the transforms so they're continuous.. |
354,961 | def index(self, value):
for idx, val in enumerate(self):
if value == val:
return idx
raise ValueError(.format(value)) | Return index of *value* in self.
Raises ValueError if *value* is not found. |
354,962 | def name2mount(self, name):
if not self.is_module(name):
raise ValueError( % (name, ))
return name.replace(self.module_prefix, self.mount_prefix) | Convert a module name to a mount name |
354,963 | def update(sc, filename, asset_id):
addresses = []
with open(filename) as hostfile:
for line in hostfile.readlines():
addresses.append(line.strip())
sc.asset_update(asset_id, dns=addresses) | Updates a DNS Asset List with the contents of the filename. The assumed
format of the file is 1 entry per line. This function will convert the
file contents into an array of entries and then upload that array into
SecurityCenter. |
354,964 | def _has_file_rolled(self):
if self._fh:
size = self._getsize_of_current_file()
if size < self.oldsize:
return True
self.oldsize = size
return False | Check if the file has been rolled |
354,965 | def search_file_upwards(name, base=None):
base = base or os.getcwd()
while base != os.path.dirname(base):
if os.path.exists(os.path.join(base, name)):
return base
base = os.path.dirname(base)
return None | Search for a file named `name` from cwd or given directory to root.
Return None if nothing's found. |
354,966 | def get_int(self, key: str) -> Optional[int]:
v = self.get(key)
if v is None:
return None
try:
return int(v)
except:
raise ConfigTypeError(self.full_key(key), v, ) | Returns an optional configuration value, as an int, by its key, or None if it doesn't exist.
If the configuration value isn't a legal int, this function will throw an error.
:param str key: The requested configuration key.
:return: The configuration key's value, or None if one does not exist.
... |
354,967 | def _transactional(self, method, *argv, **argd):
self._session.begin(subtransactions = True)
try:
result = method(self, *argv, **argd)
self._session.commit()
return result
except:
self._session.rollback()
raise | Begins a transaction and calls the given DAO method.
If the method executes successfully the transaction is commited.
If the method fails, the transaction is rolled back.
@type method: callable
@param method: Bound method of this class or one of its subclasses.
The first ... |
354,968 | def surrogate_escape(error):
chars = error.object[error.start:error.end]
assert len(chars) == 1
val = ord(chars)
val += 0xdc00
return __builtin__.unichr(val), error.end | Simulate the Python 3 ``surrogateescape`` handler, but for Python 2 only. |
354,969 | def delete(self):
if self.instance is None:
raise CQLEngineException("DML Query instance attribute is None")
ds = DeleteStatement(self.column_family_name, timestamp=self._timestamp, conditionals=self._conditional, if_exists=self._if_exists)
for name, col in self.model._prim... | Deletes one instance |
354,970 | def yield_amd_require_string_arguments(
node, pos,
reserved_module=reserved_module, wrapped=define_wrapped):
for i, child in enumerate(node.args.items[pos]):
if isinstance(child, asttypes.String):
result = to_str(child)
if ((result not in reserved_module) and (
... | This yields only strings within the lists provided in the argument
list at the specified position from a function call.
Originally, this was implemented for yield a list of module names to
be imported as represented by this given node, which must be of the
FunctionCall type. |
354,971 | def set_description(self, feature_id, description, organism=None, sequence=None):
data = {
: [
{
: feature_id,
: description,
}
]
}
data = self._update_data(data, sequence, organism)
... | Set a feature's description
:type feature_id: str
:param feature_id: Feature UUID
:type description: str
:param description: Feature description
:type organism: str
:param organism: Organism Common Name
:type sequence: str
:param sequence: Sequence Nam... |
354,972 | def setup_directories(self, use_sudo=True):
runner = self._runner.sudo if use_sudo else self._runner.run
runner("mkdir -p ".format(self._releases)) | Create the minimal required directories for deploying multiple
releases of a project.
By default, creation of directories is done with the Fabric
``sudo`` function but can optionally use the ``run`` function.
This method performs one network operation.
:param bool use_sudo: If... |
354,973 | def saveInputs(self, fname):
if not fname:
return
appdir = systools.get_appdir()
if not os.path.isdir(appdir):
os.makedirs(appdir)
fname = os.path.join(appdir, fname)
savedict = {}
savedict[] = self.ui.binszSpnbx.val... | Save the values in the input fields so they can be loaded
next time the GUI is run
:param fname: file path of location to store values at
:type fname: str |
354,974 | def readlines(self, sizehint=None):
lines = []
byte_count = 0
while True:
line = self.readline()
if len(line) == 0:
break
lines.append(line)
byte_count += len(line)
if (sizehint is not None) and (byte_count >= s... | Read all remaining lines using `readline` and return them as a list.
If the optional ``sizehint`` argument is present, instead of reading up
to EOF, whole lines totalling approximately sizehint bytes (possibly
after rounding up to an internal buffer size) are read.
:param int sizehint: ... |
354,975 | def arc_negative(self, x, y, radius, start_angle, end_angle):
self._add_instruction("arc_negative", x, y, radius, start_angle, end_angle) | draw arc going clockwise from start_angle to end_angle |
354,976 | def RemoveFromQueue(self, addr):
if addr in self.connection_queue:
self.connection_queue.remove(addr) | Remove an address from the connection queue
Args:
addr:
Returns: |
354,977 | def binary_erosion(x, radius=3):
mask = disk(radius)
x = _binary_erosion(x, selem=mask)
return x | Return binary morphological erosion of an image,
see `skimage.morphology.binary_erosion <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_erosion>`__.
Parameters
-----------
x : 2D array
A binary image.
radius : int
For the radius of mask.
... |
354,978 | def mostDeviant(requestContext, seriesList, n):
deviants = []
for series in seriesList:
mean = safeAvg(series)
if mean is None:
continue
square_sum = sum([(value - mean) ** 2 for value in series
if value is not None])
sigma = safeDiv(sq... | Takes one metric or a wildcard seriesList followed by an integer N.
Draws the N most deviant metrics.
To find the deviants, the standard deviation (sigma) of each series
is taken and ranked. The top N standard deviations are returned.
Example::
&target=mostDeviant(server*.instance*.memory.free... |
354,979 | def _group_models(self):
od = OrderedDict()
for i, model in enumerate(self.models):
output = getattr(model, "output", {})
if output.get("AIC") and output.get("BMD") and output["BMD"] > 0:
key = "{}-{}".format(output["AIC"], output["BMD"... | If AIC and BMD are numeric and identical, then treat models as
identical. Returns a list of lists. The outer list is a list of related
models, the inner list contains each individual model, sorted by the
number of parameters in ascending order.
This is required because in some cases, a ... |
354,980 | def evaluate(self):
if self.opt[]:
DX = self.reconstruct()
W = self.dstep.W
S = self.dstep.S
else:
W = mp_W
S = mp_S
Xf = mp_Zf
Df = mp_Df
DX = sl.irfftn(sl.inner(
Df[np.newaxis, ...... | Evaluate functional value of previous iteration. |
354,981 | def ownerDocument(self) -> Optional[AbstractNode]:
if self.nodeType == Node.DOCUMENT_NODE:
return self
elif self.parentNode:
return self.parentNode.ownerDocument
return None | Return the owner document of this node.
Owner document is an ancestor document node of this node. If this node
(or node tree including this node) is not appended to any document
node, this property returns ``None``.
:rtype: Document or None |
354,982 | def saveAsTable(self, name, format=None, mode=None, partitionBy=None, **options):
self.mode(mode).options(**options)
if partitionBy is not None:
self.partitionBy(partitionBy)
if format is not None:
self.format(format)
self._jwrite.saveAsTable(name) | Saves the content of the :class:`DataFrame` as the specified table.
In the case the table already exists, behavior of this function depends on the
save mode, specified by the `mode` function (default to throwing an exception).
When `mode` is `Overwrite`, the schema of the :class:`DataFrame` doe... |
354,983 | def format_edges_section(self):
buf = io.StringIO()
buf.write()
buf.write()
for e in self.edges.values():
buf.write( + e.format(self.vertices) + )
buf.write()
return buf.getvalue() | format edges section.
assign_vertexid() should be called before this method, because
vertices reffered by blocks should have valid index. |
354,984 | def group_search(auth=None, **kwargs):
**
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.search_groups(**kwargs) | Search for groups
CLI Example:
.. code-block:: bash
salt '*' keystoneng.group_search name=group1
salt '*' keystoneng.group_search domain_id=b62e76fbeeff4e8fb77073f591cf211e |
354,985 | def on_map_fragment_created(self, obj_id):
self.fragment = MapFragment(__id__=obj_id)
self.map.onMapReady.connect(self.on_map_ready)
self.fragment.getMapAsync(self.map.getId())
context = self.get_context()
def on_transaction(id):
trans = FragmentT... | Create the fragment and pull the map reference when it's loaded. |
354,986 | def infer_list_subtype(items):
subtype = End
for item in items:
item_type = type(item)
if not issubclass(item_type, Base):
continue
if subtype is End:
subtype = item_type
if not issubclass(subtype, ... | Infer a list subtype from a collection of items. |
354,987 | def add_rolling_statistics_variables(
df = None,
variable = None,
window = 20,
upper_factor = 2,
lower_factor = 2
):
df[variable + "_rolling_mean"] = pd.stats.moments.rolling_mean(df[variable], window)
df[variable + "_rolling_standard_deviation"] = ... | Add rolling statistics variables derived from a specified variable in a
DataFrame. |
354,988 | def parser():
parser = argparse.ArgumentParser()
parser.add_argument(, , default=[], action=,
help=)
return parser | Return a parser for setting one or more configuration paths |
354,989 | def _get_param_names(cls):
init = getattr(cls.__init__, , cls.__init__)
if init is object.__init__:
return []
args, varargs, kw, default = getargspec_no_self(init)
if varargs is not None:
raise RuntimeErro... | Get parameter names for the estimator |
354,990 | def _find_input_dependencies(self, inputs):
dependencies = []
for address in inputs:
dependencies.extend(
self._predecessor_tree.find_read_predecessors(address))
return dependencies | Use the predecessor tree to find dependencies based on inputs.
Returns: A list of transaction ids. |
354,991 | def add_column(self, func, name=None, show=True):
assert func
name = name or func.__name__
if name == :
raise ValueError("Please provide a valid name for " + name)
d = {: func,
: show,
}
self._columns[name] = d
data... | Add a column function which takes an id as argument and
returns a value. |
354,992 | def find_zonefile_origins( self, missing_zfinfo, peer_hostports ):
zonefile_origins = {}
for zfhash in missing_zfinfo.keys():
for peer_hostport in peer_hostports:
if not zonefile_origins.has_key(peer_hostport):
zonefile_origins[peer_h... | Find out which peers can serve which zonefiles |
354,993 | def find_local_peaks(sig, radius):
if np.min(sig) == np.max(sig):
return np.empty(0)
peak_inds = []
i = 0
while i < radius + 1:
if sig[i] == max(sig[:i + radius]):
peak_inds.append(i)
i += radius
else:
i += 1
while i < len(sig)... | Find all local peaks in a signal. A sample is a local peak if it is
the largest value within the <radius> samples on its left and right.
In cases where it shares the max value with nearby samples, the
middle sample is classified as the local peak.
Parameters
----------
sig : numpy array
... |
354,994 | def serialize(self, **kwargs) -> str:
kwargs = {key: str(value) for key, value in kwargs.items()}
return self.g.serialize(**kwargs) | rdflib.Graph().serialize wrapper
Original serialize cannot handle PosixPath from pathlib. You should ignore everything, but
destination and format. format is a must, but if you don't include a destination, it will
just return the formated graph as an str output.
Args:
desti... |
354,995 | def wait(self, timeout=None):
us = -1 if timeout is None else int(timeout * 1000000)
return super(Reader, self).wait(us) | Wait for a change in the journal.
`timeout` is the maximum time in seconds to wait, or None which
means to wait forever.
Returns one of NOP (no change), APPEND (new entries have been added to
the end of the journal), or INVALIDATE (journal files have been added or
removed). |
354,996 | def plot_hpars(HDD, hpars, sym):
plt.figure(num=HDD[])
X, Y = [], []
X.append(0)
Y.append(old_div(float(hpars[]), float(
hpars[])))
X.append(float(hpars[]))
Y.append(0)
plt.plot(X, Y, sym)
bounds = plt.axis()
n4 = + % (float(hpars[])) +
plt.text(bounds[1] - .9 * b... | function to plot hysteresis parameters
deprecated (used in hysteresis_magic) |
354,997 | def _parse_arguments(self, method, parameters):
arguments = _fetch_arguments(self, method)
arg_dict = {}
errors = []
for key, properties in parameters:
if key in arguments:
value = arguments[key]
try:
arg_dict[key] = _apply_validator_chain(
... | Parse arguments to method, returning a dictionary. |
354,998 | def decrease_writes_in_units(
current_provisioning, units, min_provisioned_writes, log_tag):
updated_provisioning = int(current_provisioning) - int(units)
min_provisioned_writes = __get_min_writes(
current_provisioning,
min_provisioned_writes,
log_tag)
if updated_provis... | Decrease the current_provisioning with units units
:type current_provisioning: int
:param current_provisioning: The current provisioning
:type units: int
:param units: How many units should we decrease with
:returns: int -- New provisioning value
:type min_provisioned_writes: int
:param min... |
354,999 | def islink(self, path=None, header=None):
if header is None:
header = self._head(self.get_client_kwargs(path))
for key in (, ):
try:
return header.pop(key) ==
except KeyError:
continue
return False | Returns True if object is a symbolic link.
Args:
path (str): File path or URL.
header (dict): Object header.
Returns:
bool: True if object is Symlink. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.