Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
356,500 | def update(self):
super(AnalysisProfileAnalysesView, self).update()
self.allow_edit = self.is_edit_allowed()
self.configuration = self.get_configuration() | Update hook |
356,501 | def main():
parser = optparse.OptionParser(usage="%prog [options] <model_path> [another_model_path...]",
formatter=optparse.TitledHelpFormatter())
parser.set_description(__doc__.strip())
parser.add_option("-f", "--function", de... | Parse argv for options and arguments, and start schema generation. |
356,502 | def eval_fitness(self, chromosome):
sx, sy = self.translator.translate_chromosome(chromosome)
penalty = 0
if sx >= self.w:
penalty += self.w * self.h
if sy >= self.h:
penalty += self.w * self.h
if penalty > 0:
self.... | Return the number of plants reached by the sprinkler.
Returns a large penalty for sprinkler locations outside the map. |
356,503 | def list_types_view(request, semester, profile=None):
page_name = "Workshift Types"
full_management = utils.can_manage(request.user, semester)
any_management = utils.can_manage(request.user, semester, any_pool=True)
types = WorkshiftType.objects.all()
type_shifts = [
RegularWorkshift.o... | View the details of a particular WorkshiftType. |
356,504 | def formatex(ex, msg=,
prefix=None, key_list=[], locals_=None, iswarning=False, tb=False,
N=0, keys=None, colored=None):
r
if prefix is None:
prefix = get_caller_prefix(aserror=True, N=N)
if locals_ is None:
locals_ = get_parent_frame(N=N).f_locals
if keys ... | r"""
Formats an exception with relevant info
Args:
ex (Exception): exception to print
msg (unicode): a message to display to the user (default = u'[!?] Caught exception')
keys (None): a list of strings denoting variables or expressions of interest (default = [])
iswarning (bool... |
356,505 | def parse(self, commands):
to_delete = []
for id_, val in self._objects.items():
if val == JUST_DELETED:
to_delete.append(id_)
for id_ in to_delete:
self._objects.pop(id_)
for command in commands:
self._pars... | Parse a list of commands. |
356,506 | def insert(self, thread):
thread_id = thread[]
title = thread[]
self.db.threads.new(thread_id, title)
comments = list(map(self._build_comment, thread[]))
comments.sort(key=lambda comment: comment[])
self.count += len(comments)
for comment in comments:
... | Process a thread and insert its comments in the DB. |
356,507 | def get_default_connection():
tid = id(threading.current_thread())
conn = _conn_holder.get(tid)
if not conn:
with(_rlock):
if not in _options and not in _options:
_options[] = helper.get_project_endpoint_from_env()
if not in _options:
_options[] = helper.get_cre... | Returns the default datastore connection.
Defaults endpoint to helper.get_project_endpoint_from_env() and
credentials to helper.get_credentials_from_env().
Use set_options to override defaults. |
356,508 | def percept(self, agent):
status = if_(self.some_things_at(agent.location, Dirt),
, )
bump = if_(agent.bump, , )
return (status, bump) | The percept is a tuple of ('Dirty' or 'Clean', 'Bump' or 'None').
Unlike the TrivialVacuumEnvironment, location is NOT perceived. |
356,509 | def text(draw, xy, txt, fill=None, font=None):
font = font or DEFAULT_FONT
x, y = xy
for ch in txt:
for byte in font[ord(ch)]:
for j in range(8):
if byte & 0x01 > 0:
draw.point((x, y + j), fill=fill)
byte >>= 1
x += 1 | Draw a legacy font starting at :py:attr:`x`, :py:attr:`y` using the
prescribed fill and font.
:param draw: A valid canvas to draw the text onto.
:type draw: PIL.ImageDraw
:param txt: The text string to display (must be ASCII only).
:type txt: str
:param xy: An ``(x, y)`` tuple denoting the top-... |
356,510 | def verify_retry_data(self, retry_data):
retry_defaults = {
: True,
: 2,
: 0,
: 30,
}
expected_data = {
: bool,
: int,
: int,
: int,
}
validated_retry_data = {... | verifies the specified retry data |
356,511 | def clean_stats(self):
stats = self.stats()
if in stats:
topics = stats[]
topics = dict((t.pop(), t) for t in topics)
for topic, data in topics.items():
if in data:
channels = data[]
channels = dic... | Stats with topics and channels keyed on topic and channel names |
356,512 | def get_value(self, element):
if not self.__elements:
return
values = self.filter_values(r"^{0}$".format(element))
return foundations.common.get_first_item(values) | | Returns the given element value.
| If multiple elements with the same name exists, only the first encountered will be returned.
Usage::
>>> plist_file_parser = PlistFileParser("standard.plist")
>>> plist_file_parser.parse()
True
>>> plist_file_parser.g... |
356,513 | def close(self, reply_code=0, reply_text=, class_id=0, method_id=0):
self.channel.close(reply_code, reply_text, class_id, method_id) | Close this channel. Routes to channel.close. |
356,514 | def keyReleaseEvent(self, event):
if self.isReadOnly():
return
initial_state = event.isAccepted()
event.ignore()
self.key_released.emit(event)
if not event.isAccepted():
event.setAccepted(initial_state)
super(CodeEdit, self).keyRelease... | Overrides keyReleaseEvent to emit the key_released signal.
:param event: QKeyEvent |
356,515 | def get_candles(self, market, tick_interval):
return self._api_query(path_dict={
API_V2_0:
}, options={
: market, : tick_interval
}, protection=PROTECTION_PUB) | Used to get all tick candles for a market.
Endpoint:
1.1 NO EQUIVALENT
2.0 /pub/market/GetTicks
Example ::
{ success: true,
message: '',
result:
[ { O: 421.20630125,
H: 424.03951276,
L: 421.20... |
356,516 | def set_subject(self, value: Union[Literal, Identifier, str], lang: str= None):
return self.metadata.add(key=DC.subject, value=value, lang=lang) | Set the DC Subject literal value
:param value: Value of the subject node
:param lang: Language in which the value is |
356,517 | def require_debian_packages(packages: List[str]) -> None:
present = are_debian_packages_installed(packages)
missing_packages = [k for k, v in present.items() if not v]
if missing_packages:
missing_packages.sort()
msg = (
"Debian packages are missing, as follows. Suggest:\n\n... | Ensure specific packages are installed under Debian.
Args:
packages: list of packages
Raises:
ValueError: if any are missing |
356,518 | def isspecword(somestr):
OnlyStringsCanBeChecked(somestr)
if somestr.isalpha() and len(somestr) in [1, 2]:
matches = re.search(r, somestr, flags = re.IGNORECASE)
if matches == None:
if somestr.casefold()[0:1] not in [, ]:
return True
return False | Checks that some string is a special word
:param str somestr:
It is some string that will be checked for special word.
The special word is a string that contains only alphabetic characters,
its length not less 1 character and not more 2 characters and
also noone characters does not re... |
356,519 | def build(self, field: Field) -> Mapping[str, Any]:
builder_types = self.builder_types() + [
self.default_builder_type()
]
builders: List[ParameterBuilder] = [
builder_type(
build_parameter=self.build,
)
for b... | Build a swagger parameter from a marshmallow field. |
356,520 | def fromtimestamp(cls, timestamp, tz=None):
_check_tzinfo_arg(tz)
converter = _time.localtime if tz is None else _time.gmtime
self = cls._from_timestamp(converter, timestamp, tz)
if tz is not None:
self = tz.fromutc(self)
return self | Construct a datetime from a POSIX timestamp (like time.time()).
A timezone info object may be passed in as well. |
356,521 | def deploy_from_template(self, si, logger, data_holder, vcenter_data_model, reservation_id, cancellation_context):
template_resource_model = data_holder.template_resource_model
return self._deploy_a_clone(si,
logger,
data_h... | :param cancellation_context:
:param reservation_id:
:param si:
:param logger:
:type data_holder: DeployFromTemplateDetails
:type vcenter_data_model
:rtype DeployAppResult:
:return: |
356,522 | def _create_entry(entry: dict, source: Source = None) -> dict:
entry["package_name"] = entry["package"].pop("package_name")
entry["package_version"] = entry["package"].pop("installed_version")
if source:
entry["index_url"] = source.url
entry["sha256"] = []
for item in source.ge... | Filter and normalize the output of pipdeptree entry. |
356,523 | def complete_command(self, tokens: List[str], text: str, line: str, begidx: int, endidx: int) -> List[str]:
if not is_potential_flag(token, self._parser) and flag_action is not None:
flag_arg.count += 1
arg_choices = self._reso... | Complete the command using the argparse metadata and provided argument dictionary |
356,524 | def recent(self):
kwd = {
: ,
: ,
}
self.render(,
view=MWiki.query_recent(),
format_date=tools.format_date,
kwd=kwd,
userinfo=self.userinfo) | List recent wiki. |
356,525 | def reset_ctx(self, ctx):
if ctx is None:
ctx = [context.current_context()]
if isinstance(ctx, Context):
ctx = [ctx]
if self._data:
data = self._reduce()
with autograd.pause():
self._init_impl(data, ctx)
elif self._... | Re-assign Parameter to other contexts.
Parameters
----------
ctx : Context or list of Context, default ``context.current_context()``.
Assign Parameter to given context. If ctx is a list of Context, a
copy will be made for each context. |
356,526 | def format(self, show_enabled=True):
what =
if show_enabled:
if self.enabled:
what +=
else:
what +=
pass
pass
if self.fmt:
what += self.fmt +
pass
what += self.arg
... | format display item |
356,527 | def check_split_ratio(split_ratio):
valid_ratio = 0.
if isinstance(split_ratio, float):
assert 0. < split_ratio < 1., (
"Split ratio {} not between 0 and 1".format(split_ratio))
test_ratio = 1. - split_ratio
return (split_ratio, test_ratio, valid_ratio... | Check that the split ratio argument is not malformed |
356,528 | def head(self, path, query=None, data=None, redirects=True):
return self.request(, path, query, None, redirects) | HEAD request wrapper for :func:`request()` |
356,529 | def main():
*checkplot*re given.
--splitout SPLITOUT if there are more than SPLITOUT objects in the target
directory (default: 5000), checkplotlist will split
the output JSON into multiple files. this helps keep
... | This is the main function of this script.
The current script args are shown below ::
Usage: checkplotlist [-h] [--search SEARCH] [--sortby SORTBY]
[--filterby FILTERBY] [--splitout SPLITOUT]
[--outprefix OUTPREFIX] [--maxkeyworkers MAXKEYWORKERS]
... |
356,530 | def get_webhook(self, scaling_group, policy, webhook):
return self._manager.get_webhook(scaling_group, policy, webhook) | Gets the detail for the specified webhook. |
356,531 | def get_or_wait(self, path, name):
d, watch = self.get_children_and_watch(path)
deferred = Deferred()
path += "/" + name
@watch.addCallback
def _notify(event):
if event.type_name == "child":
d = self.get(path)
d.add... | Get data of node under path, or wait for it. |
356,532 | def convolutional_barycenter2d(A, reg, weights=None, numItermax=10000, stopThr=1e-9, stabThr=1e-30, verbose=False, log=False):
if weights is None:
weights = np.ones(A.shape[0]) / A.shape[0]
else:
assert(len(weights) == A.shape[0])
if log:
log = {: []}
b = np.zeros_like(A[... | Compute the entropic regularized wasserstein barycenter of distributions A
where A is a collection of 2D images.
The function solves the following optimization problem:
.. math::
\mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i)
where :
- :math:`W_{reg}(\cdot,\cdot)... |
356,533 | def fix_line_range(source_code, start, end, options):
start = max(start, 1)
options.line_range = [start, end]
from autopep8 import fix_code
fixed = fix_code(source_code, options)
try:
if options.docformatter:
from docformatter import format_code
fixed = fo... | Apply autopep8 (and docformatter) between the lines start and end of
source. |
356,534 | def queryName(self, queryName):
if not queryName or type(queryName) != str or len(queryName.strip()) == 0:
raise ValueError( % queryName)
self._jwrite = self._jwrite.queryName(queryName)
return self | Specifies the name of the :class:`StreamingQuery` that can be started with
:func:`start`. This name must be unique among all the currently active queries
in the associated SparkSession.
.. note:: Evolving.
:param queryName: unique name for the query
>>> writer = sdf.writeStrea... |
356,535 | def get_msms_annotations_parallelize(self, sc, representatives_only=True, force_rerun=False):
genes_rdd = sc.parallelize(self.genes)
def get_msms_annotation(g):
g.protein.get_msms_annotations(representative_only=representatives_only, force_rerun=force_rerun)
return g
... | Run MSMS on structures and store calculations.
Annotations are stored in the protein structure's chain sequence at:
``<chain_prop>.seq_record.letter_annotations['*-msms']``
Args:
representative_only (bool): If analysis should only be run on the representative structure
... |
356,536 | def make_butterworth_bandpass_b_a(CenterFreq, bandwidth, SampleFreq, order=5, btype=):
lowcut = CenterFreq-bandwidth/2
highcut = CenterFreq+bandwidth/2
b, a = make_butterworth_b_a(lowcut, highcut, SampleFreq, order, btype)
return b, a | Generates the b and a coefficients for a butterworth bandpass IIR filter.
Parameters
----------
CenterFreq : float
central frequency of bandpass
bandwidth : float
width of the bandpass from centre to edge
SampleFreq : float
Sample frequency of filter
order : int, optiona... |
356,537 | def format(self, date):
context = {: date}
for handler in self.format_chain:
handler(self, date, context)
return eval(self.format_code, globals(), context) | Given a datetime.datetime object, return a string representing this date/time,
formatted according to this dateformat. |
356,538 | def parse_metric_family(self, response, scraper_config):
input_gen = response.iter_lines(chunk_size=self.REQUESTS_CHUNK_SIZE, decode_unicode=True)
if scraper_config[]:
input_gen = self._text_filter_input(input_gen, scraper_config)
for metric in text_fd_to_metric_families(in... | Parse the MetricFamily from a valid requests.Response object to provide a MetricFamily object (see [0])
The text format uses iter_lines() generator.
:param response: requests.Response
:return: core.Metric |
356,539 | def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
mongo_ids = self.get_initial()[]
for form_mongo_id in form.data.getlist():
for mongo_id in mongo_ids:
if form_mongo_id == m... | Creates new mongoengine records. |
356,540 | def visit((prefix, strip, found), dirname, names):
files = []
for name in names[:]:
path = os.path.join(dirname, name)
if os.path.isdir(path):
if isbad(name):
names.remove(name)
continue
elif isgood(name):
... | Visit directory, create distutil tuple
Add distutil tuple for each directory using this format:
(destination, [dirname/file1, dirname/file2, ...])
distutil will copy later file1, file2, ... info destination. |
356,541 | def visit_Call(self, node):
args = [self.visit(arg) for arg in node.args]
func = self.visit(node.func)
params = args + [func or []]
return list({frozenset.union(*p) for p in itertools.product(*params)}) | Function call depend on all function use in the call.
>> a = foo(bar(c) or foobar(d))
Return type depend on [foo, bar] or [foo, foobar] |
356,542 | def consoleLabel(deduper):
finished = False
use_previous = False
fields = unique(field.field
for field
in deduper.data_model.primary_fields)
buffer_len = 1
examples_buffer = []
uncertain_pairs = []
while not finished:
if use_previou... | Command line interface for presenting and labeling training pairs
by the user
Argument :
A deduper object |
356,543 | def get_or_set_hash(name,
length=8,
chars=):
t need to be stored somewhere centrally.
State Example:
.. code-block:: yaml
some_mysql_user:
mysql_user:
- present
- host: localhost
- password: {{ salt[]() }}
CLI Example:
.. cod... | Perform a one-time generation of a hash and write it to the local grains.
If that grain has already been set return the value instead.
This is useful for generating passwords or keys that are specific to a
single minion that don't need to be stored somewhere centrally.
State Example:
.. code-bloc... |
356,544 | def get_queryset(self):
qs = super(BaseCalendarMonthView, self).get_queryset()
year = self.get_year()
month = self.get_month()
date_field = self.get_date_field()
end_date_field = self.get_end_date_field()
date = _date_from_string(year, self.get_year_format(),
... | Returns a queryset of models for the month requested |
356,545 | def RGB(self, val):
val = np.atleast_1d(val).astype(np.float32) / 255.
self.rgba = val | Set the color using an Nx3 array of RGB uint8 values |
356,546 | def _match_elements(dom, matches):
out = {}
for key, content in matches.items():
pattern = content["data"].strip()
if "\n" in pattern:
pattern = pattern.split()
transformer = lambda x: x.strip().split()
else:
transformer = lambda x: x.strip()
... | Find location of elements matching patterns specified in `matches`.
Args:
dom (obj): HTMLElement DOM tree.
matches (dict): Structure: ``{"var": {"data": "match", ..}, ..}``.
Returns:
dict: Structure: ``{"var": {"data": HTMLElement_obj, ..}, ..}`` |
356,547 | def unpack(self, fmt, length=1):
try:
info = struct.unpack(fmt, self.stream.read(length))[0]
except struct.error as e:
raise SDKException(ErrorCode.unpack_error(e.args[0]))
return info | Unpack the stream contents according to the specified format in `fmt`.
For more information about the `fmt` format see: https://docs.python.org/3/library/struct.html
Args:
fmt (str): format string.
length (int): amount of bytes to read.
Returns:
variable: th... |
356,548 | def zhang_huang_solar(alt, cloud_cover, relative_humidity,
dry_bulb_present, dry_bulb_t3_hrs, wind_speed,
irr_0=1355):
C0, C1, C2, C3, C4, C5, D_COEFF, K_COEFF = 0.5598, 0.4982, \
-0.6762, 0.02842, -0.00317, 0.014, -17.853, 0.843
glob_ir = 0
... | Calculate global horizontal solar irradiance using the Zhang-Huang model.
Note:
[1] Zhang, Q.Y. and Huang, Y.J. 2002. "Development of typical year weather files
for Chinese locations", LBNL-51436, ASHRAE Transactions, Vol. 108, Part 2.
Args:
alt: A solar altitude in degrees.
cl... |
356,549 | def raise_exit_downtime_log_entry(self):
brok = make_monitoring_log(
, "CONTACT DOWNTIME ALERT: %s;STOPPED; "
"Contact has exited from a period of scheduled downtime" % self.get_name()
)
self.broks.append(brok) | Raise CONTACT DOWNTIME ALERT entry (info level)
Format is : "CONTACT DOWNTIME ALERT: *get_name()*;STOPPED;
Contact has entered a period of scheduled downtime"
Example : "CONTACT DOWNTIME ALERT: test_contact;STOPPED;
Contact has entered a period of scheduled down... |
356,550 | def to_potential(f):
number
if is_potential(f): return f
elif f is Ellipsis: return identity
elif pimms.is_array(f, ): return const_potential(f)
elif isinstance(f, tuple) and len(f) == 2: return PotentialLambda(f[0], f[1])
else: raise ValueError() | to_potential(f) yields f if f is a potential function; if f is not, but f can be converted to
a potential function, that conversion is performed then the result is yielded.
to_potential(Ellipsis) yields a potential function whose output is simply its input (i.e., the
identity function).
to_potential... |
356,551 | def factory(data):
if not in data:
raise exceptions.UnknownAPIResource()
for reconstituable_api_resource_type in ReconstituableAPIResource.__subclasses__():
if reconstituable_api_resource_type.object_type == data[]:
return reconstituable_api_resource_ty... | Try to reconstruct the APIResource from its data.
:param data: The APIResource data
:type data: dict
:return: The guessed APIResource
:raise
exceptions.UnkownAPIResource when it's impossible to reconstruct the APIResource from its data. |
356,552 | def index_to_slice(idx, idx_min=None, idx_max=None, step=None, pad=True):
idx_fixed = fix_frames(idx, idx_min, idx_max, pad=pad)
return [slice(start, end, step) for (start, end) in zip(idx_fixed, idx_fixed[1:])] | Generate a slice array from an index array.
Parameters
----------
idx : list-like
Array of index boundaries
idx_min : None or int
idx_max : None or int
Minimum and maximum allowed indices
step : None or int
Step size for each slice. If `None`, then the default
... |
356,553 | def img(self):
if self._img is not None:
return self._img
self._img = cv2.cvtColor(self.original_img, cv2.COLOR_BGR2RGB)
if self.border_width and self.border_colour is not None:
cv2.rectangle(self._img, (0, 0), (self.width-1, self.height-1),
... | return a cv image for the thumbnail |
356,554 | def observers(self):
ret = []
for player in self.players:
try:
if player.observer: ret.append(player)
except: pass
return ret | the players who are actually observers |
356,555 | def update_nio(self, port_number, nio):
bridge_name = "{}-{}".format(self._id, port_number)
if self._ubridge_hypervisor and self._ubridge_hypervisor.is_running():
yield from self._ubridge_apply_filters(bridge_name, nio.filters) | Update an nio on this node
:param nio: NIO instance to add
:param port_number: port to allocate for the NIO |
356,556 | def move_to_other_side(self, init_slab, index_of_sites):
slab = init_slab.copy()
h = self._proj_height
p = h/self.parent.lattice.d_hkl(self.miller_index)
if self.in_unit_planes:
nlayers_slab = int(math.ceil(self.min_slab_size / p))
nla... | This method will Move a set of sites to the
other side of the slab (opposite surface).
Arg:
init_slab (structure): A structure object representing a slab.
index_of_sites (list of ints): The list of indices representing
the sites we want to move to the other side.... |
356,557 | def view_global_gmfs(token, dstore):
imtls = dstore[].imtls
row = dstore[][].mean(axis=0)
return rst_table([row], header=imtls) | Display GMFs averaged on everything for debugging purposes |
356,558 | def subplots(figures,shape=None,
shared_xaxes=False, shared_yaxes=False,
start_cell=, theme=None,base_layout=None,
**kwargs):
if not isinstance(figures,list):
figures=[figures]
if shape:
rows,cols=shape
if len(figures)>rows*cols:
raise Exception("Invalid shape for the number of figures g... | Generates a subplot view for a set of figures
This is a wrapper for plotly.tools.make_subplots
Parameters:
-----------
figures : [Figures]
List of Plotly Figures
shape : (rows,cols)
Tuple indicating the size of rows and columns
If omitted then the layout is automatically set
shared_xaxes : bool
As... |
356,559 | def run_bcl2fastq(run_folder, ss_csv, config):
bc_dir = os.path.join(run_folder, "Data", "Intensities", "BaseCalls")
output_dir = os.path.join(run_folder, "fastq")
if not os.path.exists(os.path.join(output_dir, "Makefile")):
subprocess.check_call(["configureBclToFastq.pl", "--no-eamss",
... | Run bcl2fastq for de-multiplexing and fastq generation.
run_folder -- directory of Illumina outputs
ss_csv -- Samplesheet CSV file describing samples. |
356,560 | def rescale(self, fun):
if self.bands != 1:
raise ValueError()
mat = self.matrix()
scaled = fun(mat)
self.assign(scaled, band=0) | perform raster computations with custom functions and assign them to the existing raster object in memory
Parameters
----------
fun: function
the custom function to compute on the data
Examples
--------
>>> with Raster('filename') as ras:
>>> ras... |
356,561 | def delete_trigger(self, trigger):
assert trigger is not None
assert isinstance(trigger.id, str), "Value must be a string"
status, _ = self.http_client.delete(
NAMED_TRIGGER_URI % trigger.id,
params={: self.API_key},
headers={: }) | Deletes from the Alert API the trigger record identified by the ID of the provided
`pyowm.alertapi30.trigger.Trigger`, along with all related alerts
:param trigger: the `pyowm.alertapi30.trigger.Trigger` object to be deleted
:type trigger: `pyowm.alertapi30.trigger.Trigger`
:returns: `N... |
356,562 | def open_args(subparsers):
parser = subparsers.add_parser(
,
help=,
description=open_args.__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.set_defaults(run_command=open_cmd)
parser.add_argument(, nargs=,
help="Path or ... | The `mp open` command will open a resource with the system application, such as Excel or OpenOffice |
356,563 | def emission_lock(self, name):
e = self.__property_events.get(name)
if e is None:
e = self.__events[name]
return e.emission_lock | Holds emission of events and dispatches the last event on release
The context manager returned will store the last event data called by
:meth:`emit` and prevent callbacks until it exits. On exit, it will
dispatch the last event captured (if any)::
class Foo(Dispatcher):
... |
356,564 | def read_dotenv(dotenv=None, override=False):
if dotenv is None:
frame_filename = sys._getframe().f_back.f_code.co_filename
dotenv = os.path.join(os.path.dirname(frame_filename), )
if os.path.isdir(dotenv) and os.path.isfile(os.path.join(dotenv, )):
dotenv = os.path.join(dotenv, )
... | Read a .env file into os.environ.
If not given a path to a dotenv path, does filthy magic stack backtracking
to find manage.py and then find the dotenv.
If tests rely on .env files, setting the overwrite flag to True is a safe
way to ensure tests run consistently across all environments.
:param o... |
356,565 | def delete_secret(namespace, name, apiserver_url=None, force=True):
**
ret = {: name, : True, : , : {}}
apiserver_url = _guess_apiserver(apiserver_url)
if apiserver_url is None:
return False
if not _get_namespaces(apiserver_url, namespace):
return {: name, : False,
... | .. versionadded:: 2016.3.0
Delete kubernetes secret in the defined namespace. Namespace is the mandatory parameter as well as name.
CLI Example:
.. code-block:: bash
salt '*' k8s.delete_secret namespace_name secret_name
salt '*' k8s.delete_secret namespace_name secret_name http://kube-m... |
356,566 | def get_ini(self, incl_unset=False):
configp = configparser.ConfigParser(allow_no_value=True)
configp.read_dict(self._config)
with StringIO() as config_ini:
if self._parser:
self._parser.set_defaults(
**self.get_section(self.root_section)... | Return the config dictionary in INI format
Args:
incl_unset (bool): include variables with no defaults.
Returns:
str: string of the config file in INI format |
356,567 | def prune_clusters(clusters, index, n=3):
torem = set(c for c in clusters if c.size < n)
pruned_clusters = [c for c in clusters if c.size >= n]
terms_torem = []
for term, clusters in index.items():
index[term] = clusters - torem
if len(index[term]) == 0:
terms_torem.appe... | Delete clusters with fewer than n elements. |
356,568 | def setCenter(self, loc):
offset = self.getCenter().getOffset(loc)
return self.setLocation(self.getTopLeft().offset(offset)) | Move this region so it is centered on ``loc`` |
356,569 | def BuildApprovalUrn(self, approval_id):
event = rdf_events.AuditEvent(
user=self.token.username,
action="CLIENT_APPROVAL_REQUEST",
client=self.subject_urn,
description=self.reason)
events.Events.PublishEvent("Audit", event, token=self.token)
return self.ApprovalUrnBuil... | Builds approval object urn. |
356,570 | def plot3d(self, x, y, z, vx=None, vy=None, vz=None, vwhat=None, limits=None, grid=None, what="count(*)", shape=128, selection=[None, True], f=None,
vcount_limits=None,
smooth_pre=None, smooth_post=None, grid_limits=None, normalize="normalize", colormap="afmhot",
figure_key=... | Use at own risk, requires ipyvolume |
356,571 | def stake(self, confidence, value, tournament=1):
query =
arguments = {: ,
: str(confidence),
: "somepassword",
: self.get_current_round(),
: str(value),
: tournament}
result = sel... | Participate in the staking competition.
Args:
confidence (float or str): your confidence (C) value
value (float or str): amount of NMR you are willing to stake
tournament (int): ID of the tournament (optional, defaults to 1)
Returns:
dict: stake informat... |
356,572 | def validate_queues(queues):
if not isinstance(queues, dict):
raise exceptions.ConfigurationException(
" must be a dictionary mapping queue names to settings."
)
for queue, settings in queues.items():
if not isinstance(settings, dict):
raise exceptions.Confi... | Validate the queues configuration.
Raises:
exceptions.ConfigurationException: If the configuration provided is of an
invalid format. |
356,573 | def get_parsed_query(self):
return .format(
self.backend.dataset_index.get_parsed_query()[0],
self.backend.partition_index.get_parsed_query()[0]) | Returns string with last query parsed. Assuming called after search_datasets. |
356,574 | def checkout(cwd,
remote,
target=None,
user=None,
username=None,
password=None,
*opts):
*
opts += (remote,)
if target:
opts += (target,)
return _run_svn(, cwd, user, username, password, opts) | Download a working copy of the remote Subversion repository
directory or file
cwd
The path to the Subversion repository
remote : None
URL to checkout
target : None
The name to give the file or directory working copy
Default: svn uses the remote basename
user : Non... |
356,575 | def send(self, topic, kmsg):
try:
self.client.do_request(
method="POST", params=dict(format="raw"),
path="/topic/{}".format(topic),
data=kmsg.MARSHMALLOW_SCHEMA.dump(kmsg)
)
result = Result(
uuid=kmsg.uu... | Send the message into the given topic
:param str topic: a kafka topic
:param ksr.transport.Message kmsg: Message to serialize
:return: Execution result
:rtype: kser.result.Result |
356,576 | def duplicate_statements(model, oldorigin, neworigin, rfilter=None):
for o, r, t, a in model.match(oldorigin):
if rfilter is None or rfilter(o, r, t, a):
model.add(I(neworigin), r, t, a)
return | Take links with a given origin, and create duplicate links with the same information but a new origin
:param model: Versa model to be updated
:param oldres: resource IRI to be duplicated
:param newres: origin resource IRI for duplication
:return: None |
356,577 | def convert_error(exc_src, exc_dest):
def wrap(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except exc_dest:
raise
except exc_src as err:
reraise(exc_dest, err, sys.exc_i... | A decorator for reraising exceptions with a different type.
Mostly useful for IOError.
Args:
exc_src (type): The source exception type
exc_dest (type): The target exception type. |
356,578 | def get_instance(self, payload):
return SampleInstance(
self._version,
payload,
assistant_sid=self._solution[],
task_sid=self._solution[],
) | Build an instance of SampleInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance
:rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance |
356,579 | def _iter_qs(self):
cumum = log(self.qrange[1] / self.qrange[0]) / 2**(1/2.)
nplanes = int(max(ceil(cumum / self.deltam), 1))
dq = cumum / nplanes
for i in xrange(nplanes):
yield self.qrange[0] * exp(2**(1/2.) * dq * (i + .5)) | Iterate over the Q values |
356,580 | def setModelData(self, spinBox, model, index):
spinBox.interpretText()
value = spinBox.value()
model.setData(index, value, QtCore.Qt.EditRole) | Gets data from the editor widget and stores it in the specified model at the item index.
Args:
spinBox (QDoubleSpinBox): editor widget.
model (QAbstractItemModel): parent model.
index (QModelIndex): model data index. |
356,581 | def open(self, filename, mode=):
self._raise_if_none()
fn = path_join(self.path, filename)
return open(fn, mode) | Returns file object from given filename. |
356,582 | def extended_euclid(a, b):
if b == 0:
return (1, 0, a)
x0, y0, d = StridedInterval.extended_euclid(b, a % b)
x, y = y0, x0 - (a // b) * y0
return x, y, d | It calculates the GCD of a and b, and two values x and y such that:
a*x + b*y = GCD(a,b).
This code has been taken from the project sympy.
:param a: first integer
:param b: second integer
:return: x,y and the GCD of a and b |
356,583 | def currencies(self) -> CurrenciesAggregate:
if not self.__currencies_aggregate:
self.__currencies_aggregate = CurrenciesAggregate(self.book)
return self.__currencies_aggregate | Returns the Currencies aggregate |
356,584 | def factorize(self):
self.update_w()
if self._compute_h:
self.update_h()
self.W = self.mdl.W
self.H = self.mdl.H
self.ferr = np.zeros(1)
self.ferr[0] = self.mdl.frobenius_norm()
self._print_cur_status( + str(self.... | Do factorization s.t. data = dot(dot(data,beta),H), under the convexity constraint
beta >=0, sum(beta)=1, H >=0, sum(H)=1 |
356,585 | def get_meta_data_index_at_scan_parameter(meta_data_array, scan_parameter_name):
scan_parameter_values = meta_data_array[scan_parameter_name]
diff = np.concatenate(([1], np.diff(scan_parameter_values)))
idx = np.concatenate((np.where(diff)[0], [len(scan_parameter_values)]))
index = np.empty(len(idx... | Takes the analyzed meta_data table and returns the indices where the scan parameter changes
Parameters
----------
meta_data_array : numpy.recordarray
scan_parameter_name : string
Returns
-------
numpy.ndarray:
first dimension: scan parameter value
second dimension: index wh... |
356,586 | def is_valid_pid_to_be_updated(did):
if not d1_gmn.app.did.is_valid_pid_to_be_updated(did):
raise d1_common.types.exceptions.InvalidRequest(
0,
.format(
d1_gmn.app.did.classify_identifier(did), did
),
identifier=did,
) | Assert that ``did`` is the PID of an object that can be updated (obsoleted) with
MNStorage.update() |
356,587 | def ppp_value(simdata, trueval, round=3):
if ndim(trueval) == 1 and ndim(simdata == 2):
return [post_pred_checks(simdata[:, i], trueval[i])
for i in range(len(trueval))]
return (simdata > trueval).mean() | Calculates posterior predictive p-values on data simulated from the posterior
predictive distribution, returning the quantile of the observed data relative to
simulated.
The posterior predictive p-value is computed by:
.. math:: Pr(T(y^{\text{sim}} > T(y) | y)
where T is a test statistic o... |
356,588 | def initialize(self, timestamp=None, user=None, comment=None,
filename=None, source=None, size=None):
self.timestamp = none_or(timestamp, Timestamp)
self.user = none_or(user, User)
self.comment = none_or(comment, str)
self.filename = none... | Upload timestamp : mwtypes.Timestamp | None |
356,589 | def error_map_source(self, kwargs_source, x_grid, y_grid, cov_param):
error_map = np.zeros_like(x_grid)
basis_functions, n_source = self.SourceModel.functions_split(x_grid, y_grid, kwargs_source)
basis_functions = np.array(basis_functions)
if cov_param is not None:
... | variance of the linear source reconstruction in the source plane coordinates,
computed by the diagonal elements of the covariance matrix of the source reconstruction as a sum of the errors
of the basis set.
:param kwargs_source: keyword arguments of source model
:param x_grid: x-axis of... |
356,590 | def getSolutions(self):
domains, constraints, vconstraints = self._getArgs()
if not domains:
return []
return self._solver.getSolutions(domains, constraints, vconstraints) | Find and return all solutions to the problem
Example:
>>> problem = Problem()
>>> problem.getSolutions() == []
True
>>> problem.addVariables(["a"], [42])
>>> problem.getSolutions()
[{'a': 42}]
@return: All solutions for the problem
@rtype: list ... |
356,591 | def disconnect(self, driver):
self.log("SSH disconnect")
try:
self.device.ctrl.sendline()
self.device.ctrl.sendline()
except OSError:
self.log("Protocol already disconnected") | Disconnect using the protocol specific method. |
356,592 | def vn_allocate(call=None, kwargs=None):
t be added to any cluster.
CLI Example:
.. code-block:: bash
salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt
functionThe vn_allocate function must be called with -f or --function.cluster_idcluster_namepathdataBoth the \ and \ arguments w... | Allocates a new virtual network in OpenNebula.
.. versionadded:: 2016.3.0
path
The path to a file containing the template of the virtual network to allocate.
Syntax within the file can be the usual attribute=value or XML. Can be used
instead of ``data``.
data
Contains the ... |
356,593 | def largest_connected_component(volume):
volume = np.asarray(volume)
labels, num_labels = scn.label(volume)
if not num_labels:
raise ValueError()
if num_labels == 1:
return volume.astype(np.bool)
label_count = np.bincount(labels.ravel().astype(np.int))
label_coun... | Return the largest connected component of a 3D array.
Parameters
-----------
volume: numpy.array
3D boolean array.
Returns
--------
volume: numpy.array
3D boolean array with only one connected component. |
356,594 | def error(self, text):
self.logger.error("{}{}".format(self.message_prefix, text)) | Ajout d'un message de log de type ERROR |
356,595 | def top1(scores: mx.nd.NDArray,
offset: mx.nd.NDArray) -> Tuple[mx.nd.NDArray, mx.nd.NDArray, mx.nd.NDArray]:
best_word_indices = mx.nd.cast(mx.nd.argmin(scores, axis=1), dtype=)
values = scores[mx.nd.arange(scores.shape[0], dtype=, ctx=scores.context), best_word_indices]
values = values.resh... | Get the single lowest element per sentence from a `scores` matrix. Expects that
beam size is 1, for greedy decoding.
NOTE(mathmu): The current implementation of argmin in MXNet much slower than topk with k=1.
:param scores: Vocabulary scores for the next beam step. (batch_size * beam_size, target_vocabula... |
356,596 | def update_callback(self, handle, events):
if self._poll is None:
raise RuntimeError()
if not has_callback(self, handle):
raise ValueError()
if events & ~(READABLE|WRITABLE):
raise ValueError(.format(events))
if handle.extra == events:
... | Update the event mask for a callback. |
356,597 | def _get_module(self, line):
for sline in self._source:
if len(sline) > 0 and sline[0] != "!":
rmatch = self.RE_MODULE.match(sline)
if rmatch is not None:
self.modulename = rmatch.group("name")
break
... | Finds the name of the module and retrieves it from the parser cache. |
356,598 | def propinquity_fn_to_study_tree(inp_fn, strip_extension=True):
if strip_extension:
study_tree = .join(inp_fn.split()[:-1])
else:
study_tree = inp_fn
x = study_tree.split()
if len(x) != 2:
msg =
msg = msg.format(study_tree)
raise ValueError(msg)
return... | This should only be called by propinquity - other code should be treating theses
filenames (and the keys that are based on them) as opaque strings.
Takes a filename (or key if strip_extension is False), returns (study_id, tree_id)
propinquity provides a map to look up the study ID and tree ID (and git SHA... |
356,599 | def fg(self) -> np.array:
fg = self._tiles["fg"][..., :3]
if self._order == "F":
fg = fg.transpose(1, 0, 2)
return fg | A uint8 array with the shape (height, width, 3).
You can change the consoles foreground colors by using this array.
Index this array with ``console.fg[i, j, channel] # order='C'`` or
``console.fg[x, y, channel] # order='F'``. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.