Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
388,000 | def server_info(self):
response = self._post(self.apiurl + "/v2/server/info", data={: self.apikey})
return self._raise_or_extract(response) | Query information about the server. |
388,001 | def get_by_index(self, index):
try:
return self[index]
except KeyError:
for v in self.get_volumes():
if v.index == str(index):
return v
raise KeyError(index) | Returns a Volume or Disk by its index. |
388,002 | def run_subprocess(executable_command,
command_arguments = [],
timeout=None,
print_process_output=True,
stdout_file=None,
stderr_file=None,
poll_seconds=.100,
buffer_size=-1,
... | Create and run a subprocess and return the process and
execution time after it has completed. The execution time
does not include the time taken for file i/o when logging
the output if stdout_file and stderr_file arguments are given.
Positional arguments:
executable_command (str) -- executable com... |
388,003 | def main():
args = _parse_arg(CountryConverter().valid_class)
coco = CountryConverter(additional_data=args.additional_data)
converted_names = coco.convert(
names=args.names,
src=args.src,
to=args.to,
enforce_list=False,
not_found=args.not_found)
print(args.o... | Main entry point - used for command line call |
388,004 | def mkdir(dir_path):
if not os.path.isdir(dir_path) or not os.path.exists(dir_path):
os.makedirs(dir_path) | Make directory if not existed |
388,005 | async def genSchema(self, name, version, attrNames) -> Schema:
schema = Schema(name, version, attrNames, self.issuerId)
return await self.wallet.submitSchema(schema) | Generates and submits Schema.
:param name: schema name
:param version: schema version
:param attrNames: a list of attributes the schema contains
:return: submitted Schema |
388,006 | def _clean_rule(self, rule):
if rule.at_keyword is not None:
return rule
cleaned_token_list = []
for token_list in split_on_comma(rule.selector):
if self._token_list_matches_tree(token_list):
if ... | Cleans a css Rule by removing Selectors without matches on the tree
Returns None if the whole rule do not match
:param rule: CSS Rule to check
:type rule: A tinycss Rule object
:returns: A cleaned tinycss Rule with only Selectors matching the tree or None
:rtype: tinycss Rule or... |
388,007 | def GeneratePassphrase(length=20):
valid_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
valid_chars += "0123456789 ,-_&$
return "".join(random.choice(valid_chars) for i in range(length)) | Create a 20 char passphrase with easily typeable chars. |
388,008 | def element_to_objects(payload: Dict) -> List:
entities = []
cls = MAPPINGS.get(payload.get())
if not cls:
return []
transformed = transform_attributes(payload, cls)
entity = cls(**transformed)
if hasattr(entity, "post_receive"):
entity.post_receive()
entities.append(... | Transform an Element to a list of entities recursively. |
388,009 | def last_modified(self):
if self.entries:
latest = max(self.entries, key=lambda x: x.last_modified)
return arrow.get(latest.last_modified)
return arrow.get() | Gets the most recent modification time for all entries in the view |
388,010 | def natsorted(seq, key=None, reverse=False, alg=ns.DEFAULT):
key = natsort_keygen(key, alg)
return sorted(seq, reverse=reverse, key=key) | Sorts an iterable naturally.
Parameters
----------
seq : iterable
The input to sort.
key : callable, optional
A key used to determine how to sort each element of the iterable.
It is **not** applied recursively.
It should accept a single argument and return a single valu... |
388,011 | def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs):
s docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see modules docstring)
:return: Trigger ID and description. False if no trigger found or on failure.
CLI Example:
.. cod... | .. versionadded:: Fluorine
Retrieve trigger ID and description based in host ID and trigger description.
.. note::
https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
:param hostid: ID of the host whose trigger we want to find
:param trigger_desc: Description of trigger ... |
388,012 | def remove_hyperedge(self, hyperedge_id):
if not self.has_hyperedge_id(hyperedge_id):
raise ValueError("No such hyperedge exists.")
frozen_tail = \
self._hyperedge_attributes[hyperedge_id]["__frozen_tail"]
frozen_head = \
self._hyperedge_attributes[h... | Removes a hyperedge and its attributes from the hypergraph.
:param hyperedge_id: ID of the hyperedge to be removed.
:raises: ValueError -- No such hyperedge exists.
Examples:
::
>>> H = DirectedHypergraph()
>>> xyz = hyperedge_list = ((["A"], ["B", "C"]),
... |
388,013 | def pipeline(self, config, request):
path_chain = request[]
if not path_chain or path_chain[0] != :
raise HTTPError(400)
authers = config.get()
if authers is None:
raise HTTPError(403)
valid_once = False
for auth in ... | The pipeline() function handles authentication and invocation of
the correct consumer based on the server configuration, that is
provided at initialization time.
When authentication is performed all the authenticators are
executed. If any returns False, authentication fails and a 403
... |
388,014 | def execute(self, context):
hook = SQSHook(aws_conn_id=self.aws_conn_id)
result = hook.send_message(queue_url=self.sqs_queue,
message_body=self.message_content,
delay_seconds=self.delay_seconds,
... | Publish the message to SQS queue
:param context: the context object
:type context: dict
:return: dict with information about the message sent
For details of the returned dict see :py:meth:`botocore.client.SQS.send_message`
:rtype: dict |
388,015 | def is_me(self):
logger.info("And arbiter is launched with the hostname:%s "
"from an arbiter point of view of addr:%s", self.host_name, socket.getfqdn())
return self.host_name == socket.getfqdn() or self.host_name == socket.gethostname() | Check if parameter name if same than name of this object
TODO: is it useful?
:return: true if parameter name if same than this name
:rtype: bool |
388,016 | def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
for p in group[]:
if p.grad is None:
continue
grad = p.grad.data
if grad.is_spa... | Performs a single optimization step.
Arguments:
closure (callable, optional): A closure that reevaluates the model
and returns the loss. |
388,017 | def write_hdf5_segmentlist(seglist, output, path=None, **kwargs):
if path is None:
raise ValueError("Please specify the HDF5 path via the "
"``path=`` keyword argument")
data = numpy.zeros((len(seglist), 4), dtype=int)
for i, seg in enumerate(seglist):
sta... | Write a `SegmentList` to an HDF5 file/group
Parameters
----------
seglist : :class:`~ligo.segments.segmentlist`
data to write
output : `str`, `h5py.File`, `h5py.Group`
filename or HDF5 object to write to
path : `str`
path to which to write inside the HDF5 file, relative to... |
388,018 | def unary_from_softmax(sm, scale=None, clip=1e-5):
num_cls = sm.shape[0]
if scale is not None:
assert 0 < scale <= 1, "`scale` needs to be in (0,1]"
uniform = np.ones(sm.shape) / num_cls
sm = scale * sm + (1 - scale) * uniform
if clip is not None:
sm = np.clip(sm, clip, ... | Converts softmax class-probabilities to unary potentials (NLL per node).
Parameters
----------
sm: numpy.array
Output of a softmax where the first dimension is the classes,
all others will be flattend. This means `sm.shape[0] == n_classes`.
scale: float
The certainty of the soft... |
388,019 | def init_app(self, app):
self.init_config(app)
blueprint = rest.create_blueprint(
app.config[]
)
post_action.connect(index_deposit_after_publish, sender=app,
weak=False) | Flask application initialization.
Initialize the REST endpoints. Connect all signals if
`DEPOSIT_REGISTER_SIGNALS` is True.
:param app: An instance of :class:`flask.Flask`. |
388,020 | def range(self, channels=None):
if channels is None:
channels = self._channels
channels = self._name_to_index(channels)
if hasattr(channels, ) \
and not isinstance(channels, six.string_types):
return [self._range[ch] f... | Get the range of the specified channel(s).
The range is a two-element list specifying the smallest and largest
values that an event in a channel should have. Note that with
floating point data, some events could have values outside the
range in either direction due to instrument compens... |
388,021 | def feature_match(template, image, options=None):
op = _DEF_TM_OPT.copy()
if options is not None:
op.update(options)
feat = fe.factory(op[])
tmpl_f = feat(template, op)
img_f = feat(image, op)
scale = image.shape[0] / img_f.shape[0]
heatmap = match_template(tmpl_f, img_f, op)
... | Match template and image by extracting specified feature
:param template: Template image
:param image: Search image
:param options: Options include
- feature: Feature extractor to use. Default is 'rgb'. Available options are:
'hog', 'lab', 'rgb', 'gray'
:return: Heatmap |
388,022 | def redirects(self):
if self._redirects is None:
self._redirects = list()
self.__pull_combined_properties()
return self._redirects | list: List of all redirects to this page; **i.e.,** the titles \
listed here will redirect to this page title
Note:
Not settable |
388,023 | def _configure_device(commands, **kwargs):
if salt.utils.platform.is_proxy():
return __proxy__[](commands, **kwargs)
else:
return _nxapi_config(commands, **kwargs) | Helper function to send configuration commands to the device over a
proxy minion or native minion using NX-API or SSH. |
388,024 | def fanout(self, hosts=None, timeout=None, max_concurrency=64,
auto_batch=None):
return MapManager(self.get_fanout_client(hosts, max_concurrency,
auto_batch),
timeout=timeout) | Returns a context manager for a map operation that fans out to
manually specified hosts instead of using the routing system. This
can for instance be used to empty the database on all hosts. The
context manager returns a :class:`FanoutClient`. Example usage::
with cluster.fanout(... |
388,025 | def meta_changed_notify_after(self, state_machine_m, _, info):
meta_signal_message = info[]
if meta_signal_message.origin == "graphical_editor_gaphas":
return
if meta_signal_message.origin == "load_meta_data":
"MAX_VISIBLE_LIBRARY_HIERARCHY... | Handle notification about the change of a state's meta data
The meta data of the affected state(s) are read and the view updated accordingly.
:param StateMachineModel state_machine_m: Always the state machine model belonging to this editor
:param str _: Always "state_meta_signal"
:param... |
388,026 | def _handle_auth(self, dtype, data, ts):
if dtype == :
raise NotImplementedError
channel_id = data.pop()
user_id = data.pop()
identifier = (, user_id)
self.channel_handlers[identifier] = channel_id
self.channel_directory[identifier] = channe... | Handles authentication responses.
:param dtype:
:param data:
:param ts:
:return: |
388,027 | def addItem(self, item):
try:
self.tree.addItem(item)
except AttributeError, e:
raise VersionError() | Adds an item if the tree is mutable |
388,028 | def _iter_rawterms(cls, tree):
for elem in tree.iterfind(OWL_CLASS):
if RDF_ABOUT not in elem.keys():
continue
rawterm = cls._extract_resources(elem)
rawterm[] = cls._get_id_from_url(elem.get(RDF_ABOUT))
yield raw... | Iterate through the raw terms (Classes) in the ontology. |
388,029 | def _split_line_with_offsets(line):
for delimiter in re.finditer(r"[\.,:\;](?![^\s])", line):
span = delimiter.span()
line = line[:span[0]] + " " + line[span[1]:]
for delimiter in re.finditer(r"[\"\)\]\}>\s])",
line):
span = delimiter.span()
... | Split a line by delimiter, but yield tuples of word and offset.
This function works by dropping all the english-like punctuation from
a line (so parenthesis preceded or succeeded by spaces, periods, etc)
and then splitting on spaces. |
388,030 | def find_id_in_folder(self, name, parent_folder_id=0):
if name is None or len(name) == 0:
return parent_folder_id
offset = 0
resp = self.get_folder_items(parent_folder_id,
limit=1000, offset=offset,
fi... | Find a folder or a file ID from its name, inside a given folder.
Args:
name (str): Name of the folder or the file to find.
parent_folder_id (int): ID of the folder where to search.
Returns:
int. ID of the file or folder found. None if not found.
Raises:
... |
388,031 | def get_section(self, section_id, params={}):
url = SECTIONS_API.format(section_id)
return CanvasSection(data=self._get_resource(url, params=params)) | Return section resource for given canvas section id.
https://canvas.instructure.com/doc/api/sections.html#method.sections.show |
388,032 | def dump(self):
from rez.utils.formatting import columnise
rows = []
for i, phase in enumerate(self.phase_stack):
rows.append((self._depth_label(i), phase.status, str(phase)))
print "status: %s (%s)" % (self.status.name, self.status.description)
print "init... | Print a formatted summary of the current solve state. |
388,033 | def load(self, config):
web_list = []
if config is None:
logger.debug("No configuration file available. Cannot load ports list.")
elif not config.has_section(self._section):
logger.debug("No [%s] section in the configuration file. Cannot load ports list." % self... | Load the web list from the configuration file. |
388,034 | def absent(name, **connection_args):
ret = {: name,
: {},
: True,
: }
if __salt__[](name, **connection_args):
if __opts__[]:
ret[] = None
ret[] = \
.format(name)
return ret
if __salt__[](name, **conne... | Ensure that the named database is absent
name
The name of the database to remove |
388,035 | def main():
colorama.init(wrap=six.PY3)
doc = usage.get_primary_command_usage()
allow_subcommands = in doc
args = docopt(doc, version=settings.version,
options_first=allow_subcommands)
if sys.excepthook is sys.__excepthook__:
sys.excepthook = log.excepthook
t... | Parse the command line options and launch the requested command.
If the command is 'help' then print the help message for the subcommand; if
no subcommand is given, print the standard help message. |
388,036 | def handleMatch(self, m):
userStr = m.group(3)
imgURL = processString(userStr)
el = etree.Element()
el.set(, imgURL)
el.set(, userStr)
el.set(, userStr)
return el | Handles user input into [magic] tag, processes it,
and inserts the returned URL into an <img> tag
through a Python ElementTree <img> Element. |
388,037 | def run(data):
name = dd.get_sample_name(data)
in_bam = dd.get_transcriptome_bam(data)
config = data[]
if not in_bam:
logger.info("Transcriptome-mapped BAM file not found, skipping eXpress.")
return data
out_dir = os.path.join(dd.get_work_dir(data), "express", name)
out_file... | Quantitaive isoforms expression by eXpress |
388,038 | def idle_task(self):
for r in self.repeats:
if r.event.trigger():
self.mpstate.functions.process_stdin(r.cmd, immediate=True) | called on idle |
388,039 | def task(name, deps = None, fn = None):
if callable(deps):
fn = deps
deps = None
if not deps and not fn:
logger.log(logger.red("The task is empty" % name))
else:
tasks[name] = [fn, deps] | Define a new task. |
388,040 | def paginate(self):
project_dir = self.project_dir
raw_dir = self.raw_dir
batch_dir = self.batch_dir
if project_dir is None:
raise UnderDefined("no project directory defined")
if raw_dir is None:
raise UnderDefined("no raw directory defined")
... | Make folders where we would like to put results etc. |
388,041 | def detect_direct_function_shadowing(contract):
functions_declared = {function.full_name: function for function in contract.functions_and_modifiers_not_inherited}
results = {}
for base_contract in reversed(contract.immediate_inheritance):
for base_function in base_contract.functions_and_modifie... | Detects and obtains functions which are shadowed immediately by the provided ancestor contract.
:param contract: The ancestor contract which we check for function shadowing within.
:return: A list of tuples (overshadowing_function, overshadowed_immediate_base_contract, overshadowed_function)
-overshadowing_... |
388,042 | def _factory(cls, constraints, op):
pieces = []
for i, constraint in enumerate(constraints):
pieces.append(constraint)
if i != len(constraints) - 1:
pieces.append(op)
return cls(pieces) | Factory for joining constraints with a single conjunction |
388,043 | def _handle_chat(self, data):
self.conn.enqueue_data(
"chat", ChatMessage.from_data(self.room, self.conn, data)
) | Handle chat messages |
388,044 | def search_upwards(self, fpath=None, repodirname=, upwards={}):
fpath = fpath or self.fpath
uuid = self.unique_id
last_path = self
path_comp = fpath.split(os.path.sep)
for n in xrange(1, len(path_comp)-1):
checkpath = os.path.join(*path_comp[0:-1 * ... | Traverse filesystem upwards, searching for .svn directories
with matching UUIDs (Recursive)
Args:
fpath (str): file path to search upwards from
repodirname (str): directory name to search for (``.svn``)
upwards (dict): dict of already-searched directories
ex... |
388,045 | def pretty_time(timestamp: str):
try:
parsed = iso_8601.parse_datetime(timestamp)
except ValueError:
now = datetime.utcnow().replace(tzinfo=timezone.utc)
try:
delta = iso_8601.parse_delta(timestamp)
except ValueError:
delta = human_time.parse_timedelt... | Format timestamp for human consumption. |
388,046 | def _sync_io(self):
if self._file_epoch == self.file_object.epoch:
return
if self._io.binary:
contents = self.file_object.byte_contents
else:
contents = self.file_object.contents
self._set_stream_contents(contents)
self._file_epoch =... | Update the stream with changes to the file object contents. |
388,047 | def find_bidi(self, el):
for node in self.get_children(el, tags=False):
if self.is_tag(node):
direction = DIR_MAP.get(util.lower(self.get_attribute_by_name(node, , )), None)
if (
self.get_tag(node) in (, , ... | Get directionality from element text. |
388,048 | def filter_missing(self):
missing = None
locus_count = 0
self.genotype_file.seek(0)
for genotypes in self.genotype_file:
genotypes = genotypes.split()
chr, rsid, junk, pos = genotypes[0:4]
if DataParser.boundary.... | Filter out individuals and SNPs that have too many missing to be considered |
388,049 | def add_cmds_cpdir(cpdir,
cmdpkl,
cpfileglob=,
require_cmd_magcolor=True,
save_cmd_pngs=False):
s
objectinfo dict.
save_cmd_pngs : bool
If this is True, then will save the CMD plots that were generated and
added... | This adds CMDs for each object in cpdir.
Parameters
----------
cpdir : list of str
This is the directory to search for checkplot pickles.
cmdpkl : str
This is the filename of the CMD pickle created previously.
cpfileglob : str
The UNIX fileglob to use when searching for c... |
388,050 | def datapoint_indices_for_tensor(self, tensor_index):
if tensor_index >= self._num_tensors:
raise ValueError( %(tensor_index, self._num_tensors))
return self._file_num_to_indices[tensor_index] | Returns the indices for all datapoints in the given tensor. |
388,051 | def marshal(self, values):
if values is not None:
return [super(EntityCollection, self).marshal(v) for v in values] | Turn a list of entities into a list of dictionaries.
:param values: The entities to serialize.
:type values: List[stravalib.model.BaseEntity]
:return: List of dictionaries of attributes
:rtype: List[Dict[str, Any]] |
388,052 | def _search(self, limit, format):
limit = min(limit, self.MAX_SEARCH_PER_QUERY)
payload = {
: self.query,
: limit,
: self.current_offset,
}
payload.update(self.CUSTOM_PARAMS)
headers = { : self.api_key }
if not self.silent_fail:... | Returns a list of result objects, with the url for the next page MsCognitive search url. |
388,053 | def boggle_hill_climbing(board=None, ntimes=100, verbose=True):
finder = BoggleFinder()
if board is None:
board = random_boggle()
best = len(finder.set_board(board))
for _ in range(ntimes):
i, oldc = mutate_boggle(board)
new = len(finder.set_board(board))
if new > be... | Solve inverse Boggle by hill-climbing: find a high-scoring board by
starting with a random one and changing it. |
388,054 | def proc_collector(process_map, args, pipeline_string):
arguments_list = []
if args.detailed_list:
arguments_list += [
"input_type",
"output_type",
"description",
"dependencies",
"conflicts",
"directives"
... | Function that collects all processes available and stores a dictionary of
the required arguments of each process class to be passed to
procs_dict_parser
Parameters
----------
process_map: dict
The dictionary with the Processes currently available in flowcraft
and their corresponding... |
388,055 | def _set_interface_brief(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=interface_brief.interface_brief, is_container=, presence=False, yang_name="interface-brief", rest_name="interface-brief", parent=self, path_helper=self._path_helper, extmethods=s... | Setter method for interface_brief, mapped from YANG variable /isis_state/interface_brief (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_interface_brief is considered as a private
method. Backends looking to populate this variable should
do so via calling thi... |
388,056 | def clear_all_events(self):
self.lock.acquire()
self.event_dict.clear()
self.lock.release() | Clear all event queues and their cached events. |
388,057 | def loadPng(varNumVol, tplPngSize, strPathPng):
print()
lstPngPaths = [None] * varNumVol
for idx01 in range(0, varNumVol):
lstPngPaths[idx01] = (strPathPng + str(idx01) + )
aryPngData = np.zeros((tplPngSize[0],
tplPngSize[1],
... | Load PNG files.
Parameters
----------
varNumVol : float
Number of volumes, i.e. number of time points in all runs.
tplPngSize : tuple
Shape of the stimulus image (i.e. png).
strPathPng: str
Path to the folder cointaining the png files.
Returns
-------
aryPngData ... |
388,058 | def new_transaction(
vm: VM,
from_: Address,
to: Address,
amount: int=0,
private_key: PrivateKey=None,
gas_price: int=10,
gas: int=100000,
data: bytes=b) -> BaseTransaction:
nonce = vm.state.get_nonce(from_)
tx = vm.create_unsigned_transaction... | Create and return a transaction sending amount from <from_> to <to>.
The transaction will be signed with the given private key. |
388,059 | def decorator(directname=None):
global _decorators
class_deco_list = _decorators
def wrapper(f):
nonlocal directname
if directname is None:
directname = f.__name__
f.ns_name = directname
set_one(class_deco_list, directname, f)
return wrapper | Attach a class to a parsing decorator and register it to the global
decorator list.
The class is registered with its name unless directname is provided |
388,060 | def query_by_user(cls, user, **kwargs):
return cls._filter(
cls.query.filter_by(user_id=user.get_id()),
**kwargs
) | Get a user's memberships. |
388,061 | def _prepare_transformation_recipe(pattern: str, reduction: str, axes_lengths: Tuple) -> TransformRecipe:
left, right = pattern.split()
identifiers_left, composite_axes_left = parse_expression(left)
identifiers_rght, composite_axes_rght = parse_expression(right)
if reduction == :
diff... | Perform initial parsing of pattern and provided supplementary info
axes_lengths is a tuple of tuples (axis_name, axis_length) |
388,062 | def merge_items(from_id, to_id, login_obj, mediawiki_api_url=,
ignore_conflicts=, user_agent=config[]):
url = mediawiki_api_url
headers = {
: ,
: ,
: user_agent
}
params = {
: ,
: from_id,
... | A static method to merge two Wikidata items
:param from_id: The QID which should be merged into another item
:type from_id: string with 'Q' prefix
:param to_id: The QID into which another item should be merged
:type to_id: string with 'Q' prefix
:param login_obj: The object conta... |
388,063 | def check_config_mode(self, check_string=")
return super(CiscoBaseConnection, self).check_config_mode(
check_string=check_string, pattern=pattern
) | Checks if the device is in configuration mode or not.
Cisco IOS devices abbreviate the prompt at 20 chars in config mode |
388,064 | def compose_object(self, file_list, destination_file, content_type):
xml_setting_list = []
for meta_data in file_list:
xml_setting_list.append()
for key, val in meta_data.iteritems():
xml_setting_list.append( % (key, val, key))
xml_setting_list.append()
xml_setting_list.appe... | COMPOSE multiple objects together.
Using the given list of files, calls the put object with the compose flag.
This call merges all the files into the destination file.
Args:
file_list: list of dicts with the file name.
destination_file: Path to the destination file.
content_type: Content... |
388,065 | def get_east_asian_width_property(value, is_bytes=False):
obj = unidata.ascii_east_asian_width if is_bytes else unidata.unicode_east_asian_width
if value.startswith():
negated = value[1:]
value = + unidata.unicode_alias[].get(negated, negated)
else:
value = unidata.unicode_al... | Get `EAST ASIAN WIDTH` property. |
388,066 | def setup_multiprocessing_logging(queue=None):
from salt.utils.platform import is_windows
global __MP_LOGGING_CONFIGURED
global __MP_LOGGING_QUEUE_HANDLER
if __MP_IN_MAINPROCESS is True and not is_windows():
__MP_LOGGING_CONFIGURED = True
if __MP_LOGGING_QUEUE_HANDLER is... | This code should be called from within a running multiprocessing
process instance. |
388,067 | def process(self, formdata=None, obj=None, data=None, **kwargs):
self._obj = obj
super(CommonFormMixin, self).process(formdata, obj, data, **kwargs) | Wrap the process method to store the current object instance |
388,068 | def url(self):
if isinstance(self.result, types.BotInlineResult):
return self.result.url | The URL present in this inline results. If you want to "click"
this URL to open it in your browser, you should use Python's
`webbrowser.open(url)` for such task. |
388,069 | def _prm_write_shared_array(self, key, data, hdf5_group, full_name, flag, **kwargs):
if flag == HDF5StorageService.ARRAY:
self._prm_write_into_array(key, data, hdf5_group, full_name, **kwargs)
elif flag in (HDF5StorageService.CARRAY,
HDF5StorageService.EARRAY,
... | Creates and array that can be used with an HDF5 array object |
388,070 | def map_components(notsplit_packages, components):
packages = set()
for c in components:
if c in notsplit_packages:
packages.add()
else:
packages.add(c)
return list(packages) | Returns a list of packages to install based on component names
This is done by checking if a component is in notsplit_packages,
if it is, we know we need to install 'ceph' instead of the
raw component name. Essentially, this component hasn't been
'split' from the master 'ceph' package yet. |
388,071 | def _dict_to_map_str_str(self, d):
return dict(map(
lambda (k, v): (k, str(v).lower() if isinstance(v, bool) else str(v)),
d.iteritems()
)) | Thrift requires the params and headers dict values to only contain str values. |
388,072 | def configure_retrieve(self, ns, definition):
request_schema = definition.request_schema or Schema()
@self.add_route(ns.instance_path, Operation.Retrieve, ns)
@qs(request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def retrieve(**path_d... | Register a retrieve endpoint.
The definition's func should be a retrieve function, which must:
- accept kwargs for path data
- return an item or falsey
:param ns: the namespace
:param definition: the endpoint definition |
388,073 | def save_history(self, f):
warnings.warn(
"save_history is deprecated and will be removed in the next "
"release, please use save_params with the f_history keyword",
DeprecationWarning)
self.history.to_file(f) | Saves the history of ``NeuralNet`` as a json file. In order
to use this feature, the history must only contain JSON encodable
Python data structures. Numpy and PyTorch types should not
be in the history.
Parameters
----------
f : file-like object or str
Examples... |
388,074 | def lessThan(self, leftIndex, rightIndex):
leftData = self.sourceModel().data(leftIndex, RegistryTableModel.SORT_ROLE)
rightData = self.sourceModel().data(rightIndex, RegistryTableModel.SORT_ROLE)
return leftData < rightData | Returns true if the value of the item referred to by the given index left is less than
the value of the item referred to by the given index right, otherwise returns false. |
388,075 | def convert_representation(self, i):
if self.number_representation == :
return i
elif self.number_representation == :
if i & (1 << self.interpreter._bit_width - 1):
return -((~i + 1) & (2**self.interpreter._bit_width - 1))
else:
... | Return the proper representation for the given integer |
388,076 | def rescale_gradients(model: Model, grad_norm: Optional[float] = None) -> Optional[float]:
if grad_norm:
parameters_to_clip = [p for p in model.parameters()
if p.grad is not None]
return sparse_clip_norm(parameters_to_clip, grad_norm)
return None | Performs gradient rescaling. Is a no-op if gradient rescaling is not enabled. |
388,077 | def solution(self, expr, v, extra_constraints=(), solver=None, model_callback=None):
if self._solver_required and solver is None:
raise BackendError("%s requires a solver for evaluation" % self.__class__.__name__)
return self._solution(self.convert(expr), self.convert(v), extra_con... | Return True if `v` is a solution of `expr` with the extra constraints, False otherwise.
:param expr: An expression (an AST) to evaluate
:param v: The proposed solution (an AST)
:param solver: A solver object, native to the backend, to assist in the ... |
388,078 | def get_bios_firmware_version(snmp_client):
try:
bios_firmware_version = snmp_client.get(BIOS_FW_VERSION_OID)
return six.text_type(bios_firmware_version)
except SNMPFailure as e:
raise SNMPBIOSFirmwareFailure(
SNMP_FAILURE_MSG % ("GET BIOS FIRMWARE VERSION", e)) | Get bios firmware version of the node.
:param snmp_client: an SNMP client object.
:raises: SNMPFailure if SNMP operation failed.
:returns: a string of bios firmware version. |
388,079 | def _get_path_pattern_tornado45(self, router=None):
if router is None:
router = self.application.default_router
for rule in router.rules:
if rule.matcher.match(self.request) is not None:
if isinstance(rule.matcher, routing.PathMatches):
... | Return the path pattern used when routing a request. (Tornado>=4.5)
:param tornado.routing.Router router: (Optional) The router to scan.
Defaults to the application's router.
:rtype: str |
388,080 | def print_trace(self, file=sys.stdout, base=10, compact=False):
if len(self.trace) == 0:
raise PyrtlError()
if base not in (2, 8, 10, 16):
raise PyrtlError()
basekey = {2: , 8: , 10: , 16: }[base]
ident_len = max(len(w) for w in self.trace)
if c... | Prints a list of wires and their current values.
:param int base: the base the values are to be printed in
:param bool compact: whether to omit spaces in output lines |
388,081 | def insert(self, song):
if song in self._songs:
return
if self._current_song is None:
self._songs.append(song)
else:
index = self._songs.index(self._current_song)
self._songs.insert(index + 1, song) | 在当前歌曲后插入一首歌曲 |
388,082 | def start(workflow_name, data=None, object_id=None, **kwargs):
from .proxies import workflow_object_class
from .worker_engine import run_worker
if data is None and object_id is None:
raise WorkflowsMissingData("No data or object_id passed to task.ß")
if object_id is not None:
obj ... | Start a workflow by given name for specified data.
The name of the workflow to start is considered unique and it is
equal to the name of a file containing the workflow definition.
The data passed could be a list of Python standard data types such as
strings, dict, integers etc. to run through the work... |
388,083 | def _netbsd_gpu_data():
known_vendors = [, , , , , , , ]
gpus = []
try:
pcictl_out = __salt__[]()
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r.format(vendor),
line,
... | num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string |
388,084 | def is_ancestor(self, commit1, commit2, patch=False):
result = self.hg("log", "-r", "first(%s::%s)" % (commit1, commit2),
"--template", "exists", patch=patch)
return "exists" in result | Returns True if commit1 is a direct ancestor of commit2, or False
otherwise.
This method considers a commit to be a direct ancestor of itself |
388,085 | async def update(self, obj, only=None):
field_dict = dict(obj.__data__)
pk_field = obj._meta.primary_key
if only:
self._prune_fields(field_dict, only)
if obj._meta.only_save_dirty:
self._prune_fields(field_dict, obj.dirty_fields)
if obj._meta.c... | Update the object in the database. Optionally, update only
the specified fields. For creating a new object use :meth:`.create()`
:param only: (optional) the list/tuple of fields or
field names to update |
388,086 | def file_content(self, value):
if isinstance(value, FileContent):
self._file_content = value
else:
self._file_content = FileContent(value) | The Base64 encoded content of the attachment
:param value: The Base64 encoded content of the attachment
:type value: FileContent, string |
388,087 | def parse_element(raw_element: str) -> List[Element]:
elements = [regex.match("^(([a-zA-Z]+)\(([^;]+),List\(([^;]*)\)\))$",
elem.lstrip().rstrip())
for elem
in raw_element.split()]
return [interpret_element(*elem.groups()[1:])
for elem... | Parse a raw element into text and indices (integers). |
388,088 | def list_services(request, step):
all_datas = []
if step == :
services = ServicesActivated.objects.filter(status=1)
elif step == :
services = ServicesActivated.objects.filter(status=1, id__iexact=request.id)
for class_name in services:
all_datas.append({class_name: class_na... | get the activated services added from the administrator
:param request: request object
:param step: the step which is proceeded
:type request: HttpRequest object
:type step: string
:return the activated services added from the administrator |
388,089 | def cd_to(path, mkdir=False):
def cd_to_decorator(func):
@functools.wraps(func)
def _cd_and_exec(*args, **kwargs):
with cd(path, mkdir):
return func(*args, **kwargs)
return _cd_and_exec
return cd_to_decorator | make a generator like cd, but use it for function
Usage::
>>> @cd_to("/")
... def say_where():
... print(os.getcwd())
...
>>> say_where()
/ |
388,090 | def to_python(self, value):
if isinstance(value, DirDescriptor):
return value
elif isinstance(value, str):
return DirDescriptor(value)
elif isinstance(value, dict):
try:
path = value[]
except KeyError:
raise... | Convert value if needed. |
388,091 | def _get_content_type(url, session):
scheme, netloc, path, query, fragment = urllib_parse.urlsplit(url)
if scheme not in (, ):
return
resp = session.head(url, allow_redirects=True)
resp.raise_for_status()
return resp.headers.get("... | Get the Content-Type of the given url, using a HEAD request |
388,092 | def getFieldMax(self, fieldName):
stats = self.getStats()
if stats == None:
return None
maxValues = stats.get(, None)
if maxValues == None:
return None
index = self.getFieldNames().index(fieldName)
return maxValues[index] | If underlying implementation does not support min/max stats collection,
or if a field type does not support min/max (non scalars), the return
value will be None.
:param fieldName: (string) name of field to get max
:returns: current maximum value for the field ``fieldName``. |
388,093 | def create_dialog_node(self,
workspace_id,
dialog_node,
description=None,
conditions=None,
parent=None,
previous_sibling=None,
outp... | Create dialog node.
Create a new dialog node.
This operation is limited to 500 requests per 30 minutes. For more information,
see **Rate limiting**.
:param str workspace_id: Unique identifier of the workspace.
:param str dialog_node: The dialog node ID. This string must conform... |
388,094 | def match(self, search, **kwargs):
kwargs[] = True
if kwargs.get():
return self.match_with_http_info(search, **kwargs)
else:
(data) = self.match_with_http_info(search, **kwargs)
return data | Searches for Repository Configurations based on internal or external url, ignoring the protocol and \".git\" suffix. Only exact matches are returned.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be ... |
388,095 | def v1_folder_rename(request, response, kvlclient,
fid_src, fid_dest, sfid_src=None, sfid_dest=None):
src, dest = make_path(fid_src, sfid_src), make_path(fid_dest, sfid_dest)
new_folders(kvlclient, request).move(src, dest)
response.status = 200 | Rename a folder or a subfolder.
The routes for this endpoint are:
* ``POST /dossier/v1/<fid_src>/rename/<fid_dest>``
* ``POST /dossier/v1/<fid_src>/subfolder/<sfid_src>/rename/
<fid_dest>/subfolder/<sfid_dest>`` |
388,096 | def _bld_pnab_generic(self, funcname, **kwargs):
margs = {: pnab, : kwargs}
setattr(self, funcname, margs) | implement's a generic version of a non-attribute based pandas function |
388,097 | def _doc2vec_doc_stream(paths, n, tokenizer=word_tokenize, sentences=True):
i = 0
p = Progress()
for path in paths:
with open(path, ) as f:
for line in f:
i += 1
p.print_progress(i/n)
line = line.lowe... | Generator to feed sentences to the dov2vec model. |
388,098 | def pbkdf2(digestmod, password, salt, count, dk_length):
def pbkdf2_function(pw, salt, count, i):
r = u = hmac.new(pw, salt + struct.pack(">i", i), digestmod).digest()
for i in range(2, count + 1):
u = hmac.new(pw, u, digestmo... | PBKDF2, from PKCS #5 v2.0[1].
[1]: http://tools.ietf.org/html/rfc2898
For proper usage, see NIST Special Publication 800-132:
http://csrc.nist.gov/publications/PubsSPs.html
The arguments for this function are:
digestmod
a crypographic hash constructor, such as hashlib.sha256
... |
388,099 | def find_unpaired_ligand(self):
unpaired_hba, unpaired_hbd, unpaired_hal = [], [], []
involved_atoms = [hbond.a.idx for hbond in self.hbonds_pdon] + [hbond.d.idx for hbond in self.hbonds_ldon]
[[involved_atoms.append(atom.idx) for atom in sb.negative.atoms] for sb in self.saltb... | Identify unpaired functional in groups in ligands, involving H-Bond donors, acceptors, halogen bond donors. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.