Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
20,900 | def camera_list(self, **kwargs):
api = self._api_info[]
payload = dict({
: self._sid,
: api[],
: ,
: api[],
}, **kwargs)
response = self._get_json_with_retry(api[], payload)
cameras = []
for data in response[][]:
... | Return a list of cameras. |
20,901 | def video_set_callbacks(self, lock, unlock, display, opaque):
return libvlc_video_set_callbacks(self, lock, unlock, display, opaque) | Set callbacks and private data to render decoded video to a custom area
in memory.
Use L{video_set_format}() or L{video_set_format_callbacks}()
to configure the decoded format.
@param lock: callback to lock video memory (must not be NULL).
@param unlock: callback to unlock video ... |
20,902 | def main():
if in sys.argv:
print(main.__doc__)
sys.exit()
dir_path = pmag.get_named_arg("-WD", default_val=".")
input_dir_path = pmag.get_named_arg(, )
if not input_dir_path:
input_dir_path = dir_path
in_file = pmag.get_named_arg("-f", default_val="sites.txt")
... | NAME
eqarea_magic.py
DESCRIPTION
makes equal area projections from declination/inclination data
SYNTAX
eqarea_magic.py [command line options]
INPUT
takes magic formatted sites, samples, specimens, or measurements
OPTIONS
-h prints help message and quits
... |
20,903 | def _set_query_data_fast_1(self, page):
self.data[] = page.get()
assessments = page.get()
if assessments:
self.data[] = assessments
extract = page.get()
if extract:
self.data[] = extract
extext = html2text.html2text(extract)
... | set less expensive action=query response data PART 1 |
20,904 | def _merge_points(self, function_address):
try:
new_function = self.kb.functions[function_address]
except KeyError:
return [ ]
if function_address not in self._function_merge_points:
ordered_merge_points = CFGUtils.fin... | Return the ordered merge points for a specific function.
:param int function_address: Address of the querying function.
:return: A list of sorted merge points (addresses).
:rtype: list |
20,905 | def from_df(cls, df_long, df_short):
pop = cls(1,1,1,1,1)
pop.orbpop_long = OrbitPopulation.from_df(df_long)
pop.orbpop_short = OrbitPopulation.from_df(df_short)
return pop | Builds TripleOrbitPopulation from DataFrame
``DataFrame`` objects must be of appropriate form to pass
to :func:`OrbitPopulation.from_df`.
:param df_long, df_short:
:class:`pandas.DataFrame` objects to pass to
:func:`OrbitPopulation.from_df`. |
20,906 | def str_presenter(dmpr, data):
if is_multiline(data):
return dmpr.represent_scalar(, data, style=)
return dmpr.represent_scalar(, data) | Return correct str_presenter to write multiple lines to a yaml field.
Source: http://stackoverflow.com/a/33300001 |
20,907 | def get_tag(self, el):
name = self.get_tag_name(el)
return util.lower(name) if name is not None and not self.is_xml else name | Get tag. |
20,908 | def register(klass):
assert(isinstance(klass, type))
name = klass.__name__.lower()
if name in Optimizer.opt_registry:
warnings.warn(
%
(klass.__module__, klass.__name__,
Optimizer.opt_registry[na... | Registers a new optimizer.
Once an optimizer is registered, we can create an instance of this
optimizer with `create_optimizer` later.
Examples
--------
>>> @mx.optimizer.Optimizer.register
... class MyOptimizer(mx.optimizer.Optimizer):
... pass
>>>... |
20,909 | def status(self):
if self._future.running():
_status = JobStatus.RUNNING
elif self._future.cancelled():
_status = JobStatus.CANCELLED
elif self._future.done():
_status = JobStatus.DONE if self._future.exception() is None else JobStatus.ERROR
... | Gets the status of the job by querying the Python's future
Returns:
qiskit.providers.JobStatus: The current JobStatus
Raises:
JobError: If the future is in unexpected state
concurrent.futures.TimeoutError: if timeout occurred. |
20,910 | def GetStream(data=None):
if len(__mstreams_available__) == 0:
if data:
mstream = MemoryStream(data)
mstream.seek(0)
else:
mstream = MemoryStream()
__mstreams__.append(mstream)
return mstream
mstrea... | Get a MemoryStream instance.
Args:
data (bytes, bytearray, BytesIO): (Optional) data to create the stream from.
Returns:
MemoryStream: instance. |
20,911 | def parse_yaml(self, y):
self._targets = []
if in y:
for t in y[]:
if in t[]:
new_target = WaitTime()
elif in t[]:
new_target = Preceding()
else:
new_target = Condition()
... | Parse a YAML speficication of a message sending object into this
object. |
20,912 | def get_dataset(self, dataset_key):
try:
return self._datasets_api.get_dataset(
*(parse_dataset_key(dataset_key))).to_dict()
except _swagger.rest.ApiException as e:
raise RestApiError(cause=e) | Retrieve an existing dataset definition
This method retrieves metadata about an existing
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:returns: Dataset definition, with all attributes
:rtype: dict
:raises RestApiException: If a ... |
20,913 | def room(model, solution=None, linear=False, delta=0.03, epsilon=1E-03):
with model:
add_room(model=model, solution=solution, linear=linear, delta=delta,
epsilon=epsilon)
solution = model.optimize()
return solution | Compute a single solution based on regulatory on/off minimization (ROOM).
Compute a new flux distribution that minimizes the number of active
reactions needed to accommodate a previous reference solution.
Regulatory on/off minimization (ROOM) is generally used to assess the
impact of knock-outs. Thus t... |
20,914 | def secant(a, b, fn, epsilon):
f1 = fn(a)
if abs(f1) <= epsilon:
return a
f2 = fn(b)
if abs(f2) <= epsilon:
return b
for i in range(100):
slope = (f2 - f1) / (b - a)
c = b - f2 / slope
f3 = fn(c)
if abs(f3) < epsilon:
return c
... | One of the fasest root-finding algorithms.
The method calculates the slope of the function fn and this enables it to converge
to a solution very fast. However, if started too far away from a root, the method
may not converge (returning a None). For this reason, it is recommended that this
function b... |
20,915 | def Lorentzian(x, a, x0, sigma, y0):
return a / (1 + ((x - x0) / sigma) ** 2) + y0 | Lorentzian peak
Inputs:
-------
``x``: independent variable
``a``: scaling factor (extremal value)
``x0``: center
``sigma``: half width at half maximum
``y0``: additive constant
Formula:
--------
``a/(1+((x-x0)/sigma)^2)+y0`` |
20,916 | def reduce_l1(attrs, inputs, proto_obj):
new_attrs = translation_utils._fix_attribute_names(attrs, {:})
new_attrs = translation_utils._add_extra_attributes(new_attrs,
{ : 1})
return , new_attrs, inputs | Reduce input tensor by l1 normalization. |
20,917 | def assemble(self,roboset=None,color=None,format=None,bgset=None,sizex=300,sizey=300):
if roboset == :
if color in self.colors:
roboset = + color
else:
randomcolor = self.colors[self.hasharray[0] % l... | Build our Robot!
Returns the robot image itself. |
20,918 | def resize(self, width, height):
if not self.fbo:
return
self.width = width // self.widget.devicePixelRatio()
self.height = height // self.widget.devicePixelRatio()
self.buffer_width = width
self.buffer_height = height
super().resize(width,... | Pyqt specific resize callback. |
20,919 | def scolor(self):
global palette
color = palette[self.color_index]
if len(palette) - 1 == self.color_index:
self.color_index = 0
else:
self.color_index += 1
self.color(color) | Set a unique color from a serie |
20,920 | def get(self, *raw_args, **raw_kwargs):
args = self.prepare_args(*raw_args)
kwargs = self.prepare_kwargs(**raw_kwargs)
key = self.key(*args, **kwargs)
item = self.cache.get(key)
call = Call(args=raw_args, kwargs=raw_kwargs)
if item i... | Return the data for this function (using the cache if possible).
This method is not intended to be overidden |
20,921 | def _get_template_list(self):
" Get the hierarchy of templates belonging to the object/box_type given. "
t_list = []
if hasattr(self.obj, ) and self.obj.category_id:
cat = self.obj.category
base_path = % (cat.path, self.name)
if hasattr(self.obj, ):
... | Get the hierarchy of templates belonging to the object/box_type given. |
20,922 | def annot_heatmap(ax,dannot,
xoff=0,yoff=0,
kws_text={},
annot_left=,annot_right=,
annothalf=,
):
for xtli,xtl in enumerate(ax.get_xticklabels()):
xtl=xtl.get_text()
for ytli,ytl in enumerate(ax.get_yticklab... | kws_text={'marker','s','linewidth','facecolors','edgecolors'} |
20,923 | def set_forbidden_uptodate(self, uptodate):
if self._forbidden_uptodate == uptodate:
return
self._forbidden_uptodate = uptodate
self.invalidateFilter() | Set all forbidden uptodate values
:param uptodatees: a list with forbidden uptodate values
:uptodate uptodatees: list
:returns: None
:ruptodate: None
:raises: None |
20,924 | def __getRefererUrl(self, url=None):
if url is None:
url = "http://www.arcgis.com/sharing/rest/portals/self"
params = {
"f" : "json",
"token" : self.token
}
val = self._get(url=url, param_dict=params,
proxy_url=self.... | gets the referer url for the token handler |
20,925 | def extract_db_info(self, obj, keys):
objl = self.convert_in(obj)
if isinstance(objl, self.__class__):
return objl.update_meta_info()
try:
with builtins.open(objl, mode=) as fd:
state = json.load(fd)
except IOError as e:
... | Extract metadata from serialized file |
20,926 | def prior_transform(self, unit_coords, priors, prior_args=[]):
theta = []
for i, (u, p) in enumerate(zip(unit_coords, priors)):
func = p.unit_transform
try:
kwargs = prior_args[i]
except(IndexError):
kwargs = {}
theta.append(func(u, **kwargs))
ret... | An example of one way to use the `Prior` objects below to go from unit
cube to parameter space, for nested sampling. This takes and returns a
list instead of an array, to accomodate possible vector parameters. Thus
one will need something like ``theta_array=np.concatenate(*theta)``
:param unit_coords... |
20,927 | def getPixels(self):
array = self.toArray()
(width, height, depth) = array.size
for x in range(width):
for y in range(height):
yield Pixel(array, x, y) | Return a stream of pixels from current Canvas. |
20,928 | def on_error(e):
exname = {: , : }
sys.stderr.write(.format(exname[e.__class__.__name__], str(e)))
sys.stderr.write()
sys.exit(1) | Error handler
RuntimeError or ValueError exceptions raised by commands will be handled
by this function. |
20,929 | def get_config(self):
config = {
: self.location,
: self.language,
: self.topic,
}
return config | function to get current configuration |
20,930 | def _machinectl(cmd,
output_loglevel=,
ignore_retcode=False,
use_vt=False):
prefix =
return __salt__[](.format(prefix, cmd),
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,... | Helper function to run machinectl |
20,931 | def invoke_function(self, script_hash, operation, params, **kwargs):
contract_params = encode_invocation_params(params)
raw_result = self._call(
JSONRPCMethods.INVOKE_FUNCTION.value, [script_hash, operation, contract_params, ],
**kwargs)
return decode_invocation_... | Invokes a contract's function with given parameters and returns the result.
:param script_hash: contract script hash
:param operation: name of the operation to invoke
:param params: list of paramaters to be passed in to the smart contract
:type script_hash: str
:type operation: ... |
20,932 | def _get_ned_sources_needing_metadata(
self):
self.log.debug(
)
tableName = self.dbTableName
sqlQuery = u % locals()
rows = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
... | *Get the names of 50000 or less NED sources that still require metabase in the database*
**Return:**
- ``len(self.theseIds)`` -- the number of NED IDs returned
*Usage:*
.. code-block:: python
numberSources = stream._get_ned_sources_needing_metadata() |
20,933 | def _all_feature_values(
self,
column,
feature,
distinct=True,
contig=None,
strand=None):
return self.db.query_feature_values(
column=column,
feature=feature,
distinct=distinct,
conti... | Cached lookup of all values for a particular feature property from
the database, caches repeated queries in memory and
stores them as a CSV.
Parameters
----------
column : str
Name of property (e.g. exon_id)
feature : str
Type of entry (e.g. exo... |
20,934 | def create_record(self, rtype=None, name=None, content=None, **kwargs):
if not rtype and kwargs.get():
warnings.warn(,
DeprecationWarning)
rtype = kwargs.get()
return self._create_record(rtype, name, content) | Create record. If record already exists with the same content, do nothing. |
20,935 | def get_value(self,
entry_name: Text,
entry_lines: Sequence[Text]) -> Optional[Text]:
for line in entry_lines:
match = self._regex.match(line)
if match:
return match.group(1)
return None | See base class method. |
20,936 | def put(
self, item: _T, timeout: Union[float, datetime.timedelta] = None
) -> "Future[None]":
future = Future()
try:
self.put_nowait(item)
except QueueFull:
self._putters.append((item, future))
_set_timeout(future, timeout)
else... | Put an item into the queue, perhaps waiting until there is room.
Returns a Future, which raises `tornado.util.TimeoutError` after a
timeout.
``timeout`` may be a number denoting a time (on the same
scale as `tornado.ioloop.IOLoop.time`, normally `time.time`), or a
`datetime.tim... |
20,937 | def delete(self, name):
if self.service.splunk_version >= (5,):
Collection.delete(self, name)
else:
raise IllegalOperationException("Deleting indexes via the REST API is "
"not supported before Splunk version 5.") | Deletes a given index.
**Note**: This method is only supported in Splunk 5.0 and later.
:param name: The name of the index to delete.
:type name: ``string`` |
20,938 | def all(self):
identifiers = []
query = text()
for result in self.execute(query):
vid, type_, name = result
res = IdentifierSearchResult(
score=1, vid=vid, type=type_, name=name)
identifiers.append(res)
return identifiers | Returns list with all indexed identifiers. |
20,939 | def sanitize(self):
super(InfoMessage, self).sanitize()
if not isinstance(self.is_reply, bool):
raise ValueError()
if len(bytes(self.nonce)) != 8:
raise ValueError()
... | Check if the current settings conform to the LISP specifications and
fix them where possible. |
20,940 | def en_disable_breakpoint_by_number(self, bpnum, do_enable=True):
"Enable or disable a breakpoint given its breakpoint number."
success, msg, bp = self.get_breakpoint(bpnum)
if not success:
return success, msg
if do_enable:
endis =
else:
endis... | Enable or disable a breakpoint given its breakpoint number. |
20,941 | def proba2labels(proba: [list, np.ndarray], confident_threshold: float, classes: [list, np.ndarray]) -> List[List]:
y = []
for sample in proba:
to_add = np.where(sample > confident_threshold)[0]
if len(to_add) > 0:
y.append(np.array(classes)[to_add].tolist())
else:
... | Convert vectors of probabilities to labels using confident threshold
(if probability to belong with the class is bigger than confident_threshold, sample belongs with the class;
if no probabilities bigger than confident threshold, sample belongs with the class with the biggest probability)
Args:
pro... |
20,942 | def _get_migration_files(self, path):
files = glob.glob(os.path.join(path, "[0-9]*_*.py"))
if not files:
return []
files = list(map(lambda f: os.path.basename(f).replace(".py", ""), files))
files = sorted(files)
return files | Get all of the migration files in a given path.
:type path: str
:rtype: list |
20,943 | def get_status(self):
logger.debug("get server status")
server_status = ctypes.c_int()
cpu_status = ctypes.c_int()
clients_count = ctypes.c_int()
error = self.library.Srv_GetStatus(self.pointer, ctypes.byref(server_status),
ctyp... | Reads the server status, the Virtual CPU status and the number of
the clients connected.
:returns: server status, cpu status, client count |
20,944 | def transferReporter(self, xferId, message):
if self.is_stopped():
return True
_asp_message = AsperaMessage(message)
if not _asp_message.is_msg_type(
[enumAsperaMsgType.INIT,
enumAsperaMsgType.DONE,
enumAsperaMsgType.ERROR,
... | the callback method used by the Aspera sdk during transfer
to notify progress, error or successful completion |
20,945 | def decide_child_program(args_executable, args_child_program):
if os.path.sep in args_child_program:
logger.error(
"The parameter to --exec must be a file name (to be found "
"inside venv%s' not found. If you want to run an executable "
... | Decide which the child program really is (if any). |
20,946 | def set_filter(self, slices, values):
self.filters = [[sl,values[sl]] for sl in slices] | Sets Fourier-space filters for the image. The image is filtered by
subtracting values from the image at slices.
Parameters
----------
slices : List of indices or slice objects.
The q-values in Fourier space to filter.
values : np.ndarray
The complete arra... |
20,947 | def getAsKml(self, session):
statement = .format(self.geometryColumnName,
self.tableName,
self.id)
result = session.execute(statement)
for row in result:
return row.kml | Retrieve the geometry in KML format.
This method is a veneer for an SQL query that calls the ``ST_AsKml()`` function on the geometry column.
Args:
session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database.
Returns:
str... |
20,948 | def padded_sequence_accuracy(predictions,
labels,
weights_fn=common_layers.weights_nonzero):
if common_layers.shape_list(predictions)[-1] == 1:
return rounding_sequence_accuracy(
predictions, labels, weights_fn=weights_fn)
with tf.variable_... | Percentage of times that predictions matches labels everywhere (non-0). |
20,949 | def ge(self, value):
self.op =
self.negate_op =
self.value = self._value(value)
return self | Construct a greater than or equal to (``>=``) filter.
:param value: Filter value
:return: :class:`filters.Field <filters.Field>` object
:rtype: filters.Field |
20,950 | def response_cookies(self):
try:
ret = {}
for cookie_base_uris in self.response.cookies._cookies.values():
for cookies in cookie_base_uris.values():
for cookie in cookies.keys():
ret[cookie] = cookies[cookie].value
... | This will return all cookies set
:return: dict {name, value} |
20,951 | def arg(self, state, index, stack_base=None):
session = self.arg_session
if self.args is None:
arg_loc = [session.next_arg(False) for _ in range(index + 1)][-1]
else:
arg_loc = self.args[index]
return arg_loc.get_value(state, stack_base=stack_base) | Returns a bitvector expression representing the nth argument of a function.
`stack_base` is an optional pointer to the top of the stack at the function start. If it is not
specified, use the current stack pointer.
WARNING: this assumes that none of the arguments are floating-point and they're ... |
20,952 | def pretty_str(label, arr):
def is_col(a):
try:
return a.shape[0] > 1 and a.shape[1] == 1
except (AttributeError, IndexError):
return False
if label is None:
label =
if label:
label +=
if is_col(arr):
return label + str(... | Generates a pretty printed NumPy array with an assignment. Optionally
transposes column vectors so they are drawn on one line. Strictly speaking
arr can be any time convertible by `str(arr)`, but the output may not
be what you want if the type of the variable is not a scalar or an
ndarray.
Examples... |
20,953 | def prettify_json(json_string):
try:
data = json.loads(json_string)
html = + json.dumps(data, sort_keys=True, indent=4) +
except:
html = json_string
return mark_safe(html) | Given a JSON string, it returns it as a
safe formatted HTML |
20,954 | def break_around_binary_operator(logical_line, tokens):
r
def is_binary_operator(token_type, text):
return ((token_type == tokenize.OP or text in [, ]) and
text not in "()[]{},:.;@=%~")
line_break = False
unary_context = True
previous_token_ty... | r"""
Avoid breaks before binary operators.
The preferred place to break around a binary operator is after the
operator, not before it.
W503: (width == 0\n + height == 0)
W503: (width == 0\n and height == 0)
Okay: (width == 0 +\n height == 0)
Okay: foo(\n -x)
Okay: foo(x\n [])
... |
20,955 | def dpi(self):
def int_dpi(dpi):
try:
int_dpi = int(round(float(dpi)))
if int_dpi < 1 or int_dpi > 2048:
int_dpi = 72
except (TypeError, ValueError):
int_dpi = 72
return int_dpi
... | A (horz_dpi, vert_dpi) 2-tuple specifying the dots-per-inch
resolution of this image. A default value of (72, 72) is used if the
dpi is not specified in the image file. |
20,956 | def list_build_configurations_for_product_version(product_id, version_id, page_size=200, page_index=0, sort="", q=""):
data = list_build_configurations_for_project_raw(product_id, version_id, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | List all BuildConfigurations associated with the given ProductVersion |
20,957 | def _add_point_scalar(self, scalars, name, set_active=False, deep=True):
if not isinstance(scalars, np.ndarray):
raise TypeError()
if scalars.shape[0] != self.n_points:
raise Exception( +
)
if scalars.dtype == np.bo... | Adds point scalars to the mesh
Parameters
----------
scalars : numpy.ndarray
Numpy array of scalars. Must match number of points.
name : str
Name of point scalars to add.
set_active : bool, optional
Sets the scalars to the active plotting s... |
20,958 | def _update_dict(data, default_data, replace_data=False):
if not data:
data = default_data.copy()
return data
if not isinstance(data, dict):
raise TypeError()
if len(data) > 255:
raise ValueError()
for i in data.keys():
... | Update algorithm definition type dictionaries |
20,959 | def shot_chart_jointgrid(x, y, data=None, joint_type="scatter", title="",
joint_color="b", cmap=None, xlim=(-250, 250),
ylim=(422.5, -47.5), court_color="gray", court_lw=1,
outer_lines=False, flip_court=False,
joint_kde... | Returns a JointGrid object containing the shot chart.
This function allows for more flexibility in customizing your shot chart
than the ``shot_chart_jointplot`` function.
Parameters
----------
x, y : strings or vector
The x and y coordinates of the shots taken. They can be passed in as
... |
20,960 | def set_scene_config(self, scene_id, config):
if not scene_id in self.state.scenes:
err_msg = "Requested to reconfigure scene {sceneNum}, which does not exist".format(sceneNum=scene_id)
logging.info(err_msg)
return(False, 0, err_msg)
if scene_id == self.stat... | reconfigure a scene by scene ID |
20,961 | def events(self):
if self._events is None:
self._events = EventList(self._version, workspace_sid=self._solution[], )
return self._events | Access the events
:returns: twilio.rest.taskrouter.v1.workspace.event.EventList
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventList |
20,962 | def LineWrap(text, omit_sgr=False):
def _SplitWithSgr(text_line):
token_list = sgr_re.split(text_line)
text_line_list = []
line_length = 0
for (index, token) in enumerate(token_list):
if token is :
continue
if sgr_re.match(token):
text_line_list.ap... | Break line to fit screen width, factoring in ANSI/SGR escape sequences.
Args:
text: String to line wrap.
omit_sgr: Bool, to omit counting ANSI/SGR sequences in the length.
Returns:
Text with additional line wraps inserted for lines grater than the width. |
20,963 | def add_entry(self, src, dst, duration=3600, src_port1=None,
src_port2=None, src_proto=,
dst_port1=None, dst_port2=None,
dst_proto=):
self.entries.setdefault(, []).append(prepare_blacklist(
src, dst, duration, src_port1, src_port2, src_p... | Create a blacklist entry.
A blacklist can be added directly from the engine node, or from
the system context. If submitting from the system context, it becomes
a global blacklist. This will return the properly formatted json
to submit.
:param src: source address... |
20,964 | def repr_def_class(self, class_data):
classname = self.formatted_classname(class_data["classname"])
if classname not in self.classes:
self.lines.append("")
self.lines.append("class %s(%s):" % (classname, self.basename))
kwargs = list()
... | Create code like this::
class Person(Base):
def __init__(self, person_id=None, name=None):
self.person_id = person_id
self.name = name |
20,965 | def addPolylineAnnot(self, points):
CheckParent(self)
val = _fitz.Page_addPolylineAnnot(self, points)
if not val: return
val.thisown = True
val.parent = weakref.proxy(self)
self._annot_refs[id(val)] = val
return val | Add a 'Polyline' annotation for a sequence of points. |
20,966 | def visit_Call(self, node):
s an Intrinsic)
or if Pythran already computed itdemobdef foo(a, d): __builtin__.dict.setdefault(d, 0, a)<unbound-value>aABCD
self.generic_visit(node)
f = node.func
if isinstance(f, ast.Attribute) and f.attr == "partial":
return se... | Resulting node alias to the return_alias of called function,
if the function is already known by Pythran (i.e. it's an Intrinsic)
or if Pythran already computed it's ``return_alias`` behavior.
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> fun =... |
20,967 | def plot_mv_grid_topology(self, technologies=False, **kwargs):
if self.network.pypsa is None:
try:
timesteps = self.network.timeseries.timeindex
self.network.pypsa = pypsa_io.to_pypsa(
self.network, mode=None, timesteps=timesteps)
... | Plots plain MV grid topology and optionally nodes by technology type
(e.g. station or generator).
Parameters
----------
technologies : :obj:`Boolean`
If True plots stations, generators, etc. in the grid in different
colors. If False does not plot any nodes. Defau... |
20,968 | def merge_las(*las_files):
if len(las_files) == 1:
las_files = las_files[0]
if not las_files:
raise ValueError("No files to merge")
if not utils.files_have_same_dtype(las_files):
raise ValueError("All files must have the same point format")
header = las_files[0].header
... | Merges multiple las files into one
merged = merge_las(las_1, las_2)
merged = merge_las([las_1, las_2, las_3])
Parameters
----------
las_files: Iterable of LasData or LasData
Returns
-------
pylas.lasdatas.base.LasBase
The result of the merging |
20,969 | def edit_profile():
if g.user is None:
abort(401)
form = dict(name=g.user.name, email=g.user.email)
if request.method == :
if in request.form:
User.get_collection().remove(g.user)
session[] = None
flash(u)
return redirect(url_for())
... | Updates a profile |
20,970 | def modify_replication_instance(ReplicationInstanceArn=None, AllocatedStorage=None, ApplyImmediately=None, ReplicationInstanceClass=None, VpcSecurityGroupIds=None, PreferredMaintenanceWindow=None, MultiAZ=None, EngineVersion=None, AllowMajorVersionUpgrade=None, AutoMinorVersionUpgrade=None, ReplicationInstanceIdentifie... | Modifies the replication instance to apply new settings. You can change one or more parameters by specifying these parameters and the new values in the request.
Some settings are applied during the maintenance window.
See also: AWS API Documentation
:example: response = client.modify_replication_i... |
20,971 | def newton_iterate(evaluate_fn, s, t):
r
norm_update_prev = None
norm_update = None
linear_updates = 0
current_s = s
current_t = t
for index in six.moves.xrange(MAX_NEWTON_ITERATIONS):
jacobian, func_val = evaluate_fn(current_s, current_t)
if j... | r"""Perform a Newton iteration.
In this function, we assume that :math:`s` and :math:`t` are nonzero,
this makes convergence easier to detect since "relative error" at
``0.0`` is not a useful measure.
There are several tolerance / threshold quantities used below:
* :math:`10` (:attr:`MAX_NEWTON_I... |
20,972 | def node_from_xml(xmlfile, nodefactory=Node):
root = parse(xmlfile).getroot()
return node_from_elem(root, nodefactory) | Convert a .xml file into a Node object.
:param xmlfile: a file name or file object open for reading |
20,973 | def build(args):
if len(args) != 1:
log.error()
app.quit(1)
target = address.new(args[0])
log.info(, target)
try:
bb = Butcher()
bb.clean()
bb.load_graph(target)
bb.build(target)
except (gitrepo.GitError,
error.BrokenGraph,
... | Build a target and its dependencies. |
20,974 | def on_draw(self, e):
gloo.clear()
for visual in self.visuals:
logger.log(5, "Draw visual `%s`.", visual)
visual.on_draw() | Draw all visuals. |
20,975 | def multi(method):
@functools.wraps(method)
def multi(self, address=):
values = flask.request.values
address = urllib.parse.unquote_plus(address)
if address and values and not address.endswith():
address +=
result = {}
for a in values or :
t... | Decorator for RestServer methods that take multiple addresses |
20,976 | def _parse_application_info(self, info_container):
m = applications_regex.search(info_container.text)
if m:
self.open_applications = m.group(1) == "opened" | Parses the guild's application info.
Parameters
----------
info_container: :class:`bs4.Tag`
The parsed content of the information container. |
20,977 | def graph_from_dot_file(path):
fd = open(path, )
data = fd.read()
fd.close()
return graph_from_dot_data(data) | Load graph as defined by a DOT file.
The file is assumed to be in DOT format. It will
be loaded, parsed and a Dot class will be returned,
representing the graph. |
20,978 | def days_at_time(days, t, tz, day_offset=0):
days = pd.DatetimeIndex(days).tz_localize(None)
if len(days) == 0:
return days.tz_localize(UTC)
delta = pd.Timedelta(
days=day_offset,
hours=t.hour,
minutes=t.minute,
seconds=t.second,
)
return (days + de... | Create an index of days at time ``t``, interpreted in timezone ``tz``.
The returned index is localized to UTC.
Parameters
----------
days : DatetimeIndex
An index of dates (represented as midnight).
t : datetime.time
The time to apply as an offset to each day in ``days``.
tz : ... |
20,979 | def listMembers(self, id, headers=None, query_params=None, content_type="application/json"):
uri = self.client.base_url + "/network/"+id+"/member"
return self.client.get(uri, None, headers, query_params, content_type) | Get a list of network members
It is method for GET /network/{id}/member |
20,980 | def _build_table(self) -> Dict[State, Tuple[Multiplex, ...]]:
result: Dict[State, Tuple[Multiplex, ...]] = {}
for state in self.influence_graph.all_states():
result[state] = tuple(multiplex for multiplex in self.influence_graph.multiplexes
if multi... | Private method which build the table which map a State to the active multiplex. |
20,981 | def pad_batch_dimension_for_multiple_chains(
observed_time_series, model, chain_batch_shape):
[
observed_time_series,
is_missing
] = canonicalize_observed_time_series_with_mask(observed_time_series)
event_ndims = 2
model_batch_ndims = (
model.batc... | Expand the observed time series with extra batch dimension(s). |
20,982 | def update_video(video_data):
try:
video = _get_video(video_data.get("edx_video_id"))
except Video.DoesNotExist:
error_message = u"Video not found when trying to update video with edx_video_id: {0}".format(video_data.get("edx_video_id"))
raise ValVideoNotFoundError(error_message)
... | Called on to update Video objects in the database
update_video is used to update Video objects by the given edx_video_id in the video_data.
Args:
video_data (dict):
{
url: api url to the video
edx_video_id: ID of the video
duration: Length of vi... |
20,983 | def build_save_containers(platforms, registry, load_cache) -> int:
from joblib import Parallel, delayed
if len(platforms) == 0:
return 0
platform_results = Parallel(n_jobs=PARALLEL_BUILDS, backend="multiprocessing")(
delayed(_build_save_container)(platform, registry, load_cache)
... | Entry point to build and upload all built dockerimages in parallel
:param platforms: List of platforms
:param registry: Docker registry name
:param load_cache: Load cache before building
:return: 1 if error occurred, 0 otherwise |
20,984 | def cancelPnL(self, account, modelCode: str = ):
key = (account, modelCode)
reqId = self.wrapper.pnlKey2ReqId.pop(key, None)
if reqId:
self.client.cancelPnL(reqId)
self.wrapper.pnls.pop(reqId, None)
else:
self._logger.error(
... | Cancel PnL subscription.
Args:
account: Cancel for this account.
modelCode: If specified, cancel for this account model. |
20,985 | def complete_object_value(
self,
return_type: GraphQLObjectType,
field_nodes: List[FieldNode],
info: GraphQLResolveInfo,
path: ResponsePath,
result: Any,
) -> AwaitableOrValue[Dict[str, Any]]:
if return_type.is_type_of:
... | Complete an Object value by executing all sub-selections. |
20,986 | def _get_html_contents(html):
parser = MyHTMLParser()
parser.feed(html)
if parser.is_code:
return (, parser.data.strip())
elif parser.is_math:
return (, parser.data.strip())
else:
return , | Process a HTML block and detects whether it is a code block,
a math block, or a regular HTML block. |
20,987 | def remove_file(self, filepath):
self._models.pop(filepath)
self._updates.pop(filepath, default=None)
self.signalModelDestroyed.emit(filepath) | Removes the DataFrameModel from being registered.
:param filepath: (str)
The filepath to delete from the DataFrameModelManager.
:return: None |
20,988 | def to_bool(value):
bool_value = False
if str(value).lower() in [, ]:
bool_value = True
return bool_value | Convert string value to bool. |
20,989 | def _from_string(cls, serialized):
parse = cls.URL_RE.match(serialized)
if not parse:
raise InvalidKeyError(cls, serialized)
parse = parse.groupdict()
if parse[]:
parse[] = cls.as_object_id(parse[])
return cls(**{key: parse.get(key) for key in c... | Return a DefinitionLocator parsing the given serialized string
:param serialized: matches the string to |
20,990 | def get_releasenotes(project_dir=os.curdir, bugtracker_url=):
releasenotes =
pkg_info_file = os.path.join(project_dir, )
releasenotes_file = os.path.join(project_dir, )
if os.path.exists(pkg_info_file) and os.path.exists(releasenotes_file):
with open(releasenotes_file) as releasenotes_fd:
... | Retrieves the release notes, from the RELEASE_NOTES file (if in a package)
or generates it from the git history.
Args:
project_dir(str): Path to the git repo of the project.
bugtracker_url(str): Url to the bug tracker for the issues.
Returns:
str: release notes
Raises:
... |
20,991 | def mset_list(item, index, value):
if isinstance(index, (int, slice)):
item[index] = value
else:
map(item.__setitem__, index, value) | set mulitple items via index of int, slice or list |
20,992 | def addNoise(vecs, percent=0.1, n=2048):
noisyVecs = []
for vec in vecs:
nv = vec.copy()
for idx in vec:
if numpy.random.random() <= percent:
nv.discard(idx)
nv.add(numpy.random.randint(n))
noisyVecs.append(nv)
return noisyVecs | Add noise to the given sequence of vectors and return the modified sequence.
A percentage of the on bits are shuffled to other locations. |
20,993 | def list_quota_volume(name):
*
cmd = .format(name)
cmd +=
root = _gluster_xml(cmd)
if not _gluster_ok(root):
return None
ret = {}
for limit in _iter(root, ):
path = limit.find().text
ret[path] = _etree_to_dict(limit)
return ret | List quotas of glusterfs volume
name
Name of the gluster volume
CLI Example:
.. code-block:: bash
salt '*' glusterfs.list_quota_volume <volume> |
20,994 | def _map_content_types(archetype_tool, catalogs_definition):
ct_map = {}
to_reindex = []
map_types = archetype_tool.catalog_map
for catalog_id in catalogs_definition.keys():
catalog_info = catalogs_definition.get(catalog_id, {})
types = catalog_info.get(, [])... | Updates the mapping for content_types against catalogs
:archetype_tool: an archetype_tool object
:catalogs_definition: a dictionary like
{
CATALOG_ID: {
'types': ['ContentType', ...],
'indexes': {
'UID': 'FieldIndex',
... |
20,995 | def is_device_connected(self, ip):
all_devices = self.get_all_connected_devices()
for device in all_devices:
if ip == device[]:
return device[] == 1
return False | Check if a device identified by it IP is connected to the box
:param ip: IP of the device you want to test
:type ip: str
:return: True is the device is connected, False if it's not
:rtype: bool |
20,996 | def configure_room(self, form):
if form.type == "cancel":
return None
elif form.type != "submit":
raise ValueError("A form required to configure a room")
iq = Iq(to_jid = self.room_jid.bare(), stanza_type = "set")
query = iq.new_query(MUC_OWNER_NS, "que... | Configure the room using the provided data.
Do nothing if the provided form is of type 'cancel'.
:Parameters:
- `form`: the configuration parameters. Should be a 'submit' form made by filling-in
the configuration form retireved using `self.request_configuration_form` or
... |
20,997 | def insertOutputConfig(self, businput):
if not ("app_name" in businput and "release_version" in businput\
and "pset_hash" in businput and "output_module_label" in businput
and "global_tag" in businput):
dbsExceptionHandler(, "business/DBSOutputConfig/insertOutputCon... | Method to insert the Output Config.
app_name, release_version, pset_hash, global_tag and output_module_label are
required.
args:
businput(dic): input dictionary.
Updated Oct 12, 2011 |
20,998 | def import_csv(file_name, **kwargs):
sep = kwargs.get(, ",")
content = exch.read_file(file_name, skip_lines=1)
return exch.import_text_data(content, sep) | Reads control points from a CSV file and generates a 1-dimensional list of control points.
It is possible to use a different value separator via ``separator`` keyword argument. The following code segment
illustrates the usage of ``separator`` keyword argument.
.. code-block:: python
:linenos:
... |
20,999 | def points_from_x0y0x1y1(xyxy):
x0 = xyxy[0]
y0 = xyxy[1]
x1 = xyxy[2]
y1 = xyxy[3]
return "%s,%s %s,%s %s,%s %s,%s" % (
x0, y0,
x1, y0,
x1, y1,
x0, y1
) | Constructs a polygon representation from a rectangle described as a list [x0, y0, x1, y1] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.