Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
18,200 | def on_state_changed(self, state):
if state:
self.editor.painted.connect(self._paint_margin)
self.editor.repaint()
else:
self.editor.painted.disconnect(self._paint_margin)
self.editor.repaint() | Connects/Disconnects to the painted event of the editor
:param state: Enable state |
18,201 | def write_index_and_rst_files(self, overwrite: bool = False,
mock: bool = False) -> None:
for f in self.files_to_index:
if isinstance(f, FileToAutodocument):
f.write_rst(
prefix=self.rst_prefix,
suffix... | Writes both the individual RST files and the index.
Args:
overwrite: allow existing files to be overwritten?
mock: pretend to write, but don't |
18,202 | def murmur_hash3_x86_32(data, offset, size, seed=0x01000193):
key = bytearray(data[offset: offset + size])
length = len(key)
nblocks = int(length / 4)
h1 = seed
c1 = 0xcc9e2d51
c2 = 0x1b873593
for block_start in range(0, nblocks * 4, 4):
k1 = key[block_start + 3... | murmur3 hash function to determine partition
:param data: (byte array), input byte array
:param offset: (long), offset.
:param size: (long), byte length.
:param seed: murmur hash seed hazelcast uses 0x01000193
:return: (int32), calculated hash value. |
18,203 | def subdir_findall(dir, subdir):
strip_n = len(dir.split())
path = .join((dir, subdir))
return [.join(s.split()[strip_n:]) for s in setuptools.findall(path)] | Find all files in a subdirectory and return paths relative to dir
This is similar to (and uses) setuptools.findall
However, the paths returned are in the form needed for package_data |
18,204 | def update_event(self, event, uid):
ev_for_change = self.calendar.get(uid)
ev_for_change.content = event
ev_for_change.save() | Edit event
Parameters
----------
event : iCalendar file as a string
(calendar containing one event to be updated)
uid : uid of event to be updated |
18,205 | def get_meta_fields(self, fields, kwargs={}):
fields = to_list(fields)
meta = self.get_meta()
return {field: meta.get(field) for field in fields} | Return a dictionary of metadata fields |
18,206 | def brightness_multi(x, gamma=1, gain=1, is_random=False):
if is_random:
gamma = np.random.uniform(1 - gamma, 1 + gamma)
results = []
for data in x:
results.append(exposure.adjust_gamma(data, gamma, gain))
return np.asarray(results) | Change the brightness of multiply images, randomly or non-randomly.
Usually be used for image segmentation which x=[X, Y], X and Y should be matched.
Parameters
-----------
x : list of numpyarray
List of images with dimension of [n_images, row, col, channel] (default).
others : args
... |
18,207 | def _apply_sources(self):
if self.settings[] == :
f1 = 0.5
else:
f1 = 1
phase = self.project.phases()[self.settings[]]
relax = self.settings[]
for item in self.settings[]:
Ps = self.pores(item)
... | r
Update 'A' and 'b' applying source terms to specified pores
Notes
-----
Applying source terms to 'A' and 'b' is performed after (optionally)
under-relaxing the source term to improve numerical stability. Physics
are also updated before applying source terms to ensure t... |
18,208 | def _reset(self):
self.records = list()
self.featsbyid = dict()
self.featsbyparent = dict()
self.countsbytype = dict() | Clear internal data structure. |
18,209 | def _payload(fields, values):
for field_name, field in fields.items():
if field_name in values:
if isinstance(field, OneToOneField):
values[field_name + ] = (
getattr(values.pop(field_name), , None)
)
elif isinstance(field, One... | Implement the ``*_payload`` methods.
It's frequently useful to create a dict of values that can be encoded to
JSON and sent to the server. Unfortunately, there are mismatches between
the field names used by NailGun and the field names the server expects.
This method provides a default translation that ... |
18,210 | def namedtuple_with_defaults(typename, field_names, default_values=[]):
the_tuple = collections.namedtuple(typename, field_names)
the_tuple.__new__.__defaults__ = (None, ) * len(the_tuple._fields)
if isinstance(default_values, collections.Mapping):
prototype = the_tuple(**default_values)
el... | Create a namedtuple with default values
>>> Node = namedtuple_with_defaults('Node', 'val left right')
>>> Node()
Node(val=None, left=None, right=None)
>>> Node = namedtuple_with_defaults('Node', 'val left right', [1, 2, 3])
>>> Node()
Node(val=1, left=2, right=3)
>>> Node = namedtuple_with_... |
18,211 | def connect(self, source, target, witnesses):
if self.graph.has_edge(source, target):
self.graph[source][target]["label"] += ", " + str(witnesses)
else:
self.graph.add_edge(source, target, label=witnesses) | :type source: integer
:type target: integer |
18,212 | def has_layer(self, class_: Type[L], became: bool=True) -> bool:
return (class_ in self._index or
(became and class_ in self._transformed)) | Test the presence of a given layer type.
:param class_: Layer class you're interested in.
:param became: Allow transformed layers in results |
18,213 | def interval_intersection_width(a, b, c, d):
return max(0, min(b, d) - max(a, c)) | returns the width of the intersection of intervals [a,b] and [c,d]
(thinking of these as intervals on the real number line) |
18,214 | def append_column(self, header, column):
self.insert_column(self._column_count, header, column) | Append a column to end of the table.
Parameters
----------
header : str
Title of the column
column : iterable
Any iterable of appropriate length. |
18,215 | def extraction_to_conll(ex: Extraction) -> List[str]:
ex = split_predicate(ex)
toks = ex.sent.split()
ret = [] * len(toks)
args = [ex.arg1] + ex.args2
rels_and_args = [("ARG{}".format(arg_ind), arg)
for arg_ind, arg in enumerate(args)] + \
[(rel_par... | Return a conll representation of a given input Extraction. |
18,216 | def parse_list_objects_v2(data, bucket_name):
root = S3Element.fromstring(, data)
is_truncated = root.get_child_text().lower() ==
continuation_token = root.get_child_text(,
strict=False)
objects, object_dirs = _parse_objects_from_xml_elts(
... | Parser for list objects version 2 response.
:param data: Response data for list objects.
:param bucket_name: Response for the bucket.
:return: Returns three distinct components:
- List of :class:`Object <Object>`
- True if list is truncated, False otherwise.
- Continuation Token for th... |
18,217 | def op(cls,text,*args,**kwargs):
return cls.fn(text,*args,**kwargs) | This method must be overriden in derived classes |
18,218 | def run_simulations(self, parameter_list, data_folder):
for idx, parameter in enumerate(parameter_list):
current_result = {
: {},
: {}
}
current_result[].update(parameter)
command = [self.script_executable] + [ % (pa... | Run several simulations using a certain combination of parameters.
Yields results as simulations are completed.
Args:
parameter_list (list): list of parameter combinations to simulate.
data_folder (str): folder in which to save subfolders containing
simulation o... |
18,219 | def transform(self, transformer):
self.transformers.append(transformer)
from languageflow.transformer.tagged import TaggedTransformer
if isinstance(transformer, TaggedTransformer):
self.X, self.y = transformer.transform(self.sentences)
if isinstance(transformer, Tfi... | Add transformer to flow and apply transformer to data in flow
Parameters
----------
transformer : Transformer
a transformer to transform data |
18,220 | def addDrizKeywords(self,hdr,versions):
_geom =
_imgnum = 0
for pl in self.parlist:
_imgnum += 1
drizdict = DRIZ_KEYWORDS.copy()
drizdict[][] = pl[][:44]
drizdict[][] = pl[]... | Add drizzle parameter keywords to header. |
18,221 | def applyHotspot(self, lon, lat):
self.loadRealResults()
cut_detect_real = (self.data_real[] >= self.config[self.algorithm][])
lon_real = self.data_real[][cut_detect_real]
lat_real = self.data_real[][cut_detect_real]
cut_hotspot = np.tile(True, len(lon))
for ii ... | Exclude objects that are too close to hotspot
True if passes hotspot cut |
18,222 | def notify(self, level, value, target=None, ntype=None, rule=None):
if target in self.state and level == self.state[target]:
return False
if target not in self.state and level == \
and not self.reactor.options[]:
return False
... | Notify main reactor about event. |
18,223 | def variables(template):
vars = set()
for varlist in TEMPLATE.findall(template):
if varlist[0] in OPERATOR:
varlist = varlist[1:]
varspecs = varlist.split()
for var in varspecs:
var = var.split()[0]
if var.endswith():
... | Returns the set of keywords in a uri template |
18,224 | def leaveEvent(self, event):
if self.__cursor_changed:
QApplication.restoreOverrideCursor()
self.__cursor_changed = False
self.QT_CLASS.leaveEvent(self, event) | If cursor has not been restored yet, do it now |
18,225 | def from_dict(data, ctx):
data = data.copy()
if data.get() is not None:
data[] = \
ctx.order.UnitsAvailableDetails.from_dict(
data[], ctx
)
if data.get() is not None:
data[] = \
ctx.order.Unit... | Instantiate a new UnitsAvailable from a dict (generally from loading a
JSON response). The data used to instantiate the UnitsAvailable is a
shallow copy of the dict passed in, with any complex child types
instantiated appropriately. |
18,226 | def standard_to_absl(level):
if not isinstance(level, int):
raise TypeError(.format(type(level)))
if level < 0:
level = 0
if level < STANDARD_DEBUG:
return STANDARD_DEBUG - level + 1
elif level < STANDARD_INFO:
return ABSL_DEBUG
elif level < STANDARD_WARNING:
return ABSL_INFO
eli... | Converts an integer level from the standard value to the absl value.
Args:
level: int, a Python standard logging level.
Raises:
TypeError: Raised when level is not an integer.
Returns:
The corresponding integer level for use in absl logging. |
18,227 | def get_docs(r_session, url, encoder=None, headers=None, **params):
keys_list = params.pop(, None)
keys = None
if keys_list is not None:
keys = json.dumps({: keys_list}, cls=encoder)
f_params = python_to_couch(params)
resp = None
if keys is not None:
resp = r_sessio... | Provides a helper for functions that require GET or POST requests
with a JSON, text, or raw response containing documents.
:param r_session: Authentication session from the client
:param str url: URL containing the endpoint
:param JSONEncoder encoder: Custom encoder from the client
:param dict head... |
18,228 | def validateAQLQuery(self, query, bindVars = None, options = None) :
"returns the server answer is the query is valid. Raises an AQLQueryError if not"
if bindVars is None :
bindVars = {}
if options is None :
options = {}
payload = { : query, : bindVars, : option... | returns the server answer is the query is valid. Raises an AQLQueryError if not |
18,229 | def compute_log_degrees(brands, exemplars):
counts = Counter()
for followers in brands.values():
counts.update(followers)
counts.update(counts.keys())
for k in counts:
counts[k] = 1. / math.log(counts[k])
return counts | For each follower, let Z be the total number of brands they follow.
Return a dictionary of 1. / log(Z), for each follower. |
18,230 | def _load_history_from_file(path, size=-1):
if size == 0:
return []
if os.path.exists(path):
with codecs.open(path, , encoding=) as histfile:
lines = [line.rstrip() for line in histfile]
if size > 0:
lines = lines[-size:]
... | Load a history list from a file and split it into lines.
:param path: the path to the file that should be loaded
:type path: str
:param size: the number of lines to load (0 means no lines, < 0 means
all lines)
:type size: int
:returns: a list of history items (the li... |
18,231 | def cli(env, identifier):
manager = PlacementManager(env.client)
group_id = helpers.resolve_id(manager.resolve_ids, identifier, )
result = manager.get_object(group_id)
table = formatting.Table(["Id", "Name", "Backend Router", "Rule", "Created"])
table.add_row([
result[],
result... | View details of a placement group.
IDENTIFIER can be either the Name or Id of the placement group you want to view |
18,232 | def build(self, builder):
params = {}
if self.edit_point is not None:
params["EditPoint"] = self.edit_point
if self.used_imputation_method is not None:
params[] = bool_to_yes_no(self.used_imputation_method)
if self.audit_id is not None:
par... | Build XML by appending to builder |
18,233 | def rotate(name, **kwargs):
ret = {: name,
: {},
: None,
: }
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if not in kwargs:
kwargs[] = name
if not in kwargs or not kwargs[]:
if in kwargs and kwargs[]:
if kwargs[].s... | Add a log to the logadm configuration
name : string
alias for entryname
kwargs : boolean|string|int
optional additional flags and parameters |
18,234 | def _get_or_insert(*args, **kwds):
cls, args = args[0], args[1:]
return cls._get_or_insert_async(*args, **kwds).get_result() | Transactionally retrieves an existing entity or creates a new one.
Positional Args:
name: Key name to retrieve or create.
Keyword Args:
namespace: Optional namespace.
app: Optional app ID.
parent: Parent entity key, if any.
context_options: ContextOptions object (not keyword args... |
18,235 | def initLogger():
s Suspenders for initializing a logger
root')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.INFO)
formatter = logging.Formatter("[%(asctime)s] %(levelname)s: %(message)s", "%Y-%m-%d %H:%M:%S")
ch.setFormatter(formatter)
logger... | This code taken from Matt's Suspenders for initializing a logger |
18,236 | def add_job(cls, identifier, queue_name=None, priority=0, queue_model=None,
prepend=False, delayed_for=None, delayed_until=None,
**fields_if_new):
delayed_until = compute_delayed_until(delayed_for, delayed_until)
job_kwargs = {: identifier, : ... | Add a job to a queue.
If this job already exists, check it's current priority. If its higher
than the new one, don't touch it, else move the job to the wanted queue.
Before setting/moving the job to the queue, check for a `delayed_for`
(int/foat/timedelta) or `delayed_until` (datetime) a... |
18,237 | def resolve_return_value_options(self, options):
for key, value in options.items():
if isinstance(value, str) and value.startswith(RETURN_VALUE_OPTION_PREFIX):
path, name = value[len(RETURN_VALUE_OPTION_PREFIX) :].rsplit(".", 1)
result = self._find_result_by_... | Handle dynamic option value lookups in the format ^^task_name.attr |
18,238 | def gps_date_time_send(self, year, month, day, hour, min, sec, clockStat, visSat, useSat, GppGl, sigUsedMask, percentUsed, force_mavlink1=False):
return self.send(self.gps_date_time_encode(year, month, day, hour, min, sec, clockStat, visSat, useSat, GppGl, sigUsedMask, percentUsed), for... | Pilot console PWM messges.
year : Year reported by Gps (uint8_t)
month : Month reported by Gps (uint8_t)
day : Day reported by Gps (uint8_t)
hour : Hour reported by Gps (u... |
18,239 | def metadata_path(self, m_path):
if not m_path:
self.metadata_dir = None
self.metadata_file = None
else:
if not op.exists(m_path):
raise OSError(.format(m_path))
if not op.dirname(m_path):
self.metadata_dir =
... | Provide pointers to the paths of the metadata file
Args:
m_path: Path to metadata file |
18,240 | def sys_info():
p = os.path
path = p.dirname(p.abspath(p.join(__file__, )))
return pprint.pformat(pkg_info(path)) | Return useful information about IPython and the system, as a string.
Example
-------
In [2]: print sys_info()
{'commit_hash': '144fdae', # random
'commit_source': 'repository',
'ipython_path': '/home/fperez/usr/lib/python2.6/site-packages/IPython',
'ipython_version': '0.11.dev',
... |
18,241 | def derivatives(self, x, y, grid_interp_x=None, grid_interp_y=None, f_=None, f_x=None, f_y=None, f_xx=None, f_yy=None, f_xy=None):
n = len(np.atleast_1d(x))
if n <= 1 and np.shape(x) == ():
f_x_out = self.f_x_interp(x, y, grid_interp_x, grid_interp_y, f_x)
... | returns df/dx and df/dy of the function |
18,242 | def vms(message, level=1):
if verbose is not None and verbose != False:
if isinstance(verbose, bool) or (isinstance(verbose, int) and level <= verbose):
std(message) | Writes the specified message *only* if verbose output is enabled. |
18,243 | def get_alerts_unarchived(self):
js = json.dumps({: , : False})
params = urllib.urlencode({: js})
return self._read(self.api_url + , params) | Return a list of Alerts unarchived. |
18,244 | def _implicit_solver(self):
newstate = {}
for varname, value in self.state.items():
if self.use_banded_solver:
newvar = _solve_implicit_banded(value, self._diffTriDiag)
else:
newvar = np.linalg.solve(self._diffTriDiag, v... | Invertes and solves the matrix problem for diffusion matrix
and temperature T.
The method is called by the
:func:`~climlab.process.implicit.ImplicitProcess._compute()` function
of the :class:`~climlab.process.implicit.ImplicitProcess` class and
solves the matrix problem
... |
18,245 | def interpret(self, msg):
for gallery in msg.get(, []):
self.add_folder(gallery)
image_file = msg.get()
if not image_file: return
return self.find_image(image_file) | Try and find the image file
some magic here would be good.
FIXME move elsewhere and make so everyone can use.
interpreter that finds things? |
18,246 | def gatk_variant_filtration(job, vcf_id, filter_name, filter_expression, ref_fasta, ref_fai, ref_dict):
inputs = {: ref_fasta,
: ref_fai,
: ref_dict,
: vcf_id}
work_dir = job.fileStore.getLocalTempDir()
for name, file_store_id in inputs.iteritems():
jo... | Filters VCF file using GATK VariantFiltration. Fixes extra pair of quotation marks in VCF header that
may interfere with other VCF tools.
:param JobFunctionWrappingJob job: passed automatically by Toil
:param str vcf_id: FileStoreID for input VCF file
:param str filter_name: Name of filter for VCF head... |
18,247 | def download_cf_standard_name_table(version, location=None):
if location is None:
location = resource_filename(, )
url = "http://cfconventions.org/Data/cf-standard-names/{0}/src/cf-standard-name-table.xml".format(version)
r = requests.get(url, allow_redirects=True)
if r.status_code == 2... | Downloads the specified CF standard name table version and saves it to file
:param str version: CF standard name table version number (i.e 34)
:param str location: Path/filename to write downloaded xml file to |
18,248 | def get_val(self, x):
try:
if self.subtype == :
return int(round(x[self.col_name]))
else:
if np.isnan(x[self.col_name]):
return self.default_val
return x[self.col_name]
except (ValueError, TypeError):
... | Converts to int. |
18,249 | def parse_charset(header_string):
match = re.search(
r]?([a-z0-9_-]+)',
header_string,
re.IGNORECASE
)
if match:
return match.group(1) | Parse a "Content-Type" string for the document encoding.
Returns:
str, None |
18,250 | def get_ids_in_region(
self, resource, resolution,
x_range, y_range, z_range, time_range=[0, 1]):
return self.service.get_ids_in_region(
resource, resolution, x_range, y_range, z_range, time_range,
self.url_prefix, self.auth, self.session, self.session_se... | Get all ids in the region defined by x_range, y_range, z_range.
Args:
resource (intern.resource.Resource): An annotation channel.
resolution (int): 0 indicates native resolution.
x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
y_range (l... |
18,251 | def markets(self):
with self.client.connect(*self.bestip):
data = self.client.get_markets()
return self.client.to_df(data)
return None | 获取实时市场列表
:return: pd.dataFrame or None |
18,252 | def danke(client, event, channel, nick, rest):
if rest:
rest = rest.strip()
Karma.store.change(rest, 1)
rcpt = rest
else:
rcpt = channel
return f | Danke schön! |
18,253 | def childRecords(self):
if self._childRecords is not None:
return self._childRecords
tree = self.treeWidget()
try:
table, column = tree.hierarchyLookup(self.record())
except AttributeError:
table = None
column = ... | Returns a record set of children for this item based on the record. If
no record set is manually set for this instance, then it will use the
hierarchyColumn value from the tree widget with this record. If no
hierarchyColumn is speified, then a blank record set is returned.
... |
18,254 | def flatten_dict(d, prefix=, sep=):
def apply_and_resolve_conflicts(dest, item, prefix):
for k, v in flatten_dict(item, prefix=prefix, sep=sep).items():
new_key = k
i = 2
while new_key in d:
new_key = .format(key=k, sep=sep, index=i)
i... | In place dict flattening. |
18,255 | def determine_hbonds_for_drawing(self, analysis_cutoff):
self.frequency = defaultdict(int)
for traj in self.hbonds_by_type:
for bond in self.hbonds_by_type[traj]:
if bond["donor_resnm"]!="LIG":
self.frequency[(bond["donor... | Since plotting all hydrogen bonds could lead to a messy plot, a cutoff has to be imple-
mented. In this function the frequency of each hydrogen bond is summated and the total
compared against analysis cutoff - a fraction multiplied by trajectory count. Those
hydrogen bonds that are present for l... |
18,256 | def _http_req_user_agent(self):
try:
return .format(
self.settings[], self.settings[])
except (AttributeError, KeyError):
pass
if hasattr(self, ):
try:
return .format(
self._proces... | Return the User-Agent value to specify in HTTP requests, defaulting
to ``service/version`` if configured in the application settings,
or if used in a consumer, it will attempt to obtain a user-agent from
the consumer's process. If it can not auto-set the User-Agent, it
defaults to ``spro... |
18,257 | def update_path(self):
if WINDOWS:
return self.add_to_windows_path()
export_string = self.get_export_string()
addition = "\n{}\n".format(export_string)
updated = []
profiles = self.get_unix_profiles()
for profile in profiles:
i... | Tries to update the $PATH automatically. |
18,258 | def delete_agent(self, agent_id):
self._check_agent_id(agent_id)
req_url = "{}/agents/{}".format(self._base_url, agent_id)
resp = self._requests_session.delete(req_url)
decoded_resp = self._decode_response(resp)
return decoded_resp | Delete an agent.
:param str agent_id: The id of the agent to delete. It must
be an str containing only characters in "a-zA-Z0-9_-" and
must be between 1 and 36 characters.
:return: agent deleted.
:rtype: dict. |
18,259 | def append(self, other, inplace=False, **kwargs):
if not isinstance(other, MAGICCData):
other = MAGICCData(other, **kwargs)
if inplace:
super().append(other, inplace=inplace)
self.metadata.update(other.metadata)
else:
res = super().append... | Append any input which can be converted to MAGICCData to self.
Parameters
----------
other : MAGICCData, pd.DataFrame, pd.Series, str
Source of data to append.
inplace : bool
If True, append ``other`` inplace, otherwise return a new ``MAGICCData``
in... |
18,260 | def injector_ui_tree_menu_entity_2_json(self, ignore_genealogy=False):
LOGGER.debug("InjectorUITreeEntity.injector_ui_tree_menu_entity_2_json")
if ignore_genealogy:
json_obj = {
: self.id,
: self.value,
: self.type,
: s... | transform this local object to JSON
:param ignore_genealogy: ignore the genealogy of this object if true (awaited format for Ariane server)
:return: the resulting JSON of transformation |
18,261 | def _handle_argument(self, token):
name = None
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.ArgumentSeparator):
name = self._pop()
self._push()
elif isinstance(token, tokens.Ar... | Handle a case where an argument is at the head of the tokens. |
18,262 | def GetNodes(r, bulk=False):
if bulk:
return r.request("get", "/2/nodes", query={"bulk": 1})
else:
nodes = r.request("get", "/2/nodes")
return r.applier(itemgetters("id"), nodes) | Gets all nodes in the cluster.
@type bulk: bool
@param bulk: whether to return all information about all instances
@rtype: list of dict or str
@return: if bulk is true, info about nodes in the cluster,
else list of nodes in the cluster |
18,263 | def _apply_Create(self, change):
ar = _AzureRecord(self._resource_group, change.new)
create = self._dns_client.record_sets.create_or_update
create(resource_group_name=ar.resource_group,
zone_name=ar.zone_name,
relative_record_set_name=ar.relative_record_se... | A record from change must be created.
:param change: a change object
:type change: octodns.record.Change
:type return: void |
18,264 | def _make_summary_tables(self):
try:
self._Bhat
except:
raise Exception("Regression hasnnum_componentsplain')
headers = self._results[0]
table = self._results[1:]
print tabulate(table, headers, tablefmt="rs... | prints the summary of the regression. It shows
the waveform metadata, diagnostics of the fit, and results of the
hypothesis tests for each comparison encoded in the design matrix |
18,265 | def filtered_rows_from_args(self, args):
if len(self.manifests) == 0:
print("fw: No manifests downloaded. Try ")
return None
(filters,remainder) = self.filters_from_args(args)
all = self.all_firmwares()
rows = self.rows_for_firmwares(all)
filter... | extracts filters from args, rows from manifests, returns filtered rows |
18,266 | def version(self):
if not self.__version:
command = (self.name, )
logger.debug(command)
stdout, _ = subprocess.Popen(
command, stdout=subprocess.PIPE).communicate()
version_output = str(stdout)
match = re.search(self.version_pa... | Get the version of MongoDB that this Server runs as a tuple. |
18,267 | def set_state_process(self, context, process):
LOGGER.info( % (context, process))
self.state[context]["process"].append(process) | Method to append process for a context in the IF state.
:param context: It can be a layer purpose or a section (impact
function, post processor).
:type context: str, unicode
:param process: A text explain the process.
:type process: str, unicode |
18,268 | def decimal_day_to_day_hour_min_sec(
self,
daysFloat):
self.log.info(
)
daysInt = int(daysFloat)
hoursFloat = (daysFloat - daysInt) * 24.
hoursInt = int(hoursFloat)
minsFloat = (hoursFloat - hoursInt) * 60.
minsInt = int(minsF... | *Convert a day from decimal format to hours mins and sec*
Precision should be respected.
**Key Arguments:**
- ``daysFloat`` -- the day as a decimal.
**Return:**
- ``daysInt`` -- day as an integer
- ``hoursInt`` -- hour as an integer (None if input precsion... |
18,269 | def fast_boolean(operandA,
operandB,
operation,
precision=0.001,
max_points=199,
layer=0,
datatype=0):
polyA = []
polyB = []
for poly, obj in zip((polyA, polyB), (operandA, operandB)):
if isins... | Execute any boolean operation between 2 polygons or polygon sets.
Parameters
----------
operandA : polygon or array-like
First operand. Must be a ``PolygonSet``, ``CellReference``,
``CellArray``, or an array. The array may contain any of the
previous objects or an array-like[N][2]... |
18,270 | def _set_id_from_xml_frameid(self, xml, xmlpath, var):
e = xml.find(xmlpath)
if e is not None:
setattr(self, var, e.attrib[]) | Set a single variable with the frameids of matching entity |
18,271 | def sparse_surface(self):
if self._method == :
func = voxelize_ray
elif self._method == :
func = voxelize_subdivide
else:
raise ValueError()
voxels, origin = func(
mesh=self._data[],
pitch=self._data[],
max... | Filled cells on the surface of the mesh.
Returns
----------------
voxels: (n, 3) int, filled cells on mesh surface |
18,272 | def begin(self):
if self.start:
self.at_beginning = True
self.pos = 0
else:
self.at_beginning = False
self._new_song()
return self._get_song() | Start over and get a track. |
18,273 | def call(self, callname, data=None, **args):
url = f"{self.url_base}/{callname}"
payload = self.payload.copy()
payload.update(**args)
if data is not None:
payload.update(data)
res = self.session.post(url, data=payload)
if res.status_code > 299:
... | Generic interface to REST apiGeneric interface to REST api
:param callname: query name
:param data: dictionary of inputs
:param args: keyword arguments added to the payload
:return: |
18,274 | def _ann_store_annotations(self, item_with_annotations, node, overwrite=False):
if overwrite is True or overwrite == :
annotated = self._all_get_from_attrs(node, HDF5StorageService.ANNOTATED)
if annotated:
current_attrs = node._v_attrs
f... | Stores annotations into an hdf5 file. |
18,275 | def update_url_params(url, replace_all=False, **url_params):
if not (replace_all is True or replace_all is False):
url_params[] = replace_all
if not url or not url_params:
return url or None
scheme, netloc, url_path, url_query, fragment = _urlsplit(url)
if replace_all is Tr... | :return: url with its query updated from url_query (non-matching params are retained) |
18,276 | def list(self, request, *args, **kwargs):
return super(MergedPriceListItemViewSet, self).list(request, *args, **kwargs) | To get a list of price list items, run **GET** against */api/merged-price-list-items/*
as authenticated user.
If service is not specified default price list items are displayed.
Otherwise service specific price list items are displayed.
In this case rendered object contains {"is_manuall... |
18,277 | def process_text(text, output_fmt=, outbuf=None, cleanup=True, key=,
**kwargs):
nxml_str = make_nxml_from_text(text)
return process_nxml_str(nxml_str, output_fmt, outbuf, cleanup, key,
**kwargs) | Return processor with Statements extracted by reading text with Sparser.
Parameters
----------
text : str
The text to be processed
output_fmt: Optional[str]
The output format to obtain from Sparser, with the two options being
'json' and 'xml'. Default: 'json'
outbuf : Option... |
18,278 | def has_tensor(obj) -> bool:
if isinstance(obj, torch.Tensor):
return True
elif isinstance(obj, dict):
return any(has_tensor(value) for value in obj.values())
elif isinstance(obj, (list, tuple)):
return any(has_tensor(item) for item in obj)
else:
return False | Given a possibly complex data structure,
check if it has any torch.Tensors in it. |
18,279 | def await_message(self, *args, **kwargs) -> :
fut = asyncio.Future()
@self.on_message(*args, **kwargs)
async def handler(message):
fut.set_result(message)
fut.add_done_callback(lambda _: self.remove_message_handler(handler))
return fut | Block until a message matches. See `on_message` |
18,280 | def getFields(self):
d = {}
for i in self._attrsList:
key = i
value = getattr(self, i)
d[key] = value
return d | Returns all the class attributues.
@rtype: dict
@return: A dictionary containing all the class attributes. |
18,281 | def get_definition(self, name):
if name not in SERVICES:
raise ONVIFError( % name)
wsdl_file = SERVICES[name][]
ns = SERVICES[name][]
wsdlpath = os.path.join(self.wsdl_dir, wsdl_file)
if not os.path.isfile(wsdlpath):
raise ONVIFError( % ... | Returns xaddr and wsdl of specified service |
18,282 | def put(self):
return self.manager.put(
id=self.id,
name=self.name,
description=self.description,
command_to_run=self.command_to_run,
environment_variables=self.environment_variables,
required_arguments=self.required_arguments,
... | Updates this task type on the saltant server.
Returns:
:class:`saltant.models.container_task_type.ExecutableTaskType`:
An executable task type model instance representing the task type
just updated. |
18,283 | def errorprint():
try:
yield
except ConfigurationError as e:
click.secho( % e, err=True, fg=)
sys.exit(1) | Print out descriptions from ConfigurationError. |
18,284 | def find_group(self, star, starlist):
star_distance = np.hypot(star[] - starlist[],
star[] - starlist[])
distance_criteria = star_distance < self.crit_separation
return np.asarray(starlist[distance_criteria][]) | Find the ids of those stars in ``starlist`` which are at a
distance less than ``crit_separation`` from ``star``.
Parameters
----------
star : `~astropy.table.Row`
Star which will be either the head of a cluster or an
isolated one.
starlist : `~astropy.tab... |
18,285 | def load(cls, fpath):
module_name = os.path.splitext(os.path.basename(fpath))[0]
sys.path.insert(0, os.path.dirname(fpath))
try:
module = import_module(module_name)
finally:
sys.path = sys.path[1:]
return module | Loads a module and returns its object.
:param str|unicode fpath:
:rtype: module |
18,286 | def recipe(package, repository=None, depends_on=None, release=False,
output_path=None, auto=False, overwrite=False, name=None):
upgrader = InvenioUpgrader()
logger = upgrader.get_logger()
try:
path, found_repository = _upgrade_recipe_find_path(package)
if output_path:
... | Create a new upgrade recipe, for developers. |
18,287 | def parse_string(progression):
acc = 0
roman_numeral =
suffix =
i = 0
for c in progression:
if c == :
acc += 1
elif c == :
acc -= 1
elif c.upper() == or c.upper() == :
roman_numeral += c.upper()
else:
break
... | Return a tuple (roman numeral, accidentals, chord suffix).
Examples:
>>> parse_string('I')
('I', 0, '')
>>> parse_string('bIM7')
('I', -1, 'M7') |
18,288 | def get_queryset(self):
try:
qs = super(UserManager, self).get_queryset()
except AttributeError:
qs = super(UserManager, self).get_query_set()
return qs | Fixes get_query_set vs get_queryset for Django <1.6 |
18,289 | def parse_unit(name, parse_strict=, format=):
if name is None or isinstance(name, units.UnitBase):
return name
try:
return UNRECOGNIZED_UNITS[name]
except KeyError:
try:
return units.Unit(name, parse_strict=)
except ValueError as exc:
... | Attempt to intelligently parse a `str` as a `~astropy.units.Unit`
Parameters
----------
name : `str`
unit name to parse
parse_strict : `str`
one of 'silent', 'warn', or 'raise' depending on how pedantic
you want the parser to be
format : `~astropy.units.format.Base`
... |
18,290 | def editAccountInfo(self, short_name=None, author_name=None, author_url=None):
return self.make_method("editAccountInfo", {
"access_token": self.access_token,
"short_name": short_name,
"author_name": author_name,
"author_url": author_url
}) | Use this method to update information about a Telegraph account.
:param short_name: Optional. New account name.
:type short_name: str
:param author_name: Optional. New default author name used when creating new articles.
:type author_name: str
:param author_url: Option... |
18,291 | def openFile(self, openDQ=False):
if self._im.closed:
if not self._dq.closed:
self._dq.release()
assert(self._dq.closed)
fi = FileExtMaskInfo(clobber=False,
doNotOpenDQ=not openDQ,
im_... | Open file and set up filehandle for image file |
18,292 | def cache_as_field(cache_name):
def cache_wrapper(func):
@functools.wraps(func)
def inner_wrapper(self, *args, **kwargs):
value = getattr(self, cache_name, UndefToken)
if value != UndefToken:
return value
ret = func(self, *args, **kwargs)
... | Cache a functions return value as the field 'cache_name'. |
18,293 | def bhattacharyya(Ks, dim, required, clamp=True, to_self=False):
r
est = required
if clamp:
est = np.minimum(est, 1)
return est | r'''
Estimate the Bhattacharyya coefficient between distributions, based on kNN
distances: \int \sqrt{p q}
If clamp (the default), enforces 0 <= BC <= 1.
Returns an array of shape (num_Ks,). |
18,294 | def pull(self, path, use_sudo=False, user=None, force=False):
if path is None:
raise ValueError("Path to the working copy is needed to pull from a remote repository.")
options = []
if force:
options.append()
options = .join(options)
cmd = % op... | Fetch changes from the default remote repository and merge them.
:param path: Path of the working copy directory. This directory must exist
and be a Git working copy with a default remote to pull from.
:type path: str
:param use_sudo: If ``True`` execute ``git`` with
... |
18,295 | def sequence_set(self) -> SequenceSet:
try:
seqset_crit = next(crit for crit in self.all_criteria
if isinstance(crit, SequenceSetSearchCriteria))
except StopIteration:
return SequenceSet.all()
else:
return seqset_crit.se... | The sequence set to use when finding the messages to match against.
This will default to all messages unless the search criteria set
contains a sequence set. |
18,296 | def parse_refresh_header(self, refresh):
ii = refresh.find(";")
if ii != -1:
pause, newurl_spec = float(refresh[:ii]), refresh[ii+1:]
jj = newurl_spec.find("=")
key = None
if jj != -1:
key, newurl = newurl_spec[:jj], newurl_spec[jj... | >>> parse_refresh_header("1; url=http://example.com/")
(1.0, 'http://example.com/')
>>> parse_refresh_header("1; url='http://example.com/'")
(1.0, 'http://example.com/')
>>> parse_refresh_header("1")
(1.0, None)
>>> parse_refresh_header("blah") # doctest: +IGNORE_EXCEPTI... |
18,297 | def StartingKey(self, evt):
key = evt.GetKeyCode()
ch = None
if key in [
wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2, wx.WXK_NUMPAD3,
wx.WXK_NUMPAD4, wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_NUMPAD7,
wx.WXK_NUMPAD8, wx.WXK_NUMPAD9]:
... | If the editor is enabled by pressing keys on the grid, this will be
called to let the editor do something about that first key if desired. |
18,298 | def temperature(self, what):
self._temperature = units.validate_quantity(what, u.K) | Set temperature. |
18,299 | def estimate(self, significance_level=0.01):
skel, separating_sets = self.estimate_skeleton(significance_level)
pdag = self.skeleton_to_pdag(skel, separating_sets)
model = self.pdag_to_dag(pdag)
return model | Estimates a DAG for the data set, using the PC constraint-based
structure learning algorithm. Independencies are identified from the
data set using a chi-squared statistic with the acceptance threshold of
`significance_level`. PC identifies a partially directed acyclic graph (PDAG), given
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.