Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
19,200 | def calculate_deltat(year, month):
plw = \
\
try:
if np.any((year > 3000) | (year < -1999)):
warnings.warn(plw)
except ValueError:
if (year > 3000) | (year < -1999):
warnings.warn(plw)
except TypeError:
return 0
y = year ... | Calculate the difference between Terrestrial Dynamical Time (TD)
and Universal Time (UT).
Note: This function is not yet compatible for calculations using
Numba.
Equations taken from http://eclipse.gsfc.nasa.gov/SEcat5/deltatpoly.html |
19,201 | def createSegment(self, cell):
return self._createSegment(
self.connections, self.lastUsedIterationForSegment, cell, self.iteration,
self.maxSegmentsPerCell) | Create a :class:`~nupic.algorithms.connections.Segment` on the specified
cell. This method calls
:meth:`~nupic.algorithms.connections.Connections.createSegment` on the
underlying :class:`~nupic.algorithms.connections.Connections`, and it does
some extra bookkeeping. Unit tests should call this metho... |
19,202 | def add_metadata(self, metadata_matrix, meta_index_store):
assert isinstance(meta_index_store, IndexStore)
assert len(metadata_matrix.shape) == 2
assert metadata_matrix.shape[0] == self.get_num_docs()
return self._make_new_term_doc_matrix(new_X=self._X,
... | Returns a new corpus with a the metadata matrix and index store integrated.
:param metadata_matrix: scipy.sparse matrix (# docs, # metadata)
:param meta_index_store: IndexStore of metadata values
:return: TermDocMatrixWithoutCategories |
19,203 | def standardize_input_data(data):
if type(data) == bytes:
data = data.decode()
if type(data) == list:
data = [
el.decode() if type(data) == bytes else el
for el in data
]
return data | Ensure utf-8 encoded strings are passed to the indico API |
19,204 | def _construct_columns(self, column_map):
from sqlalchemy import Column, String, Boolean, Integer, Float, Binary
column_args = []
for key, value in column_map.items():
record_key = value[0]
datatype = value[1]
max_length = valu... | a helper method for constructing the column objects for a table object |
19,205 | def dependencies(self) -> List[Dependency]:
dependencies_str = DB.get_hash_value(self.key, )
dependencies = []
for dependency in ast.literal_eval(dependencies_str):
dependencies.append(Dependency(dependency))
return dependencies | Return the PB dependencies. |
19,206 | def node_style(self, node, **kwargs):
if node not in self.edges:
self.edges[node] = {}
self.nodes[node] = kwargs | Modifies a node style to the dot representation. |
19,207 | def extend_reservation(request, user_id, days=7):
s cart.
'
user = User.objects.get(id=int(user_id))
cart = CartController.for_user(user)
cart.extend_reservation(datetime.timedelta(days=days))
return redirect(request.META["HTTP_REFERER"]) | Allows staff to extend the reservation on a given user's cart. |
19,208 | def field_values(self):
if self._field_values is None:
self._field_values = FieldValueList(
self._version,
assistant_sid=self._solution[],
field_type_sid=self._solution[],
)
return self._field_values | Access the field_values
:returns: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList
:rtype: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList |
19,209 | def _parse_pool_transaction_file(
ledger, nodeReg, cliNodeReg, nodeKeys, activeValidators,
ledger_size=None):
for _, txn in ledger.getAllTxn(to=ledger_size):
if get_type(txn) == NODE:
txn_data = get_payload_data(txn)
nodeName = txn_dat... | helper function for parseLedgerForHaAndKeys |
19,210 | def cis(x: float) -> complex:
r
return np.cos(x) + 1.0j * np.sin(x) | r"""
Implements Euler's formula
:math:`\text{cis}(x) = e^{i \pi x} = \cos(x) + i \sin(x)` |
19,211 | def create_datastream(self, datastream):
raw_datastream = self.http.post(, datastream)
return Schemas.Datastream(datastream=raw_datastream) | To create Datastream
:param datastream: Datastream
:param options: dict |
19,212 | def run_once(self):
packet = _parse_irc_packet(next(self.lines))
for event_handler in list(self.on_packet_received):
event_handler(self, packet)
if packet.command == "PRIVMSG":
if packet.arguments[0].startswith("
for event_handler in list(self.... | This function runs one iteration of the IRC client. This is called in a loop
by the run_loop function. It can be called separately, but most of the
time there is no need to do this. |
19,213 | def devserver_cmd(argv=sys.argv[1:]):
arguments = docopt(devserver_cmd.__doc__, argv=argv)
initialize_config()
app.run(
host=arguments[],
port=int(arguments[]),
debug=int(arguments[]),
) | \
Serve the web API for development.
Usage:
pld-devserver [options]
Options:
-h --help Show this screen.
--host=<host> The host to use [default: 0.0.0.0].
--port=<port> The port to use [default: 5000].
--debug=<debug> Whether or not to use debug mode [default: 0]... |
19,214 | def delete(self, path, data=None):
assert path is not None
assert data is None or isinstance(data, dict)
response = self.conn.request(, path, data,
self._get_headers())
self._last_status = response_status = respo... | Executes a DELETE.
'path' may not be None. Should include the full path to the
resoure.
'data' may be None or a dictionary.
Returns a named tuple that includes:
status: the HTTP status code
json: the returned JSON-HAL
If the key was not set, throws an APIConfi... |
19,215 | def lcm(*numbers):
n = 1
for i in numbers:
n = (i * n) // gcd(i, n)
return n | Return lowest common multiple of a sequence of numbers.
Args:
\*numbers: Sequence of numbers.
Returns:
(int) Lowest common multiple of numbers. |
19,216 | def listBlockSummaries(self, block_name="", dataset="", detail=False):
if bool(dataset)+bool(block_name)!=1:
dbsExceptionHandler("dbsException-invalid-input2",
dbsExceptionCode["dbsException-invalid-input2"],
self.logger.except... | API that returns summary information like total size and total number of events in a dataset or a list of blocks
:param block_name: list block summaries for block_name(s)
:type block_name: str, list
:param dataset: list block summaries for all blocks in dataset
:type dataset: str
... |
19,217 | def emit(self):
i = self.options.rand.get_weighted_random_index(self._weights)
return self._transcriptome.transcripts[i] | Get a mapping from a transcript
:return: One random Transcript sequence
:rtype: sequence |
19,218 | def merge_entity(self, entity, if_match=):
request = _merge_entity(entity, if_match, self._require_encryption,
self._key_encryption_key)
self._add_to_batch(entity[], entity[], request) | Adds a merge entity operation to the batch. See
:func:`~azure.storage.table.tableservice.TableService.merge_entity` for more
information on merges.
The operation will not be executed until the batch is committed.
:param entity:
The entity to merge. Could be a dict... |
19,219 | def save_df_output(
df_output: pd.DataFrame,
freq_s: int = 3600,
site: str = ,
path_dir_save: Path = Path(),)->list:
.RunControl.nml
list_path_save = []
list_group = df_output.columns.get_level_values().unique()
list_grid = df_output.index.get_level_values().unique()
... | save supy output dataframe to txt files
Parameters
----------
df_output : pd.DataFrame
output dataframe of supy simulation
freq_s : int, optional
output frequency in second (the default is 3600, which indicates the a txt with hourly values)
path_dir_save : Path, optional
dir... |
19,220 | def setup(self, in_name=None, out_name=None, required=None, hidden=None,
multiple=None, defaults=None):
if in_name is not None:
self.in_name = in_name if isinstance(in_name, list) else [in_name]
if out_name is not None:
self.out_name = out_name
if... | Set the options of the block.
Only the not None given options are set
.. note:: a block may have multiple inputs but have only one output
:param in_name: name(s) of the block input data
:type in_name: str or list of str
:param out_name: name of the block output data
:ty... |
19,221 | def _protected_division(x1, x2):
with np.errstate(divide=, invalid=):
return np.where(np.abs(x2) > 0.001, np.divide(x1, x2), 1.) | Closure of division (x1/x2) for zero denominator. |
19,222 | def init_logger(self):
if not self.result_logger:
if not os.path.exists(self.local_dir):
os.makedirs(self.local_dir)
if not self.logdir:
self.logdir = tempfile.mkdtemp(
prefix="{}_{}".format(
str(self)[... | Init logger. |
19,223 | def ionic_strength(mis, zis):
r
return 0.5*sum([mi*zi*zi for mi, zi in zip(mis, zis)]) | r'''Calculate the ionic strength of a solution in one of two ways,
depending on the inputs only. For Pitzer and Bromley models,
`mis` should be molalities of each component. For eNRTL models,
`mis` should be mole fractions of each electrolyte in the solution.
This will sum to be much less than 1.
.... |
19,224 | def __compute_evolution(
df,
id_cols,
value_col,
date_col=None,
freq=1,
compare_to=None,
method=,
format=,
offseted_suffix=,
evolution_col_name=,
how=,
fillna=None,
raise_duplicate_error=True
):
if date_col is not None:
is_date_to_format = isinstance(... | Compute an evolution column :
- against a period distant from a fixed frequency.
- against a part of the df
Unfortunately, pandas doesn't allow .change() and .pct_change() to be
executed with a MultiIndex.
Args:
df (pd.DataFrame):
id_cols (list(str)):
value_col (str... |
19,225 | def license_present(name):
ret = {: name,
: {},
: False,
: }
if not __salt__[]():
ret[] = False
ret[] =
return ret
licenses = [l[] for l in __salt__[]()]
if name in licenses:
ret[] = True
ret[] = .format(name)
retu... | Ensures that the specified PowerPath license key is present
on the host.
name
The license key to ensure is present |
19,226 | def output(self, output, accepts, set_http_code, set_content_type):
graph = Decorator._get_graph(output)
if graph is not None:
output_mimetype, output_format = self.format_selector.decide(accepts, graph.context_aware)
serialized = graph.serialize(format=output_format)
set_content_type(outp... | Formats a response from a WSGI app to handle any RDF graphs
If a view function returns a single RDF graph, serialize it based on Accept header
If it's not an RDF graph, return it without any special handling |
19,227 | def centroid_2dg(data, error=None, mask=None):
gfit = fit_2dgaussian(data, error=error, mask=mask)
return np.array([gfit.x_mean.value, gfit.y_mean.value]) | Calculate the centroid of a 2D array by fitting a 2D Gaussian (plus
a constant) to the array.
Invalid values (e.g. NaNs or infs) in the ``data`` or ``error``
arrays are automatically masked. The mask for invalid values
represents the combination of the invalid-value masks for the
``data`` and ``er... |
19,228 | def statement(self):
return (self.assignment ^ self.expression) + Suppress(
self.syntax.terminator) | A terminated relational algebra statement. |
19,229 | def parse_option(self, option, block_name, *values):
_extra_subs = (, , )
if len(values) == 0:
raise ValueError
for value in values:
value = value.lower()
domain = _RE_WWW_SUB.sub(, d... | Parse domain values for option. |
19,230 | def state(self, new_state):
with self.lock:
self._state.exit()
self._state = new_state
self._state.enter() | Set the state. |
19,231 | def list_all_customer_groups(cls, **kwargs):
kwargs[] = True
if kwargs.get():
return cls._list_all_customer_groups_with_http_info(**kwargs)
else:
(data) = cls._list_all_customer_groups_with_http_info(**kwargs)
return data | List CustomerGroups
Return a list of CustomerGroups
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_customer_groups(async=True)
>>> result = thread.get()
:param async bool
... |
19,232 | def AddShadow(self, fileset):
shadow = fileset.get("/etc/shadow")
if shadow:
self._ParseFile(shadow, self.ParseShadowEntry)
else:
logging.debug("No /etc/shadow file.") | Add the shadow entries to the shadow store. |
19,233 | def get_content_slug_by_slug(self, slug):
content = self.filter(type=, body=slug)
if settings.PAGE_USE_SITE_ID:
content = content.filter(page__sites__id=global_settings.SITE_ID)
try:
content = content.latest()
except self.model.DoesNotExist:
r... | Returns the latest :class:`Content <pages.models.Content>`
slug object that match the given slug for the current site domain.
:param slug: the wanted slug. |
19,234 | def build(self):
keys = self._param_grid.keys()
grid_values = self._param_grid.values()
def to_key_value_pairs(keys, values):
return [(key, key.typeConverter(value)) for key, value in zip(keys, values)]
return [dict(to_key_value_pairs(keys, prod)) for prod in itert... | Builds and returns all combinations of parameters specified
by the param grid. |
19,235 | def luminosity_integral(self, x, axis_ratio):
r = x * axis_ratio
return 2 * np.pi * r * self.intensities_from_grid_radii(x) | Routine to integrate the luminosity of an elliptical light profile.
The axis ratio is set to 1.0 for computing the luminosity within a circle |
19,236 | def insertions_from_masked(seq):
insertions = []
prev = True
for i, base in enumerate(seq):
if base.isupper() and prev is True:
insertions.append([])
prev = False
elif base.islower():
insertions[-1].append(i)
prev = True
return [[min(i... | get coordinates of insertions from insertion-masked sequence |
19,237 | def writeCleanup(self, varBind, **context):
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger( % (self, name, val)))
cbFun = context[]
self.branchVersionId += 1
instances = context[].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTRO... | Finalize Managed Object Instance modification.
Implements the successful third step of the multi-step workflow of the
SNMP SET command processing (:RFC:`1905#section-4.2.5`).
The goal of the third (successful) phase is to seal the new state of the
requested Managed Object Instance. Onc... |
19,238 | def should_stop(self, result):
if result.get(DONE):
return True
for criteria, stop_value in self.stopping_criterion.items():
if criteria not in result:
raise TuneError(
"Stopping criteria {} not provided in result {}.".format(
... | Whether the given result meets this trial's stopping criteria. |
19,239 | def set_genre(self, genre):
self._set_attr(TCON(encoding=3, text=str(genre))) | Sets song's genre
:param genre: genre |
19,240 | def drop_if(df, fun):
def _filter_f(col):
try:
return fun(df[col])
except:
return False
cols = list(filter(_filter_f, df.columns))
return df.drop(cols, axis=1) | Drops columns where fun(ction) is true
Args:
fun: a function that will be applied to columns |
19,241 | def resolve_orm_path(model, orm_path):
bits = orm_path.split()
endpoint_model = reduce(get_model_at_related_field, [model] + bits[:-1])
if bits[-1] == :
field = endpoint_model._meta.pk
else:
field = endpoint_model._meta.get_field(bits[-1])
return field | Follows the queryset-style query path of ``orm_path`` starting from ``model`` class. If the
path ends up referring to a bad field name, ``django.db.models.fields.FieldDoesNotExist`` will
be raised. |
19,242 | def major_flux(self, fraction=0.9):
r
(paths, pathfluxes) = self.pathways(fraction=fraction)
return self._pathways_to_flux(paths, pathfluxes, n=self.nstates) | r"""Returns the main pathway part of the net flux comprising
at most the requested fraction of the full flux. |
19,243 | def pprint(self, index=False, delimiter=):
lines = _build_tree_string(self, 0, index, delimiter)[0]
print( + .join((line.rstrip() for line in lines))) | Pretty-print the binary tree.
:param index: If set to True (default: False), display level-order_
indexes using the format: ``{index}{delimiter}{value}``.
:type index: bool
:param delimiter: Delimiter character between the node index and
the node value (default: '-').
... |
19,244 | def get(self, id, seq, line):
schema = HighlightSchema()
resp = self.service.get_id(self._base(id, seq), line)
return self.service.decode(schema, resp) | Get a highlight.
:param id: Result ID as an int.
:param seq: TestResult sequence ID as an int.
:param line: Line number in TestResult's logfile as an int.
:return: :class:`highlights.Highlight <highlights.Highlight>` object |
19,245 | def deleteMember(self, address, id, headers=None, query_params=None, content_type="application/json"):
uri = self.client.base_url + "/network/"+id+"/member/"+address
return self.client.delete(uri, None, headers, query_params, content_type) | Delete member from network
It is method for DELETE /network/{id}/member/{address} |
19,246 | def request(key, features, query, timeout=5):
data = {}
data[] = key
data[] = .join([f for f in features if f in FEATURES])
data[] = quote(query)
data[] =
r = requests.get(API_URL.format(**data), timeout=timeout)
results = json.loads(_unicode(r.content))
return results | Make an API request
:param string key: API key to use
:param list features: features to request. It must be a subset of :data:`FEATURES`
:param string query: query to send
:param integer timeout: timeout of the request
:returns: result of the API request
:rtype: dict |
19,247 | def _ztanh(Np: int, gridmin: float, gridmax: float) -> np.ndarray:
x0 = np.linspace(0, 3.14, Np)
return np.tanh(x0)*gridmax+gridmin | typically call via setupz instead |
19,248 | def predecesors_pattern(element, root):
def is_root_container(el):
return el.parent.parent.getTagName() == ""
if not element.parent or not element.parent.parent or \
is_root_container(element):
return []
trail = [
[
element.parent.parent.getTagName(),
... | Look for `element` by its predecesors.
Args:
element (obj): HTMLElement instance of the object you are looking for.
root (obj): Root of the `DOM`.
Returns:
list: ``[PathCall()]`` - list with one :class:`PathCall` object (to \
allow use with ``.extend(predecesors_pattern()... |
19,249 | def _append_to_scalar_dict(self, tag, scalar_value, global_step, timestamp):
if tag not in self._scalar_dict.keys():
self._scalar_dict[tag] = []
self._scalar_dict[tag].append([timestamp, global_step, float(scalar_value)]) | Adds a list [timestamp, step, value] to the value of `self._scalar_dict[tag]`.
This allows users to store scalars in memory and dump them to a json file later. |
19,250 | def on_mouse_wheel(self, event):
state = self.state
if not state.can_zoom:
return
mousepos = self.image_coordinates(event.GetPosition())
rotation = event.GetWheelRotation() / event.GetWheelDelta()
oldzoom = self.zoom
if rotation > 0:
self.... | handle mouse wheel zoom changes |
19,251 | def _bfs(root_node, process_node):
from collections import deque
seen_nodes = set()
next_nodes = deque()
seen_nodes.add(root_node)
next_nodes.append(root_node)
while next_nodes:
current_node = next_nodes.popleft()
process_node(current_node)
for child_n... | Implementation of Breadth-first search (BFS) on caffe network DAG
:param root_node: root node of caffe network DAG
:param process_node: function to run on each node |
19,252 | def Copier(source, destination):
if source.type == and destination.type == :
return LocalCopier(source, destination)
elif source.type == and destination.type == :
return Local2GoogleStorageCopier(source, destination)
elif source.type == and destination.type == :
return Googl... | Factory method to select the right copier for a given source and destination. |
19,253 | def handle(self):
mapreduce_name = self._get_required_param("name")
mapper_input_reader_spec = self._get_required_param("mapper_input_reader")
mapper_handler_spec = self._get_required_param("mapper_handler")
mapper_output_writer_spec = self.request.get("mapper_output_writer")
mapper_params... | Handles start request. |
19,254 | def download_photo_async(photo):
photo_id = photo[]
photo_title = photo[]
download_url = get_photo_url(photo_id)
photo_format = download_url.split()[-1]
photo_title = photo_title + + photo_format
file_path = directory + os.sep + photo_title
logger.info(, photo_title.encode())
req =... | Download a photo to the the path(global varialbe `directory`)
:param photo: The photo information include id and title
:type photo: dict |
19,255 | def project_data(self):
from pyny3d.utils import sort_numpy
proj = self.light_vor.astype(float)
map_ = np.vstack((self.t2vor_map, self.integral)).T
map_sorted = sort_numpy(map_)
n_points = map_sorted.shape[0]
for i in range(proj.shape[0... | Assign the sum of ``.integral``\* to each sensible point in the
``pyny.Space`` for the intervals that the points are visible to
the Sun.
The generated information is stored in:
* **.proj_vor** (*ndarray*): ``.integral`` projected to the
Voronoi diagram.
... |
19,256 | def ignore_path(path, ignore_list=None, whitelist=None):
if ignore_list is None:
return True
should_ignore = matches_glob_list(path, ignore_list)
if whitelist is None:
return should_ignore
return should_ignore and not matches_glob_list(path, whitelist) | Returns a boolean indicating if a path should be ignored given an
ignore_list and a whitelist of glob patterns. |
19,257 | def register(self, reg_data, retry=True, interval=1, timeout=3):
if len(reg_data["resources"]) == 0:
_logger.debug("%s no need to register due to no resources" %
(reg_data["name"]))
return
def _register():
try:
resp ... | register function
retry
True, infinity retries
False, no retries
Number, retries times
interval
time period for retry
return
False if no success
Tunnel if success |
19,258 | def _split_python(python):
python = _preprocess(python)
if not python:
return []
lexer = PythonSplitLexer()
lexer.read(python)
return lexer.chunks | Split Python source into chunks.
Chunks are separated by at least two return lines. The break must not
be followed by a space. Also, long Python strings spanning several lines
are not splitted. |
19,259 | def info(gandi, resource, id, value):
output_keys = [, ]
if id:
output_keys.append()
if value:
output_keys.append()
ret = []
for item in resource:
sshkey = gandi.sshkey.info(item)
ret.append(output_sshkey(gandi, sshkey, output_keys))
return ret | Display information about an SSH key.
Resource can be a name or an ID |
19,260 | def run(self, messages):
if self.args.local:
return
if self.assignment.endpoint not in self.SUPPORTED_ASSIGNMENTS:
message = "{0} does not support hinting".format(self.assignment.endpoint)
log.info(message)
if self.args.hint:
... | Determine if a student is elgible to recieve a hint. Based on their
state, poses reflection questions.
After more attempts, ask if students would like hints. If so, query
the server. |
19,261 | def rows_max(self, size=None, focus=False):
if size is not None:
ow = self._original_widget
ow_size = self._get_original_widget_size(size)
sizing = ow.sizing()
if FIXED in sizing:
self._rows_max_cached = ow.pack(ow_size, focus)[1]
... | Return the number of rows for `size`
If `size` is not given, the currently rendered number of rows is returned. |
19,262 | def legal_status(CASRN, Method=None, AvailableMethods=False, CASi=None):
rListedNon-Domestic Substances List (NDSL)Significant New Activity (SNAc)Ministerial Condition pertaining to this
substanceListed64-17-5DSLLISTEDEINECSLISTEDNLPUNLISTEDSPINLISTEDTSCALISTED
load_law_data()
if not CASi:
... | r'''Looks up the legal status of a chemical according to either a specifc
method or with all methods.
Returns either the status as a string for a specified method, or the
status of the chemical in all available data sources, in the format
{source: status}.
Parameters
----------
CASRN : str... |
19,263 | def share_matrix(locifile, tree=None, nameorder=None):
with open(locifile, ) as locidata:
loci = locidata.read().split("|\n")[:-1]
if tree:
tree = ete.Tree(tree)
tree.ladderize()
snames = tree.get_leaf_names()
lxs, names = _getarray(loci, snames)
elif... | returns a matrix of shared RAD-seq data
Parameters:
-----------
locifile (str):
Path to a ipyrad .loci file.
tree (str):
Path to Newick file or a Newick string representation of
a tree. If used, names will be ordered by the ladderized
tip order.
nameorder (lis... |
19,264 | async def add_unknown_id(self, unknown_id, timeout=OTGW_DEFAULT_TIMEOUT):
cmd = OTGW_CMD_UNKNOWN_ID
unknown_id = int(unknown_id)
if unknown_id < 1 or unknown_id > 255:
return None
ret = await self._wait_for_cmd(cmd, unknown_id, timeout)
if ret is not None:
... | Inform the gateway that the boiler doesn't support the
specified Data-ID, even if the boiler doesn't indicate that
by returning an Unknown-DataId response. Using this command
allows the gateway to send an alternative Data-ID to the boiler
instead.
Return the added ID, or None on ... |
19,265 | def get_repos(self, visibility=github.GithubObject.NotSet, affiliation=github.GithubObject.NotSet, type=github.GithubObject.NotSet, sort=github.GithubObject.NotSet, direction=github.GithubObject.NotSet):
assert visibility is github.GithubObject.NotSet or isinstance(visibility, (str, unicode)), visibili... | :calls: `GET /user/repos <http://developer.github.com/v3/repos>`
:param visibility: string
:param affiliation: string
:param type: string
:param sort: string
:param direction: string
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Reposito... |
19,266 | def create(self, _attributes=None, **attributes):
if _attributes is not None:
attributes.update(_attributes)
instance = self._related.new_instance(attributes)
instance.set_attribute(self.get_plain_foreign_key(), self.get_parent_key())
instance.save()
retu... | Create a new instance of the related model.
:param attributes: The attributes
:type attributes: dict
:rtype: Model |
19,267 | def find_usage(self):
logger.debug("Checking usage for service %s", self.service_name)
self.connect()
for lim in self.limits.values():
lim._reset_usage()
self._find_usage_nodes()
self._find_usage_subnet_groups()
self._find_usage_parameter_groups()
... | Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`. |
19,268 | def post_loader(*decorator_args, serializer):
def wrapped(fn):
@wraps(fn)
def decorated(*args, **kwargs):
return fn(*serializer.load(request.get_json()))
return decorated
if decorator_args and callable(decorator_args[0]):
return wrapped(decorator_args[0])
re... | Decorator to automatically instantiate a model from json request data
:param serializer: The ModelSerializer to use to load data from the request |
19,269 | def undeploy_lambda_alb(self, lambda_name):
print("Undeploying ALB infrastructure...")
try:
self.lambda_client.remove_permission(
FunctionName=lambda_name,
StatementId=lambda_name
)
except botocore.exceptions... | The `zappa undeploy` functionality for ALB infrastructure. |
19,270 | def purge(self, session, checksum):
C = session.query(model.Calculation).get(checksum)
if not C:
return
if C.siblings_count:
C_meta = session.query(model.Metadata).get(checksum)
higher_lookup = {}
more = C.parent
di... | Deletes calc entry by checksum entirely from the database
NB source files on disk are not deleted
NB: this is the PUBLIC method
@returns error |
19,271 | def __convert_key(expression):
if type(expression) is str and len(expression) > 2 and expression[1] == :
expression = eval(expression[2:-1])
return expression | Converts keys in YAML that reference other keys. |
19,272 | def request(self, request):
url = "{}{}".format(self._base_url, request.path)
timeout = self.poll_timeout
if request.stream is True:
timeout = self.stream_timeout
try:
http_response = self._session.request(
request.method,
... | Perform an HTTP request through the context
Args:
request: A v20.request.Request object
Returns:
A v20.response.Response object |
19,273 | def qorts_general_stats (self):
headers = OrderedDict()
headers[] = {
: ,
: ,
: 100,
: 0,
: ,
:
}
headers[] = {
: ,
: ,
:
}
self.general_stats_addcols(se... | Add columns to the General Statistics table |
19,274 | def sql(self):
from fasta.indexed import DatabaseFASTA, fasta_to_sql
db = DatabaseFASTA(self.prefix_path + ".db")
if not db.exists: fasta_to_sql(self.path, db.path)
return db | If you access this attribute, we will build an SQLite database
out of the FASTA file and you will be able access everything in an
indexed fashion, and use the blaze library via sql.frame |
19,275 | def GET_AUTH(self, courseid, aggregationid=):
course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=True)
if course.is_lti():
raise web.notfound()
return self.display_page(course, aggregationid) | Edit a aggregation |
19,276 | def create_from_str(name_and_zone: str):
if _NAME_ZONE_SEGREGATOR not in name_and_zone:
raise ValueError("Users name cannot be blank")
if len(zone) == 0:
raise ValueError("User's zone cannot be blank")
return User(name, zone) | Factory method for creating a user from a string in the form `name#zone`.
:param name_and_zone: the user's name followed by hash followed by the user's zone
:return: the created user |
19,277 | def _versioned_lib_name(env, libnode, version, prefix, suffix, prefix_generator, suffix_generator, **kw):
Verbose = False
if Verbose:
print("_versioned_lib_name: libnode={:r}".format(libnode.get_path()))
print("_versioned_lib_name: version={:r}".format(version))
print("_versioned_l... | For libnode='/optional/dir/libfoo.so.X.Y.Z' it returns 'libfoo.so |
19,278 | def split_by_files(self, valid_names:)->:
"Split the data by using the names in `valid_names` for validation."
if isinstance(self.items[0], Path): return self.split_by_valid_func(lambda o: o.name in valid_names)
else: return self.split_by_valid_func(lambda o: os.path.basename(o) in valid_names) | Split the data by using the names in `valid_names` for validation. |
19,279 | def scheme_specification(cls):
return WSchemeSpecification(
,
WURIComponentVerifier(WURI.Component.path, WURIComponentVerifier.Requirement.optional)
) | :meth:`.WSchemeHandler.scheme_specification` method implementation |
19,280 | def run_script(self, filename, start_opts=None, globals_=None,
locals_=None):
self.mainpyfile = self.core.canonic(filename)
return retval | Run debugger on Python script `filename'. The script may
inspect sys.argv for command arguments. `globals_' and
`locals_' are the dictionaries to use for local and global
variables. If `globals' is not given, globals() (the current
global variables) is used. If `locals_' is not given, it... |
19,281 | def merge_requests_data_to(to, food={}):
if not to:
to.update(food)
to[][] += food[][]
to[][] += food[][]
to[] += food[]
for group_name, urls in food[].items():
if group_name not in to[]:
to[][group_name] = urls
else:
to_urls = to[][group_name]
... | Merge a small analyzed result to a big one, this function will modify the
original ``to`` |
19,282 | def from_raw(self, raw: RawScalar) -> Optional[bytes]:
try:
return base64.b64decode(raw, validate=True)
except TypeError:
return None | Override superclass method. |
19,283 | def get_out_ip_addr(cls, tenant_id):
if tenant_id not in cls.serv_obj_dict:
LOG.error("Fabric not prepared for tenant %s", tenant_id)
return
tenant_obj = cls.serv_obj_dict.get(tenant_id)
return tenant_obj.get_out_ip_addr() | Retrieves the 'out' service subnet attributes. |
19,284 | def __add_text(self, text):
if text is not None and not isinstance(text, six.text_type):
raise TypeError( % text)
sid = self.__new_sid()
location = None
if self.table_type.is_shared:
location = self.__import_location(sid)
token = SymbolToken(text,... | Adds the given Unicode text as a locally defined symbol. |
19,285 | def Dadgostar_Shaw_integral_over_T(T, similarity_variable):
r
a = similarity_variable
a2 = a*a
a11 = -0.3416
a12 = 2.2671
a21 = 0.1064
a22 = -0.3874
a31 = -9.8231E-05
a32 = 4.182E-04
constant = 24.5
S = T*T*0.5*(a2*a32 + a*a31) + T*(a2*a22 + a*a21) + a*constant*(a*a12 + a11)*... | r'''Calculate the integral of liquid constant-pressure heat capacitiy
with the similarity variable concept and method as shown in [1]_.
Parameters
----------
T : float
Temperature of gas [K]
similarity_variable : float
similarity variable as defined in [1]_, [mol/g]
Returns
... |
19,286 | def find_files(path, patterns):
if not isinstance(patterns, (list, tuple)):
patterns = [patterns]
matches = []
for root, dirnames, filenames in os.walk(path):
for pattern in patterns:
for filename in fnmatch.filter(filenames, pattern):
matches.append(os.path... | Returns all files from a given path that matches the pattern or list
of patterns
@type path: str
@param path: A path to traverse
@typ patterns: str|list
@param patterns: A pattern or a list of patterns to match
@rtype: list[str]:
@return: A list of matched files |
19,287 | def _execute_pillar(pillar_name, run_type):
groups = __salt__[](pillar_name)
data = {}
for group in groups:
data[group] = {}
commands = groups[group]
for command in commands:
if isinstance(command, dict):
plugin = next(six.i... | Run one or more nagios plugins from pillar data and get the result of run_type
The pillar have to be in this format:
------
webserver:
Ping_google:
- check_icmp: 8.8.8.8
- check_icmp: google.com
Load:
- check_load: -w 0.8 -c 1
APT:
- ch... |
19,288 | def capability_info(self, name=None):
for r in self.resources:
if (r.capability == name):
return(r)
return(None) | Return information about the requested capability from this list.
Will return None if there is no information about the requested capability. |
19,289 | def msg_name(code):
ids = {v: k for k, v in COMMANDS.items()}
return ids[code] | Convert integer message code into a string name. |
19,290 | def normalize_parameters(params):
key_values = [(utils.escape(k), utils.escape(v)) for k, v in params]
key_values.sort()
parameter_parts = [.format(k, v) for k, v in key_values]
return .join(parameter_parts) | **Parameters Normalization**
Per `section 3.4.1.3.2`_ of the spec.
For example, the list of parameters from the previous section would
be normalized as follows:
Encoded::
+------------------------+------------------+
| Name | Value |
+------------------------+... |
19,291 | def manifest_repr(self, p_num):
prefix = "p" + str(p_num) + "_"
manifest = prefix + "MODE=" + ("IN" if self.type == Type.FILE else "") + "\n"
manifest += prefix + "TYPE=" + str(self.type.value) + "\n"
if self.type == Type.FILE and len(self.choices) > 0:
... | Builds a manifest string representation of the parameters and returns it
:param p_num: int
:return: string |
19,292 | def clear_dir(path):
for f in os.listdir(path):
f_path = os.path.join(path, f)
if os.path.isfile(f_path) or os.path.islink(f_path):
os.unlink(f_path) | Empty out the image directory. |
19,293 | def autogen_explicit_injectable_metaclass(classname, regen_command=None,
conditional_imports=None):
r
import utool as ut
vals_list = []
def make_redirect(func):
src_fmt = r
from utool._internal import meta_util_six
orig_docstr =... | r"""
Args:
classname (?):
Returns:
?:
CommandLine:
python -m utool.util_class --exec-autogen_explicit_injectable_metaclass
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_class import * # NOQA
>>> from utool.util_class import __CLASSTYPE_ATTRIBUTES... |
19,294 | def _sanitize_inputs(self):
ret = {}
if self.inputs is None:
return
if isinstance(self.inputs, dict):
for key, grouping in self.inputs.items():
if not Grouping.is_grouping_sane(grouping):
raise ValueError()
if isinstance(key, HeronComponentSpec):
... | Sanitizes input fields and returns a map <GlobalStreamId -> Grouping> |
19,295 | def machine_to_machine(self):
if self._machine_to_machine is None:
self._machine_to_machine = MachineToMachineList(
self._version,
account_sid=self._solution[],
country_code=self._solution[],
)
return self._machine_to_machi... | Access the machine_to_machine
:returns: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachineList
:rtype: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachineList |
19,296 | def relaxation_matvec(P, p0, obs, times=[1]):
r
times = np.asarray(times)
ind = np.argsort(times)
times = times[ind]
if times[0] < 0:
raise ValueError("Times can not be negative")
dt = times[1:] - times[0:-1]
nt = len(times)
relaxations = np.zeros(nt)
obs_t = 1.... | r"""Relaxation experiment.
The relaxation experiment describes the time-evolution
of an expectation value starting in a non-equilibrium
situation.
Parameters
----------
P : (M, M) ndarray
Transition matrix
p0 : (M,) ndarray (optional)
Initial distribution for a relaxation e... |
19,297 | def expand(obj, relation, seen):
if hasattr(relation, ):
relation = relation.all()
if hasattr(relation, ):
return [expand(obj, item, seen) for item in relation]
if type(relation) not in seen:
return to_json(relation, seen + [type(obj)])
else:
return relation.id | Return the to_json or id of a sqlalchemy relationship. |
19,298 | def triggers_update_many(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/triggers
api_path = "/api/v2/triggers/update_many.json"
return self.call(api_path, method="PUT", data=data, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/triggers#update-many-triggers |
19,299 | def dotter(self):
if self.globalcount <= 80:
sys.stdout.write()
self.globalcount += 1
else:
sys.stdout.write()
self.globalcount = 1 | Prints formatted time to stdout at the start of a line, as well as a "."
whenever the length of the line is equal or lesser than 80 "." long |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.