Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
361,800 | def value(self) -> float:
return map_single_axis(self.min, self.max, self.dead_zone, self.hot_zone, self.__value) | Get a centre-compensated, scaled, value for the axis, taking any dead-zone into account. The value will
scale from 0.0 at the edge of the dead-zone to 1.0 (positive) at the extreme position of
the trigger or the edge of the hot zone, if defined as other than 1.0.
:return:
a float va... |
361,801 | def random_line(file_path: str, encoding: str = FORCED_ENCODING) -> str:
line_num = 0
selected_line = ""
with open(file_path, encoding=encoding) as stream:
while True:
line = stream.readline()
if not line:
break
line_num += 1
... | Get random line from a file. |
361,802 | def call_path(self, basepath):
rel_filepath = self.path
if basepath:
rel_filepath = os.path.relpath(self.path, basepath)
basename = self.name
if basename in set([, ]):
rel_filepath = os.path.dirname(rel_filepath)
return rel_filepath | return that path to be able to call this script from the passed in
basename
example --
basepath = /foo/bar
self.path = /foo/bar/che/baz.py
self.call_path(basepath) # che/baz.py
basepath -- string -- the directory you would be calling this script in
... |
361,803 | def __get_cfg_pkgs_rpm(self):
out, err = self._syscall(, None, None, , ,
, )
data = dict()
pkg_name = None
pkg_configs = []
out = salt.utils.stringutils.to_str(out)
for line in out.split(os.linesep):
line = line.strip... | Get packages with configuration files on RPM systems. |
361,804 | async def _process_polling_updates(self, updates, fast: typing.Optional[bool] = True):
need_to_call = []
for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
for response in responses:
if not isinstance(response, BaseResponse):
... | Process updates received from long-polling.
:param updates: list of updates.
:param fast: |
361,805 | def _resolve(value, model_instance=None, context=None):
if isinstance(value, basestring) and "{" in value:
if context is None:
context = Context()
if model_instance is not None:
context[model_instance._meta.module_name] = model_instance
value = Template(value).r... | Resolves any template references in the given value. |
361,806 | def next_task(self):
node = self._find_next_ready_node()
if node is None:
return None
executor = node.get_executor()
if executor is None:
return None
tlist = executor.get_all_targets()
task = self.tasker(self, tlist, node in self.origi... | Returns the next task to be executed.
This simply asks for the next Node to be evaluated, and then wraps
it in the specific Task subclass with which we were initialized. |
361,807 | def help_center_article_delete(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/articles
api_path = "/api/v2/help_center/articles/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, method="DELETE", **kwargs) | https://developer.zendesk.com/rest_api/docs/help_center/articles#archive-article |
361,808 | def get(
self, job_id, job_get_options=None, custom_headers=None, raw=False, **operation_config):
select = None
if job_get_options is not None:
select = job_get_options.select
expand = None
if job_get_options is not None:
expand = job_get_opti... | Gets information about the specified job.
:param job_id: The ID of the job.
:type job_id: str
:param job_get_options: Additional parameters for the operation
:type job_get_options: ~azure.batch.models.JobGetOptions
:param dict custom_headers: headers that will be added to the re... |
361,809 | def add_item(self,jid,node=None,name=None,action=None):
return DiscoItem(self,jid,node,name,action) | Add a new item to the `DiscoItems` object.
:Parameters:
- `jid`: item JID.
- `node`: item node name.
- `name`: item name.
- `action`: action for a "disco push".
:Types:
- `jid`: `pyxmpp.JID`
- `node`: `unicode`
- `name`... |
361,810 | def get_tokens(self):
try:
while True:
token = self.lexer.token()
if not token:
break
yield token
except QasmError as e:
print(, e.msg) | Returns a generator of the tokens. |
361,811 | def classify(self, dataset, verbose=True, batch_size=64):
prob_vector = self.predict(dataset, output_type=,
verbose=verbose, batch_size=batch_size)
id_to_label = self._id_to_class_label
return _tc.SFrame({
: prob_vector.apply(lambda v: id_... | Return the classification for each examples in the ``dataset``.
The output SFrame contains predicted class labels and its probability.
Parameters
----------
dataset : SFrame | SArray | dict
The audio data to be classified.
If dataset is an SFrame, it must have a ... |
361,812 | def _cast(self, value):
if value.isdigit():
value = int(value)
elif re.compile("^\d+\.\d+").match(value):
value = float(value)
return value | Try to cast value to int or float if possible
:param value: value to cast
:return: casted value |
361,813 | def _init_metadata(self):
super(TextAnswerFormRecord, self)._init_metadata()
self._min_string_length_metadata = {
: Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
),
: ,
:... | stub |
361,814 | def create(self, recording_status_callback_event=values.unset,
recording_status_callback=values.unset,
recording_status_callback_method=values.unset, trim=values.unset,
recording_channels=values.unset):
data = values.of({
: serialize.map(recordin... | Create a new RecordingInstance
:param unicode recording_status_callback_event: The recording status changes that should generate a callback
:param unicode recording_status_callback: The callback URL on each selected recording event
:param unicode recording_status_callback_method: The HTTP metho... |
361,815 | def onLeftUp(self, event=None):
if event is None:
return
self.cursor_mode_action(, event=event)
self.canvas.draw_idle()
self.canvas.draw()
self.ForwardEvent(event=event.guiEvent) | left button up |
361,816 | def cli():
args = docopt.docopt(__doc__, version=__VERSION__)
secure = args[]
numberofwords = int(args[])
dictpath = args[]
if dictpath is not None:
dictfile = open(dictpath)
else:
dictfile = load_stream()
with dictfile:
wordlist = read_wordlist(dictfile)
w... | Run the command line interface. |
361,817 | def process_script(self, filename):
try:
with managed_process(subprocess.Popen(shlex.split("bash %s" % filename),
stdout=self.stdout, stderr=self.stderr,
shell=self.shell, env=self.env)) as p... | Running the Bash code. |
361,818 | def get_active_entry(user, select_for_update=False):
entries = apps.get_model(, ).no_join
if select_for_update:
entries = entries.select_for_update()
entries = entries.filter(user=user, end_time__isnull=True)
if not entries.exists():
return None
if entries.count() > 1:
... | Returns the user's currently-active entry, or None. |
361,819 | def copy_non_reserved(props, target):
target.update(
{
key: value
for key, value in props.items()
if not is_reserved_property(key)
}
)
return target | Copies all properties with non-reserved names from ``props`` to ``target``
:param props: A dictionary of properties
:param target: Another dictionary
:return: The target dictionary |
361,820 | def getShocks(self):
PermShkNow = np.zeros(self.AgentCount)
TranShkNow = np.zeros(self.AgentCount)
newborn = self.t_age == 0
for t in range(self.T_cycle):
these = t == self.t_cycle
N = np.sum(these)
if N > 0:
IncomeDstnNow ... | Gets permanent and transitory income shocks for this period. Samples from IncomeDstn for
each period in the cycle. This is a copy-paste from IndShockConsumerType, with the
addition of the Markov macroeconomic state. Unfortunately, the getShocks method for
MarkovConsumerType cannot be used, as... |
361,821 | def setup_logging(default_path=None, default_level=logging.INFO,
env_key=None):
path = default_path or os.path.join(
os.path.dirname(__file__), )
value = os.getenv(env_key, None) if env_key is not None else None
home = _get_home()
if value:
path = value
if os.p... | Setup logging configuration
Parameters
----------
default_path: str
Default path of the yaml logging configuration file. If None, it
defaults to the 'logging.yaml' file in the config directory
default_level: int
Default: :data:`logging.INFO`. Default level if default_path does n... |
361,822 | def evaluate_call_args(self, calculator):
args = []
kwargs = OrderedDict()
for var_node, value_node in self.argpairs:
value = value_node.evaluate(calculator, divide=True)
if var_node is None:
args.append(value)
else:... | Interpreting this literal as a function call, return a 2-tuple of
``(args, kwargs)``. |
361,823 | def _open_response(self, objects, namespace, pull_type, **params):
max_obj_cnt = params[]
if max_obj_cnt is None:
max_obj_cnt = _DEFAULT_MAX_OBJECT_COUNT
default_server_timeout = 40
timeout = default_server_timeout if params[] is None \
else params[]
... | Build an open... response once the objects have been extracted from
the repository. |
361,824 | def p_types(self, p):
if len(p) == 2:
p[0] = tuple((t,) for t in p[1])
else:
p[0] = tuple((t,) + ts for t in p[1] for ts in p[3]) | types : type
| type COMMA types |
361,825 | def humanize_dates(p_due=None, p_start=None, p_creation=None):
dates_list = []
if p_creation:
dates_list.append(humanize_date(p_creation))
if p_due:
dates_list.append( + humanize_date(p_due))
if p_start:
now = arrow.now().date()
dates_list.append(.format(
... | Returns string with humanized versions of p_due, p_start and p_creation.
Examples:
- all dates: "16 days ago, due in a month, started 2 days ago"
- p_due and p_start: "due in a month, started 2 days ago"
- p_creation and p_due: "16 days ago, due in a month" |
361,826 | def save(self, fp, mode=):
if hasattr(fp, ):
self._record.write(fp)
else:
with open(fp, mode) as f:
self._record.write(f) | Save the PSD file.
:param fp: filename or file-like object.
:param mode: file open mode, default 'wb'. |
361,827 | def depclean(name=None, slot=None, fromrepo=None, pkgs=None):
*
try:
pkg_params = __salt__[](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
if name and not pkgs and (slot is not None or fromrepo is not None)and len(pkg_params) == 1:
... | Portage has a function to remove unused dependencies. If a package
is provided, it will only removed the package if no other package
depends on it.
name
The name of the package to be cleaned.
slot
Restrict the remove to a specific slot. Ignored if ``name`` is None.
fromrepo
... |
361,828 | def tokenize(self):
if not self.quiet:
print
print "Finding compound words..."
compound_word_dict = {}
for compound_length in range(5,1,-1):
compound_word_dict[compound_length] = [name for name in self.names if len(name.split()) == compound_... | Tokenizes all multiword names in the list of Units.
Modifies:
- (indirectly) self.unit_list, by combining words into compound words.
This is done because many names may be composed of multiple words, e.g.,
'grizzly bear'. In order to count the number of permissible words
ge... |
361,829 | def labelHealpix(pixels, values, nside, threshold=0, xsize=1000):
proj = healpy.projector.MollweideProj(xsize=xsize)
vec = healpy.pix2vec(nside,pixels)
xy = proj.vec2xy(vec)
ij = proj.xy2ij(xy)
xx,yy = proj.ij2xy()
searchims = []
if values.... | Label contiguous regions of a (sparse) HEALPix map. Works by mapping
HEALPix array to a Mollweide projection and applying scipy.ndimage.label
Assumes non-nested HEALPix map.
Parameters:
pixels : Pixel values associated to (sparse) HEALPix array
values : (Spa... |
361,830 | def generate(self, chars, format=):
im = self.generate_image(chars)
out = BytesIO()
im.save(out, format=format)
out.seek(0)
return out | Generate an Image Captcha of the given characters.
:param chars: text to be generated.
:param format: image file format |
361,831 | def ftp_download(ftp, ftp_path, local_path):
with open(local_path, ) as _f:
ftp.retrbinary( % ftp_path, _f.write) | Download the master database
:param ftp: ftp connection
:param ftp_path: path to file on the ftp server
:param local_path: local path to download file
:return: |
361,832 | def get_repos(self, type=github.GithubObject.NotSet):
assert type is github.GithubObject.NotSet or isinstance(type, (str, unicode)), type
url_parameters = dict()
if type is not github.GithubObject.NotSet:
url_parameters["type"] = type
return github.PaginatedList.Pagi... | :calls: `GET /orgs/:org/repos <http://developer.github.com/v3/repos>`_
:param type: string ('all', 'public', 'private', 'forks', 'sources', 'member')
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository` |
361,833 | def resize_imgs(fnames, targ, path, new_path, resume=True, fn=None):
target_path = path_for(path, new_path, targ)
if resume:
subdirs = {os.path.dirname(p) for p in fnames}
subdirs = {s for s in subdirs if os.path.exists(os.path.join(target_path, s))}
already_resized_fnames = set()
... | Enlarge or shrink a set of images in the same directory to scale, such that the smaller of the height or width dimension is equal to targ.
Note:
-- This function is multithreaded for efficiency.
-- When destination file or folder already exist, function exists without raising an error. |
361,834 | def run(self):
try:
from _winapi import WAIT_OBJECT_0, INFINITE
except ImportError:
from _subprocess import WAIT_OBJECT_0, INFINITE
handles = []
if self.interrupt_handle:
handles.append(self.interrupt_handle)
if self.parent_h... | Run the poll loop. This method never returns. |
361,835 | def compute_ema(smoothing_factor, points):
ema = []
if(len(points) > 0):
ema.append(points[0])
for i in range(1, len(points)):
ema.append(smoothing_factor * points[i] + (1 - smoothing_factor) * ema[i - 1])
return ema | Compute exponential moving average of a list of points.
:param float smoothing_factor: the smoothing factor.
:param list points: the data points.
:return list: all ema in a list. |
361,836 | def regional_atlas(graph, label_image, xxx_todo_changeme1):
r
(probability_map, alpha) = xxx_todo_changeme1
label_image = scipy.asarray(label_image)
probability_map = scipy.asarray(probability_map)
__check_label_image(label_image)
objects = scipy.ndimage.find_objects(label_image)
... | r"""
Regional term based on a probability atlas.
An implementation of a regional term, suitable to be used with the
`~medpy.graphcut.generate.graph_from_labels` function.
This regional term introduces statistical probability of a voxel to belong to the
object to segment. It computes the su... |
361,837 | def factorise_strings (string_list, boundary_char=None):
cmn = find_common_beginning(string_list, boundary_char)
new_list = [el[len(cmn):] for el in string_list]
return (new_list, cmn) | Given a list of strings, finds the longest string that is common
to the *beginning* of all strings in the list and
returns a new list whose elements lack this common beginning.
boundary_char defines a boundary that must be preserved, so that the
common string removed must end with this char.
... |
361,838 | def endpoint_from_flag(flag):
relation_name = None
value = _get_flag_value(flag)
if isinstance(value, dict) and in value:
relation_name = value[]
elif flag.startswith():
relation_name = flag.split()[1]
elif in flag:
relation_name = flag.split... | The object used for interacting with relations tied to a flag, or None. |
361,839 | def main():
coloredlogs.install(syslog=True)
rotation_scheme = {}
kw = dict(include_list=[], exclude_list=[])
parallel = False
use_sudo = False
selected_locations = []
try:
options, arguments = getopt.getopt(sys.argv[1:], , [
, , , , , ,
, ... | Command line interface for the ``rotate-backups`` program. |
361,840 | def idle(self, stop_signals: tuple = (SIGINT, SIGTERM, SIGABRT)):
def signal_handler(*args):
self.is_idle = False
for s in stop_signals:
signal(s, signal_handler)
self.is_idle = True
while self.is_idle:
time.sleep(1)
self.stop() | Blocks the program execution until one of the signals are received,
then gently stop the Client by closing the underlying connection.
Args:
stop_signals (``tuple``, *optional*):
Iterable containing signals the signal handler will listen to.
Defaults to (SIGIN... |
361,841 | def add_default(self, ext, content_type):
return self._add_default(extension=ext, contentType=content_type) | Add a child ``<Default>`` element with attributes set to parameter
values. |
361,842 | def scale(self, scale, center=None):
scale = transforms.scale(as_vec4(scale, default=(1, 1, 1, 1))[0, :3])
if center is not None:
center = as_vec4(center)[0, :3]
scale = np.dot(np.dot(transforms.translate(-center), scale),
transforms.translate(... | Scale the matrix about a given origin.
The scaling is applied *after* the transformations already present
in the matrix.
Parameters
----------
scale : array-like
Scale factors along x, y and z axes.
center : array-like or None
The x, y and z coor... |
361,843 | def msg(self, msg):
hookenv.log(.format(self._name(), msg),
level=hookenv.INFO) | Emit a message. Override to customize log spam. |
361,844 | def listify(x, none_value=[]):
if isinstance(x, list):
return x
elif isinstance(x, tuple):
return list(x)
elif x is None:
return none_value
else:
return [x] | Make a list of the argument if it is not a list. |
361,845 | def wrap_queries_in_bool_clauses_if_more_than_one(queries,
use_must_clause,
preserve_bool_semantics_if_one_clause=False):
if not queries:
return {}
if len(queries) == 1 and not preserve_bool_semanti... | Helper for wrapping a list of queries into a bool.{must, should} clause.
Args:
queries (list): List of queries to be wrapped in a bool.{must, should} clause.
use_must_clause (bool): Flag that signifies whether to use 'must' or 'should' clause.
preserve_bool_semantics_if_one_clause (bool): F... |
361,846 | def filter_correlation(self, x_analyte, y_analyte, window=None,
r_threshold=0.9, p_threshold=0.05, filt=True,
samples=None, subset=None):
if samples is not None:
subset = self.make_subset(samples)
samples = self._get_samples(sub... | Applies a correlation filter to the data.
Calculates a rolling correlation between every `window` points of
two analytes, and excludes data where their Pearson's R value is
above `r_threshold` and statistically significant.
Data will be excluded where their absolute R value is greater ... |
361,847 | def _download_tlds_list(self):
url_list =
if self._default_cache_file and \
not os.access(self._tld_list_path, os.W_OK):
self._logger.info("Default cache file is not writable.")
self._tld_list_path = self._get_cache_file_path()
... | Function downloads list of TLDs from IANA.
LINK: https://data.iana.org/TLD/tlds-alpha-by-domain.txt
:return: True if list was downloaded, False in case of an error
:rtype: bool |
361,848 | def set_rich_text_font(self, font):
self.rich_text.set_font(font, fixed_font=self.get_plugin_font()) | Set rich text mode font |
361,849 | def colorize_invoke_command(self, string):
final_string = string
try:
try:
for token in [, , , ]:
if token in final_string:
format_string =
pattern = r
... | Apply various heuristics to return a colorized version the invoke
command string. If these fail, simply return the string in plaintext.
Inspired by colorize_log_entry(). |
361,850 | def add_position_pattern(self, m):
if self.version == 1:
return
coordinates = tables.position_adjustment[self.version]
min_coord = coordinates[0]
max_coord = coordinates[-1]
for i in coordinates:
for j in coo... | This method draws the position adjustment patterns onto the QR
Code. All QR code versions larger than one require these special boxes
called position adjustment patterns. |
361,851 | def update(self, file_path, new_data={}, **kwargs):
data = new_data.copy()
file_path = file_path.replace(, )
data[] = file_path
path = % (self.path, file_path)
self._check_missing_update_attrs(data)
return self.gitlab.http_put(path, post_data=data, **kwargs) | Update an object on the server.
Args:
id: ID of the object to update (can be None if not required)
new_data: the update data for the object
**kwargs: Extra options to send to the server (e.g. sudo)
Returns:
dict: The new object data (*not* a RESTObject)
... |
361,852 | def type(self) -> DataType:
if self._accept(Tokens.PRIMITIVE):
assert self.tok is not None
return self.tok.value
elif self._accept(Tokens.TIMESTAMP):
if self._accept(Tokens.LPAREN):
self._expect(Tokens.STRARG)
assert self.tok ... | type : primitive
| decimal
| array
| set
| map
| struct
primitive : "any"
| "null"
| "bool"
| "boolean"
| "int8"
| "int16"
| "int32"
... |
361,853 | def coords(self):
x, y = ("lat", "lng") if self.order == "lat" else ("lng", "lat")
try:
return (self["location"][x], self["location"][y])
except KeyError:
return None | Returns a tuple representing the location of the address in a
GIS coords format, i.e. (longitude, latitude). |
361,854 | def get_volumes(self):
volumes = []
for v in self.volumes:
volumes.extend(v.get_volumes())
return volumes | Gets a list of all volumes in this disk, including volumes that are contained in other volumes. |
361,855 | def _to_dict(self):
_dict = {}
if hasattr(self, ) and self.collections is not None:
_dict[] = [x._to_dict() for x in self.collections]
return _dict | Return a json dictionary representing this model. |
361,856 | def is_prefix(cls, result):
from boto.s3.prefix import Prefix
return isinstance(result, Prefix) or cls._is_gs_folder(result) | Return ``True`` if result is a prefix object.
.. note::
Boto uses the S3 Prefix object for GS prefixes. |
361,857 | def send_request(self, url):
while True:
try:
return urllib.request.urlopen(url)
except urllib.error.HTTPError as e:
raise serror(
"Request `%s` failed (%s:%s)." %
(url, e.__class__.__name__, e.code))
... | Send a request to given url. |
361,858 | def filter(self, **kwargs):
keys = self.filter_keys(**kwargs)
return self.keys_to_values(keys) | Filter data according to the given arguments. |
361,859 | def el_to_path_vector(el):
path = []
while el.parent:
path.append(el)
el = el.parent
return list(reversed(path + [el])) | Convert `el` to vector of foregoing elements.
Attr:
el (obj): Double-linked HTMLElement instance.
Returns:
list: HTMLElements which considered as path from root to `el`. |
361,860 | def repl_proc(self, inputstring, log=True, **kwargs):
return self.apply_procs(self.replprocs, kwargs, inputstring, log=log) | Process using replprocs. |
361,861 | def toxml(self):
argstr =
if self.component:
argstr += .format(self.component)
if self.component_type:
argstr += .format(self.component_type)
if self.number:
argstr += .format(self.number)
if self.assignments:
chxmlstr =
... | Exports this object into a LEMS XML object |
361,862 | def main():
parser = optparse.OptionParser()
parser.usage = textwrap.dedent()
group = optparse.OptionGroup(
parser, ,
)
group.add_option(
, , dest=, action=,
help=
)
group.add_option(
, dest=,
action=,
help=
)
... | Main. |
361,863 | def send_config_set(
self,
config_commands=None,
exit_config_mode=False,
delay_factor=1,
max_loops=150,
strip_prompt=False,
strip_command=False,
config_mode_command=None,
):
return super(VyOSSSH, self).send_config_set(
conf... | Remain in configuration mode. |
361,864 | def load_or_create_workflow(self):
self.workflow_spec = self.get_worfklow_spec()
return self._load_workflow() or self.create_workflow() | Tries to load the previously serialized (and saved) workflow
Creates a new one if it can't |
361,865 | def yml_fnc(fname, *args, **options):
key = "ac_safe"
fnc = getattr(yaml, r"safe_" + fname if options.get(key) else fname)
return fnc(*args, **common.filter_from_options(key, options)) | An wrapper of yaml.safe_load, yaml.load, yaml.safe_dump and yaml.dump.
:param fname:
"load" or "dump", not checked but it should be OK.
see also :func:`yml_load` and :func:`yml_dump`
:param args: [stream] for load or [cnf, stream] for dump
:param options: keyword args may contain "ac_safe" ... |
361,866 | def list_attached_storage_groups(self, full_properties=False):
sg_list = []
sg_uris = self.get_property()
if sg_uris:
cpc = self.manager.cpc
for sg_uri in sg_uris:
sg = cpc.storage_groups.resource_object(sg_uri)
sg_list.append(sg)
... | Return the storage groups that are attached to this partition.
The CPC must have the "dpm-storage-management" feature enabled.
Authorization requirements:
* Object-access permission to this partition.
* Task permission to the "Partition Details" task.
Parameters:
f... |
361,867 | def generate(self, x, **kwargs):
assert self.parse_params(**kwargs)
asserts = []
if self.clip_min is not None:
asserts.append(utils_tf.assert_greater_equal(x,
tf.cast(self.clip_min,
... | Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: Keyword arguments. See `parse_params` for documentation. |
361,868 | def load_template(filename):
template_file = os.path.join(PKG_DIR, , filename)
with open(template_file) as fp:
return fp.read() | Load template from file.
The templates are part of the package and must be included as
``package_data`` in project ``setup.py``.
Args:
filename (str):
The template path. Relative to `peltak` package directory.
Returns:
str: The content of the chosen template. |
361,869 | def _to_dict(self):
_dict = {}
if hasattr(self, ) and self.type is not None:
_dict[] = self.type
if hasattr(self, ) and self.frequency is not None:
_dict[] = self.frequency
if hasattr(self, ) and self.arguments is not None:
_dict[] = [x._to_di... | Return a json dictionary representing this model. |
361,870 | def set_params(self,**kwargs):
for key,value in list(kwargs.items()):
setattr(self,key,value) | Set the parameter values |
361,871 | def get_bank_lookup_session(self):
if not self.supports_bank_lookup():
raise errors.Unimplemented()
return sessions.BankLookupSession(runtime=self._runtime) | Gets the OsidSession associated with the bank lookup service.
return: (osid.assessment.BankLookupSession) - a
``BankLookupSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_bank_lookup() is false``
*compliance: optional -- T... |
361,872 | def build_polygon_dict(self,
path,
stroke_color=,
stroke_opacity=.8,
stroke_weight=2,
fill_color=,
fill_opacity=0.3):
if not isinstance(path... | Set a dictionary with the javascript class Polygon parameters
This function sets a default drawing configuration if the user just
pass the polygon path, but also allows to set each parameter
individually if the user wish so.
Args:
path (list): A list of latitude and longitu... |
361,873 | def kwinsert(clas,pool_or_cursor,**kwargs):
"kwargs version of insert"
returning = kwargs.pop(,None)
fields,vals = zip(*kwargs.items())
return clas.insert(pool_or_cursor,fields,vals,returning=returning) | kwargs version of insert |
361,874 | def prune_hashes(self, hashes, list_type):
discarded = []
for hash in hashes:
if (hash in self.hashes):
self.hashes.discard(hash)
discarded.append(hash)
self.logger.info("Not calculating %s hash(es) on destination as not present "
... | Prune any hashes not in source resource or change list. |
361,875 | def ensure_clean(self):
if not self.is_clean:
raise WorkingTreeNotCleanError(compact(, local=format_path(self.local))) | Make sure the working tree is clean (contains no changes to tracked files).
:raises: :exc:`~vcs_repo_mgr.exceptions.WorkingTreeNotCleanError`
when the working tree contains changes to tracked files. |
361,876 | def save_json(object, handle, indent=2):
obj_json = json.dumps(object, indent=indent, cls=NumpyJSONEncoder)
handle.write(obj_json) | Save object as json on CNS. |
361,877 | def calculate_size(name, timeout):
data_size = 0
data_size += calculate_size_str(name)
data_size += LONG_SIZE_IN_BYTES
return data_size | Calculates the request payload size |
361,878 | def _extract_resources(elem):
resources = collections.defaultdict(list)
for child in itertools.islice(elem.iter(), 1, None):
try:
basename = child.tag.split(, 1)[-1]
if child.text is not None:
child.text = child.text.strip()
... | Extract the children of an element as a key/value mapping. |
361,879 | def coefficient_of_variation(data, data_mean=None, data_stdev=None):
data_mean = data_mean or mean(data)
data_stdev = data_stdev or stdevp(data, data_mean)
if data_mean == 0:
return float("inf") if data_stdev != 0 else 0
else:
return data_stdev / data_mean | Return the coefficient of variation (CV) of a sequence of numbers.
:param data_mean: Precomputed mean of the sequence.
:param data_stdevp: Precomputed stdevp of the
sequence. |
361,880 | def get(self, deviceId, measurementId):
record = self.measurements.get(deviceId)
if record is not None:
return record.get(measurementId)
return None | details the specific measurement. |
361,881 | def group_keys(shape, *inputs_keys):
ndim = len(inputs_keys[0][0])
grouped_inputs_keys = {tuple((None, None, None)
for _ in range(ndim)): inputs_keys}
for dim, dim_len in enumerate(shape):
for group_keys, group_inputs_keys in grouped_inp... | Usecase: Two sets of chunks, one spans the whole of a dimension, the other
chunked it up. We need to know that we need to collect together the
chunked form, so that we can work with both sets at the same time.
Conceptually we have multiple source inputs, each with multiple key sets
for indexing.
... |
361,882 | def louvain_clustering(self, X=None, res=1, method=):
if X is None:
X = self.adata.uns[][]
save = True
else:
if not sp.isspmatrix_csr(X):
X = sp.csr_matrix(X)
save = False
import igraph as ig
import louvain
... | Runs Louvain clustering using the vtraag implementation. Assumes
that 'louvain' optional dependency is installed.
Parameters
----------
res - float, optional, default 1
The resolution parameter which tunes the number of clusters Louvain
finds.
method - s... |
361,883 | def _send_command(self, command, raw_text=False):
return self.device.show(command, raw_text=raw_text) | Wrapper for NX-API show method.
Allows more code sharing between NX-API and SSH. |
361,884 | def to_html(self, index=False, escape=False, header=True,
collapse_table=True, class_outer="table_outer", **kargs):
_buffer = {}
for k, v in self.pd_options.items():
_buffer[k] = pd.get_option(k)
pd.set_option(k, v)
... | Return HTML version of the table
This is a wrapper of the to_html method of the pandas dataframe.
:param bool index: do not include the index
:param bool escape: do not escape special characters
:param bool header: include header
:param bool collapse_table: long tables are shor... |
361,885 | def validate_users(self, **kwargs):
kwargs[] = True
if kwargs.get():
return self.validate_users_with_http_info(**kwargs)
else:
(data) = self.validate_users_with_http_info(**kwargs)
return data | Returns valid users and invalid identifiers from the given list # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.validate_users(async_req=True)
>>> result = thr... |
361,886 | def combine(self, a, b):
for l in (a, b):
for x in l:
yield x | A generator that combines two iterables. |
361,887 | def update_project(project):
try:
project_id = project.id
project = _forbidden_attributes(project)
res = _pybossa_req(, , project_id, payload=project.data)
if res.get():
return Project(res)
else:
return res
except:
raise | Update a project instance.
:param project: PYBOSSA project
:type project: PYBOSSA Project
:returns: True -- the response status code |
361,888 | def setup_connection():
try:
con_params = {
: os.getenv() or cfg.get(, ),
: os.getenv() or cfg.get(, ),
: os.getenv() or cfg.get(, ),
: os.getenv() or cfg.get(, )
}
except (configparser.NoOptionError, configparser.NoSectionError... | Set up the global pynipap connection object |
361,889 | def get_delete_security_group_commands(self, sg_id):
cmds = []
cmds.append("no ip access-list %s" %
self._acl_name(sg_id, n_const.INGRESS_DIRECTION))
cmds.append("no ip access-list %s" %
self._acl_name(sg_id, n_const.EGRESS_DIRECTION))
ret... | Commands for deleting ACL |
361,890 | def peer(opt_peer, opt_username, opt_password, scope="module"):
p = BigIP(opt_peer, opt_username, opt_password)
return p | peer bigip fixture |
361,891 | def build_authorization_request(username, method, uri, nonce_count, digest_challenge=None,
realm=None, nonce=None, opaque=None, password=None,
request_digest=None, client_nonce=None):
Authorization
if not client_nonce:
client_nonce = .join... | Builds an authorization request that may be sent as the value of the 'Authorization'
header in an HTTP request.
Either a digest_challenge object (as returned from parse_digest_challenge) or its required
component parameters (nonce, realm, opaque) must be provided.
The nonce_count should be the last us... |
361,892 | def add_register(self, register):
if(self._lock):
raise SetupError("RegisterInterface is already running, no changes to the register layout can be performed")
if(len(self.registers_by_index) >= self.size):
raise SetupError("Number of Registers would exceed the address space({})".format(self.size))
if(reg... | .. _add_register:
Adds the Register_ ``register`` to the interface.
Will raise a SetupError_ if the interface is locked (because it is running) or if
there is already a Register with the name of the new Register or if
the number of Registers would exceed the size of the interface.
Returns the index of the ... |
361,893 | def get_variation_from_id(self, experiment_key, variation_id):
variation_map = self.variation_id_map.get(experiment_key)
if variation_map:
variation = variation_map.get(variation_id)
if variation:
return variation
else:
self.logger.error( % variation_id)
self.err... | Get variation given experiment and variation ID.
Args:
experiment: Key representing parent experiment of variation.
variation_id: ID representing the variation.
Returns
Object representing the variation. |
361,894 | def invert(series):
df = series.reset_index()
df.set_index(series.name, inplace=True)
return df[df.columns[0]] | Swap index with values of series.
Parameters
----------
series : ~pandas.Series
Series to swap on, must have a name.
Returns
-------
~pandas.Series
Series after swap.
See also
--------
pandas.Series.map
Joins series ``a -> b`` and ``b -> c`` into ``a -> c``... |
361,895 | def make_clean_html(raw, stream_item=None, encoding=None):
raw = fix_emails(raw)
raw_decoded = nice_decode(raw, stream_item=stream_item, encoding=encoding)
if raw_decoded is None:
raw_decoded = raw
try:
root = lxml.html.document_fromstring(raw_decoded)
except... | Get a clean text representation of presumed HTML.
Treat `raw` as though it is HTML, even if we have no idea what it
really is, and attempt to get a properly formatted HTML document
with all HTML-escaped characters converted to their unicode.
This is called below by the `clean_html` transform stage, wh... |
361,896 | def _build_web_client(cls, session: AppSession):
cookie_jar = cls._build_cookie_jar(session)
http_client = cls._build_http_client(session)
redirect_factory = functools.partial(
session.factory.class_map[],
max_redirects=session.args.max_redirect
)
... | Build Web Client. |
361,897 | def CalculateBestPosition(self,widget):
"When dealing with a Top-Level window position it absolute lower-right"
if isinstance(widget, wx.Frame):
screen = wx.ClientDisplayRect()[2:]
left,top = widget.ClientToScreenXY(0,0)
right,bottom = widget.ClientToScreenXY(*widget.... | When dealing with a Top-Level window position it absolute lower-right |
361,898 | def longest_non_repeat_v1(string):
if string is None:
return 0
dict = {}
max_length = 0
j = 0
for i in range(len(string)):
if string[i] in dict:
j = max(dict[string[i]], j)
dict[string[i]] = i + 1
max_length = max(max_length, i - j + 1)
return max... | Find the length of the longest substring
without repeating characters. |
361,899 | def run(self):
compiler = new_compiler(compiler=self.compiler)
if compiler.compiler_type == "msvc":
self.define = [
("UNICODE", ""),
]
else:
command = "sh configure --disable-shared-libs"
output = self._RunCommand(command)
print_line = False
for line in o... | Runs the build extension. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.