Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
366,300 | def startup_config_file(self):
path = os.path.join(self.working_dir, )
if os.path.exists(path):
return path
else:
return None | Returns the startup-config file for this IOU VM.
:returns: path to config file. None if the file doesn't exist |
366,301 | def parse_clusterflow_runfiles(self, f):
data = dict()
in_comment = False
seen_pipeline = False
cf_file = False
for l in f[]:
l = l.rstrip()
if in l:
cf_file = True
if l.startswith():
... | Parse run files generated by Cluster Flow.
Currently gets pipeline IDs and associated steps. |
366,302 | def getPrice(self, searches):
totalPrice = 0
for item in self.items:
res = ShopWizard.priceItem(self.usr, item.name, searches, ShopWizard.RETLOW)
if not res:
self.failedItem = item.name
return False
... | Prices all quest items and returns result
Searches the shop wizard x times (x being number given in searches) for each
quest item and finds the lowest price for each item. Combines all item prices
and sets KitchenQuest.npSpent to the final value. Returns whether or not this
proc... |
366,303 | async def get_novel(self, term, hide_nsfw=False):
if not term.isdigit() and not term.startswith():
try:
vnid = await self.search_vndb(, term)
vnid = vnid[0][]
except VNDBOneResult as e:
vnid = e.vnid
else:
vnid ... | If term is an ID will return that specific ID. If it's a string, it will return the details of the first search result for that term.
Returned Dictionary Has the following structure:
Please note, if it says list or dict, it means the python types.
Indentation indicates level. So English is ['Tit... |
366,304 | def id(self):
return sa.Column(sa.Integer, primary_key=True, autoincrement=True) | Unique identifier of user object |
366,305 | def load_weight(weight_file: str,
weight_name: str,
weight_file_cache: Dict[str, Dict]) -> mx.nd.NDArray:
logger.info(, weight_file)
if weight_file.endswith(".npy"):
return np.load(weight_file)
elif weight_file.endswith(".npz"):
if weight_file not in weig... | Load wight fron a file or the cache if it was loaded before.
:param weight_file: Weight file.
:param weight_name: Weight name.
:param weight_file_cache: Cache of loaded files.
:return: Loaded weight. |
366,306 | def base_url(self):
if self.doc.package_url:
return self.doc.package_url
return self.doc._ref | Base URL for resolving resource URLs |
366,307 | def tag_clause_annotations(self):
if not self.is_tagged(ANALYSIS):
self.tag_analysis()
if self.__clause_segmenter is None:
self.__clause_segmenter = load_default_clausesegmenter()
return self.__clause_segmenter.tag(self) | Tag clause annotations in ``words`` layer.
Depends on morphological analysis. |
366,308 | def set_differentiable_objective(self):
if self.vector_g is not None:
return
bias_sum = 0
for i in range(0, self.nn_params.num_hidden_layers):
bias_sum = bias_sum + tf.reduce_sum(
tf.multiply(self.nn_params.biases[i], self.lambda_pos[i + 1]))
lu_sum = 0
for i in... | Function that constructs minimization objective from dual variables. |
366,309 | def draw_line(self, img, pixmapper, pt1, pt2, colour, linewidth):
pix1 = pixmapper(pt1)
pix2 = pixmapper(pt2)
(width, height) = image_shape(img)
(ret, pix1, pix2) = cv2.clipLine((0, 0, width, height), pix1, pix2)
if ret is False:
return
cv2.line(img, ... | draw a line on the image |
366,310 | def DeserializeExclusiveData(self, reader):
self.Type = TransactionType.StateTransaction
self.Descriptors = reader.ReadSerializableArray() | Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
Raises:
Exception: If the transaction type is incorrect or if there are no claims. |
366,311 | def challenge(self,
shutit,
task_desc,
expect=None,
hints=None,
congratulations=,
failed=,
expect_type=,
challenge_type=,
timeout=None,
check_exit=None,
fa... | Set the user a task to complete, success being determined by matching the output.
Either pass in regexp(s) desired from the output as a string or a list, or an md5sum of the output wanted.
@param follow_on_context On success, move to this context. A dict of information about that context.
... |
366,312 | async def FindActionTagsByPrefix(self, prefixes):
_params = dict()
msg = dict(type=,
request=,
version=3,
params=_params)
_params[] = prefixes
reply = await self.rpc(msg)
return reply | prefixes : typing.Sequence[str]
Returns -> typing.Sequence[~Entity] |
366,313 | def parse_response(fields, records):
data = [i[][] for i in records]
return [
{fields[idx]: row for idx, row in enumerate(d)}
for d in data
] | Parse an API response into usable objects.
Args:
fields (list[str]): List of strings indicating the fields that
are represented in the records, in the order presented in
the records.::
[
'number1',
'number2',
... |
366,314 | def function(self,p):
return np.around(
0.5 +
0.5*np.sin(pi*(p.duty_cycle-0.5)) +
0.5*np.sin(p.frequency*2*pi*self.pattern_y + p.phase)) | Return a square-wave grating (alternating black and white bars). |
366,315 | def is_repeated_suggestion(params, history):
if any(params == hparams and hstatus ==
for hparams, hscore, hstatus in history):
return True
else:
return False | Parameters
----------
params : dict
Trial param set
history : list of 3-tuples
History of past function evaluations. Each element in history
should be a tuple `(params, score, status)`, where `params` is a
dict mapping parameter names to values
... |
366,316 | def get(cls):
mask = sigset_t()
sigemptyset(mask)
cls._do_mask(0, None, mask)
signals = []
for sig_num in range(1, NSIG):
if sigismember(mask, sig_num):
signals.append(sig_num)
self = cls(signals)
self._is_active = True
... | Use the masking function (``sigprocmask(2)`` or ``pthread_sigmask(3)``)
to obtain the mask of blocked signals
:returns:
A fresh :class:`sigprocmask` object.
The returned object behaves as it was constructed with the list of
currently blocked signals, ``setmask=False`` and a... |
366,317 | def get_series_by_name(self, series_name):
try:
return self.api.search_series(name=series_name), None
except exceptions.TVDBRequestException as err:
LOG.exception(, series_name)
return None, _as_str(err) | Perform lookup for series
:param str series_name: series name found within filename
:returns: instance of series
:rtype: object |
366,318 | def username(self, value):
if isinstance(value, str):
self._username = value
self._handler = None | gets/sets the username |
366,319 | def read_time(self, content):
if get_class_name(content) in self.content_type_supported:
if hasattr(content, ):
return None
default_lang_conf = self.lang_settings[]
lang_conf = self.lang_settings.get(content.lang, default_lang_conf)
... | Core function used to generate the read_time for content.
Parameters:
:param content: Instance of pelican.content.Content
Returns:
None |
366,320 | def _reference_rmvs(self, removes):
print("")
self.msg.template(78)
msg_pkg = "package"
if len(removes) > 1:
msg_pkg = "packages"
print("| Total {0} {1} removed".format(len(removes), msg_pkg))
self.msg.template(78)
for pkg in removes:
... | Prints all removed packages |
366,321 | def get_delivery_stats(api_key=None, secure=None, test=None, **request_args):
return _default_delivery_stats.get(api_key=api_key, secure=secure,
test=test, **request_args) | Get delivery stats for your Postmark account.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param \*\*request_args: Keyword argu... |
366,322 | def tasks_by_tag(self, registry_tag):
if registry_tag not in self.__registry.keys():
return None
tasks = self.__registry[registry_tag]
return tasks if self.__multiple_tasks_per_tag__ is True else tasks[0] | Get tasks from registry by its tag
:param registry_tag: any hash-able object
:return: Return task (if :attr:`.WTaskRegistryStorage.__multiple_tasks_per_tag__` is not True) or \
list of tasks |
366,323 | def unchanged(self):
def _unchanged(current_dict, diffs, prefix):
keys = []
for key in current_dict.keys():
if key not in diffs:
keys.append(.format(prefix, key))
elif isinstance(current_dict[key], dict):
if... | Returns all keys that have been unchanged.
If the keys are in child dictionaries they will be represented with
. notation |
366,324 | def merge_svg_files(svg_file1, svg_file2, x_coord, y_coord, scale=1):
svg1 = _check_svg_file(svg_file1)
svg2 = _check_svg_file(svg_file2)
svg2_root = svg2.getroot()
svg1.append([svg2_root])
svg2_root.moveto(x_coord, y_coord, scale=scale)
return svg1 | Merge `svg_file2` in `svg_file1` in the given positions `x_coord`, `y_coord` and `scale`.
Parameters
----------
svg_file1: str or svgutils svg document object
Path to a '.svg' file.
svg_file2: str or svgutils svg document object
Path to a '.svg' file.
x_coord: float
Horizo... |
366,325 | def update_object_from_dictionary_representation(dictionary, instance):
for key, value in dictionary.iteritems():
if hasattr(instance, key):
setattr(instance, key, value)
return instance | Given a dictionary and an object instance, will set all object attributes equal to the dictionary's keys and
values. Assumes dictionary does not have any keys for which object does not have attributes
@type dictionary: dict
@param dictionary: Dictionary representation of the object
@par... |
366,326 | def switch_toggle(self, device):
state = self.get_state(device)
if(state == ):
return self.switch_off(device)
elif(state == ):
return self.switch_on(device)
else:
return state | Toggles the current state of the given device |
366,327 | def requires_libsodium(func):
@wraps(func)
def wrapper(*args, **kwargs):
libsodium_check()
return func(*args, **kwargs)
return wrapper | Mark a function as requiring libsodium.
If no libsodium support is detected, a `RuntimeError` is thrown. |
366,328 | def connect_head_namespaced_pod_proxy_with_path(self, name, namespace, path, **kwargs):
kwargs[] = True
if kwargs.get():
return self.connect_head_namespaced_pod_proxy_with_path_with_http_info(name, namespace, path, **kwargs)
else:
(data) = self.connect_head_n... | connect_head_namespaced_pod_proxy_with_path # noqa: E501
connect HEAD requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_head_namespaced_pod_proxy_with... |
366,329 | def _write_scalar(self, name:str, scalar_value, iteration:int)->None:
"Writes single scalar value to Tensorboard."
tag = self.metrics_root + name
self.tbwriter.add_scalar(tag=tag, scalar_value=scalar_value, global_step=iteration) | Writes single scalar value to Tensorboard. |
366,330 | def ip_between(ip, start, finish):
if is_IPv4Address(ip) and is_IPv4Address(start) and is_IPv4Address(finish):
return IPAddress(ip) in IPRange(start, finish)
else:
return False | Checks to see if IP is between start and finish |
366,331 | def _get_npcap_config(param_key):
hkey = winreg.HKEY_LOCAL_MACHINE
node = r"SYSTEM\CurrentControlSet\Services\npcap\Parameters"
try:
key = winreg.OpenKey(hkey, node)
dot11_adapters, _ = winreg.QueryValueEx(key, param_key)
winreg.CloseKey(key)
except WindowsError:
ret... | Get a Npcap parameter matching key in the registry.
List:
AdminOnly, DefaultFilterSettings, DltNull, Dot11Adapters, Dot11Support
LoopbackAdapter, LoopbackSupport, NdisImPlatformBindingOptions, VlanSupport
WinPcapCompatible |
366,332 | def sentiment(self):
_RETURN_TYPE = namedtuple(, [, ])
_polarity = 0
_subjectivity = 0
for s in self.sentences:
_polarity += s.polarity
_subjectivity += s.subjectivity
try:
polarity = _polarity / len(self.sen... | Return a tuple of form (polarity, subjectivity ) where polarity
is a float within the range [-1.0, 1.0] and subjectivity is a float
within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is
very subjective.
:rtype: named tuple of the form ``Sentiment(polarity=0.0, subjectivity=... |
366,333 | def process(inFile,force=False,newpath=None, inmemory=False, num_cores=None,
headerlets=True, align_to_gaia=True):
import drizzlepac
from drizzlepac import processInput
from stwcs import updatewcs
from drizzlepac import alignimages
if envvar_compute_name in os.enviro... | Run astrodrizzle on input file/ASN table
using default values for astrodrizzle parameters. |
366,334 | def _addSpecfile(self, specfile, path):
datatypeStatus = {: False, : False, : False, : False,
: False
}
self.info[specfile] = {: path, : datatypeStatus} | Adds a new specfile entry to MsrunContainer.info. See also
:class:`MsrunContainer.addSpecfile()`.
:param specfile: the name of an ms-run file
:param path: filedirectory used for loading and saving ``mrc`` files |
366,335 | def policyChange(self, updateParams, func):
for k,v in updateParams.items():
k = k.replace(,)
c = globals()[k](v)
try:
self.defaultPolicies[k] = getattr(c,func)(self.defaultPolicies[k])
except Exception, e:
raise | update defaultPolicy dict |
366,336 | def serialize_list(out, lst, delimiter=u, max_length=20):
have_multiline_items = any(map(is_multiline, lst))
result_will_be_too_long = sum(map(len, lst)) > max_length
if have_multiline_items or result_will_be_too_long:
padding = len(out)
add_padding = padding_adder(padding)
... | This method is used to serialize list of text
pieces like ["some=u'Another'", "blah=124"]
Depending on how many lines are in these items,
they are concatenated in row or as a column.
Concatenation result is appended to the `out` argument. |
366,337 | def toggle_state(self, state, active=TOGGLE):
if active is TOGGLE:
active = not self.is_state(state)
if active:
self.set_state(state)
else:
self.remove_state(state) | Toggle the given state for this conversation.
The state will be set ``active`` is ``True``, otherwise the state will be removed.
If ``active`` is not given, it will default to the inverse of the current state
(i.e., ``False`` if the state is currently set, ``True`` if it is not; essentially
... |
366,338 | def dragEnterEvent(self, event):
data = event.mimeData()
if data.hasFormat() and \
data.hasFormat():
tableName = self.tableTypeName()
if nstr(data.data()) == tableName:
event.acceptProposedAction()
return
elif d... | Listens for query's being dragged and dropped onto this tree.
:param event | <QDragEnterEvent> |
366,339 | def parse_requirements_list(requirements_list):
req_list = []
for requirement in requirements_list:
requirement_no_comments = requirement.split()[0].strip()
req_match = re.match(
r,
requirement_no_comments
)
if req_match:
req_li... | Take a list and return a list of dicts with {package, versions) based on the requirements specs
:param requirements_list: string
:return: string |
366,340 | def get_length_task_loss(config: LossConfig) -> :
if config.length_task_link is not None:
if config.length_task_link == C.LINK_NORMAL:
return MSELoss(config,
output_names=[C.LENRATIO_OUTPUT_NAME],
label_names=[C.LENRATIO_LABEL_NAME])
... | Returns a Loss instance.
:param config: Loss configuration.
:return: Instance implementing Loss. |
366,341 | def listen(self):
try:
self._pubsub.subscribe(self._channels)
for message in self._pubsub.listen():
if message[] == :
yield message
finally:
self._channels = [] | Listen for events as they come in |
366,342 | def random_string(length=8, charset=None):
if length < 1:
raise ValueError()
if not charset:
charset = string.letters + string.digits
return .join(random.choice(charset) for unused in xrange(length)) | Generates a string with random characters. If no charset is specified, only
letters and digits are used.
Args:
length (int) length of the returned string
charset (string) list of characters to choose from
Returns:
(str) with random characters from charset
Raises:
- |
366,343 | def upload_predictions(self, file_path, tournament=1):
self.logger.info("uploading predictions...")
auth_query =
arguments = {: os.path.basename(file_path),
: tournament}
submission_resp = self.raw_query(auth_query, arguments,
... | Upload predictions from file.
Args:
file_path (str): CSV file with predictions that will get uploaded
tournament (int): ID of the tournament (optional, defaults to 1)
Returns:
str: submission_id
Example:
>>> api = NumerAPI(secret_key="..", publi... |
366,344 | def calculate_metrics(self, model, train_loader, valid_loader, metrics_dict):
self.log_count += 1
log_valid = (
valid_loader is not None
and self.valid_every_X
and not (self.log_count % self.valid_every_X)
)
metrics_dict = {}
... | Add standard and custom metrics to metrics_dict |
366,345 | def _new_from_cdata(cls, cdata: Any) -> "Color":
return cls(cdata.r, cdata.g, cdata.b) | new in libtcod-cffi |
366,346 | def _is_bhyve_hyper():
sysctl_cmd =
vmm_enabled = False
try:
stdout = subprocess.Popen(sysctl_cmd,
shell=True,
stdout=subprocess.PIPE).communicate()[0]
vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split()[1]... | Returns a bool whether or not this node is a bhyve hypervisor |
366,347 | def _ttm_me_compute(self, V, edims, sdims, transp):
shapeY = np.copy(self.shape)
for n in np.union1d(edims, sdims):
shapeY[n] = V[n].shape[1] if transp else V[n].shape[0]
Y = zeros(shapeY)
shapeY = array(shapeY)
v = [None for _ in range(le... | Assume Y = T x_i V_i for i = 1...n can fit into memory |
366,348 | def list_eids(self):
entities = self.list()
return sorted([int(eid) for eid in entities]) | Returns a list of all known eids |
366,349 | def get_stranger_info(self, *, user_id, no_cache=False):
return super().__getattr__() \
(user_id=user_id, no_cache=no_cache) | 获取陌生人信息
------------
:param int user_id: QQ 号(不可以是登录号)
:param bool no_cache: 是否不使用缓存(使用缓存可能更新不及时,但响应更快)
:return: { "user_id": (QQ 号: int), "nickname": (昵称: str), "sex": (性别: str in ['male', 'female', 'unknown']), "age": (年龄: int) }
:rtype: dict[ str, int | str ]
------... |
366,350 | def set_file_type(self, doc, type_value):
type_dict = {
: file.FileType.SOURCE,
: file.FileType.BINARY,
: file.FileType.ARCHIVE,
: file.FileType.OTHER
}
if self.has_package(doc) and self.has_file(doc):
if not self.file_type_set... | Raises OrderError if no package or file defined.
Raises CardinalityError if more than one type set.
Raises SPDXValueError if type is unknown. |
366,351 | def mouse_event(dwFlags: int, dx: int, dy: int, dwData: int, dwExtraInfo: int) -> None:
ctypes.windll.user32.mouse_event(dwFlags, dx, dy, dwData, dwExtraInfo) | mouse_event from Win32. |
366,352 | def _sample(probability_vec):
return map(int,
numpy.random.random(probability_vec.size) <= probability_vec) | Return random binary string, with given probabilities. |
366,353 | def cprint(message, status=None):
status = {: Fore.YELLOW, : Fore.RED,
: Fore.GREEN, None: Style.BRIGHT}[status]
print(status + message + Style.RESET_ALL) | color printing based on status:
None -> BRIGHT
'ok' -> GREEN
'err' -> RED
'warn' -> YELLOW |
366,354 | def three_way_information_gain(W, X, Y, Z, base=2):
W_X_Y = [.format(w, x, y) for w, x, y in zip(W, X, Y)]
return (mutual_information(W_X_Y, Z, base=base) -
two_way_information_gain(W, X, Z, base=base) -
two_way_information_gain(W, Y, Z, base=base) -
two_way_information_... | Calculates the three-way information gain between three variables, I(W;X;Y;Z), in the given base
IG(W;X;Y;Z) indicates the information gained about variable Z by the joint variable W_X_Y, after removing
the information that W, X, and Y have about Z individually and jointly in pairs. Thus, 3-way information gai... |
366,355 | def do(self, params):
request_params = self.create_basic_params()
request_params.update(params)
response_data = self.request(request_params)
try:
format_json_data = self.format_response_data(response_data)
except Exception:
r... | 发起对 api 的请求并过滤返回结果
:param params: 交易所需的动态参数 |
366,356 | async def on_isupport_maxlist(self, value):
self._list_limits = {}
for entry in value.split():
modes, limit = entry.split()
self._list_limits[frozenset(modes)] = int(limit)
for mode in modes:
self._list_limit_groups[mode] = froz... | Limits on channel modes involving lists. |
366,357 | def bartlett(timeseries, segmentlength, noverlap=None, window=None, plan=None):
return _lal_spectrum(timeseries, segmentlength, noverlap=0,
method=, window=window, plan=plan) | Calculate an PSD of this `TimeSeries` using Bartlett's method
Parameters
----------
timeseries : `~gwpy.timeseries.TimeSeries`
input `TimeSeries` data.
segmentlength : `int`
number of samples in single average.
noverlap : `int`
number of samples to overlap between segments... |
366,358 | def fit_partial(
self,
interactions,
user_features=None,
item_features=None,
sample_weight=None,
epochs=1,
num_threads=1,
verbose=False,
):
interactions = interactions.tocoo()
if interactions.dtype != CYTHON... | Fit the model.
Fit the model. Unlike fit, repeated calls to this method will
cause training to resume from the current model state.
For details on how to use feature matrices, see the documentation
on the :class:`lightfm.LightFM` class.
Arguments
---------
int... |
366,359 | def table_create(self, remove_existing=False):
for engine in self.engines():
tables = self._get_tables(engine, create_drop=True)
logger.info(, engine)
try:
self.metadata.create_all(engine, tables=tables)
except Exception as exc:
... | Creates all tables. |
366,360 | def _to_rule(self, lark_rule):
assert isinstance(lark_rule.origin, NT)
assert all(isinstance(x, Symbol) for x in lark_rule.expansion)
return Rule(
lark_rule.origin, lark_rule.expansion,
weight=lark_rule.options.priority if lark_rule.options and lark_rule.options.... | Converts a lark rule, (lhs, rhs, callback, options), to a Rule. |
366,361 | def import_libsvm_sparse(filename):
from sklearn.datasets import load_svmlight_file
X, y = load_svmlight_file(filename)
return Dataset(X.toarray().tolist(), y.tolist()) | Imports dataset file in libsvm sparse format |
366,362 | def random_forest(self):
model = RandomForestRegressor(random_state=42)
scores = []
kfold = KFold(n_splits=self.cv, shuffle=True, random_state=42)
for i, (train, test) in enumerate(kfold.split(self.baseline_in, self.baseline_out)):
model.fit(self.baseline_in.iloc[t... | Random Forest.
This function runs random forest and stores the,
1. Model
2. Model name
3. Max score
4. Metrics |
366,363 | def emit(self, record, closed=False):
HierarchicalOutput.emit(self, record, closed) | Do nothing |
366,364 | def model_eval(sess, x, y, predictions, X_test=None, Y_test=None,
feed=None, args=None):
global _model_eval_cache
args = _ArgsWrapper(args or {})
assert args.batch_size, "Batch size was not given in args dict"
if X_test is None or Y_test is None:
raise ValueError("X_test argument and Y_te... | Compute the accuracy of a TF model on some data
:param sess: TF session to use
:param x: input placeholder
:param y: output placeholder (for labels)
:param predictions: model output predictions
:param X_test: numpy array with training inputs
:param Y_test: numpy array with training outputs
:param feed: An... |
366,365 | def run_false_positive_experiment_dim(
numActive = 128,
dim = 500,
numSamples = 1000,
numDendrites = 500,
synapses = 24,
numTrials = 10000,
... | Run an experiment to test the false positive rate based on number of synapses
per dendrite, dimension and sparsity. Uses two competing neurons, along the
P&M model.
Based on figure 5B in the original SDR paper. |
366,366 | def is_multidex(self):
dexre = re.compile("^classes(\d+)?.dex$")
return len([instance for instance in self.get_files() if dexre.search(instance)]) > 1 | Test if the APK has multiple DEX files
:return: True if multiple dex found, otherwise False |
366,367 | def scrape(self, selector, cleaner=None, processor=None):
selected = selector.xpath(self.selection) if self.xpath else selector.css(self.selection)
value = selected.re(self.re) if self.re else selected.extract(raw=self.raw, cleaner=cleaner)
return self._post_scrape(val... | Scrape the value for this field from the selector. |
366,368 | def load_gettext_translations(directory: str, domain: str) -> None:
global _translations
global _supported_locales
global _use_gettext
_translations = {}
for lang in os.listdir(directory):
if lang.startswith("."):
continue
if os.path.isfile(os.path.join(directory, ... | Loads translations from `gettext`'s locale tree
Locale tree is similar to system's ``/usr/share/locale``, like::
{directory}/{lang}/LC_MESSAGES/{domain}.mo
Three steps are required to have your app translated:
1. Generate POT translation file::
xgettext --language=Python --keyword=_:1,2... |
366,369 | def add_grad(left, right):
assert left is not None and right is not None
left_type = type(left)
right_type = type(right)
if left_type is ZeroGradient:
return right
if right_type is ZeroGradient:
return left
return grad_adders[(left_type, right_type)](left, right) | Recursively add the gradient of two objects.
Args:
left: The left value to add. Can be either an array, a number, list or
dictionary.
right: The right value. Must be of the same type (recursively) as the left.
Returns:
The sum of the two gradients, which will of the same type. |
366,370 | def refine_cell(self, tilde_obj):
try: lattice, positions, numbers = spg.refine_cell(tilde_obj[][-1], symprec=self.accuracy, angle_tolerance=self.angle_tolerance)
except Exception as ex:
self.error = % ex
else:
self.refinedcell = Atoms(numbers=numbers, cell=latt... | NB only used for perovskite_tilting app |
366,371 | def iresolve(self, *keys):
for key in keys:
missing = self.get_missing_deps(key)
if missing:
raise UnresolvableError("Missing dependencies for %s: %s" % (key, missing))
provider = self._providers.get(key)
if not provider:
... | Iterates over resolved instances for given provider keys.
:param keys: Provider keys
:type keys: tuple
:return: Iterator of resolved instances
:rtype: generator |
366,372 | def _read_from_socket(self):
if not self.use_ssl:
if not self.socket:
raise socket.error()
return self.socket.recv(MAX_FRAME_SIZE)
with self._rd_lock:
if not self.socket:
raise socket.error()
return self.socket.rea... | Read data from the socket.
:rtype: bytes |
366,373 | def run(uri,
user_entry_point,
args,
env_vars=None,
wait=True,
capture_error=False,
runner=_runner.ProcessRunnerType,
extra_opts=None):
env_vars = env_vars or {}
env_vars = env_vars.copy()
_files.download_and_extract(uri, user_entry_point, _... | Download, prepare and executes a compressed tar file from S3 or provided directory as an user
entrypoint. Runs the user entry point, passing env_vars as environment variables and args as command
arguments.
If the entry point is:
- A Python package: executes the packages as >>> env_vars python -m mo... |
366,374 | def load_json_from_string(string):
try:
json_data = json.loads(string)
except ValueError as e:
raise ValueError(.format(e))
else:
return json_data | Load schema from JSON string |
366,375 | def disconnect_pools(self):
with self._lock:
for pool in self._pools.itervalues():
pool.disconnect()
self._pools.clear() | Disconnects all connections from the internal pools. |
366,376 | def chmod(path, mode, recursive=False):
log = logging.getLogger(mod_logger + )
if not isinstance(path, basestring):
msg =
log.error(msg)
raise CommandError(msg)
if not isinstance(mode, basestring):
msg =
log.error(msg)
raise CommandError(msg)
... | Emulates bash chmod command
This method sets the file permissions to the specified mode.
:param path: (str) Full path to the file or directory
:param mode: (str) Mode to be set (e.g. 0755)
:param recursive: (bool) Set True to make a recursive call
:return: int exit code of the chmod command
:r... |
366,377 | def handle_get_passphrase(self, conn, _):
p1 = self.client.device.ui.get_passphrase()
p2 = self.client.device.ui.get_passphrase()
if p1 == p2:
result = b + util.assuan_serialize(p1.encode())
keyring.sendline(conn, result, confidential=True)
else:
... | Allow simple GPG symmetric encryption (using a passphrase). |
366,378 | def _as_array(arr, dtype=None):
if arr is None:
return None
if isinstance(arr, np.ndarray) and dtype is None:
return arr
if isinstance(arr, integer_types + (float,)):
arr = [arr]
out = np.asarray(arr)
if dtype is not None:
if out.dtype != dtype:
out =... | Convert an object to a numerical NumPy array.
Avoid a copy if possible. |
366,379 | def _parse_req(requnit, reqval):
assert reqval[0] !=
try:
retn = []
for val in reqval.split():
if requnit == :
if reqval[0].isdigit():
retn.append(int(reqval))
else:
... | Parse a non-day fixed value |
366,380 | def cp_als(X, rank, random_state=None, init=, **options):
optim_utils._check_cpd_inputs(X, rank)
U, normX = optim_utils._get_initial_ktensor(init, X, rank, random_state)
result = FitResult(U, , **options)
while result.still_optimizing:
for n in range(X.ndim):
... | Fits CP Decomposition using Alternating Least Squares (ALS).
Parameters
----------
X : (I_1, ..., I_N) array_like
A tensor with ``X.ndim >= 3``.
rank : integer
The `rank` sets the number of components to be computed.
random_state : integer, ``RandomState``, or ``None``, optional (... |
366,381 | def execute(self, **minimize_options):
minimizer_ans = self.minimizer.execute(**minimize_options)
try:
cov_matrix = minimizer_ans.covariance_matrix
except AttributeError:
cov_matrix = self.covariance_matrix(dict(zip(self.model.params, minimizer_ans._popt)))
... | Execute the fit.
:param minimize_options: keyword arguments to be passed to the specified
minimizer.
:return: FitResults instance |
366,382 | def web(port, debug=False, theme="modern", ssh_config=None):
from storm import web as _web
_web.run(port, debug, theme, ssh_config) | Starts the web UI. |
366,383 | def get_url(pif, dataset, version=1, site="https://citrination.com"):
return "{site}/datasets/{dataset}/version/{version}/pif/{uid}".format(
uid=pif.uid, version=version, dataset=dataset, site=site
) | Construct the URL of a PIF on a site
:param pif: to construct URL for
:param dataset: the pif will belong to
:param version: of the PIF (default: 1)
:param site: for the dataset (default: https://citrination.com)
:return: the URL as a string |
366,384 | def _adapt_WSDateTime(dt):
try:
ts = int(
(dt.replace(tzinfo=pytz.utc)
- datetime(1970,1,1,tzinfo=pytz.utc)
).total_seconds()
)
except (OverflowError,OSError):
if dt < datetime.now():
ts = 0
else:
ts = 2**63-1
r... | Return unix timestamp of the datetime like input.
If conversion overflows high, return sint64_max ,
if underflows, return 0 |
366,385 | def _build_tpm(tpm):
tpm = np.array(tpm)
validate.tpm(tpm)
if is_state_by_state(tpm):
tpm = convert.state_by_state2state_by_node(tpm)
else:
tpm = convert.to_multidimensional(tpm)
utils.np_immutable(tpm)
return (tpm, utils.np_h... | Validate the TPM passed by the user and convert to multidimensional
form. |
366,386 | def getWeights(self, fromName, toName):
for connection in self.connections:
if connection.fromLayer.name == fromName and \
connection.toLayer.name == toName:
return connection.weight
raise NetworkError(, (fromName, toName)) | Gets the weights of the connection between two layers (argument strings). |
366,387 | def add_voice(self, voices, item):
voice = None
if item.get() == :
voice = self.get_title_voice(item)
elif item.get() == :
voice = self.get_app_voice(item)
elif item.get() == :
voice = self.get_app_model_voice(item)
elif item.get() == ... | Adds a voice to the list |
366,388 | def print_png(o):
s = latex(o, mode=)
s = s.replace(,)
s = s.replace(, )
png = latex_to_png(s)
return png | A function to display sympy expression using inline style LaTeX in PNG. |
366,389 | def slice_orthogonal(dataset, x=None, y=None, z=None,
generate_triangles=False, contour=False):
output = vtki.MultiBlock()
if x is None:
x = dataset.center[0]
if y is None:
y = dataset.center[1]
if z is None:
... | Creates three orthogonal slices through the dataset on the three
caresian planes. Yields a MutliBlock dataset of the three slices
Parameters
----------
x : float
The X location of the YZ slice
y : float
The Y location of the XZ slice
z : float
... |
366,390 | def deregister_all(self, *events):
if events:
for event in events:
self._handler_dict[event] = []
else:
self._handler_dict = {} | Deregisters all handler functions, or those registered against the given event(s). |
366,391 | def update_vm_result(self, context, msg):
args = jsonutils.loads(msg)
agent = context.get()
port_id = args.get()
result = args.get()
LOG.debug(
, {: agent,
: port_id,
... | Update VM's result field in the DB.
The result reflects the success of failure of operation when an
agent processes the vm info. |
366,392 | def getCustomDict(cls):
if not os.path.exists(cls.getPath()):
return dict()
properties = Configuration._readConfigFile(os.path.basename(
cls.getPath()), os.path.dirname(cls.getPath()))
values = dict()
for propName in properties:
if in properties[propName]:
values[propNa... | Returns a dict of all temporary values in custom configuration file |
366,393 | def get_update(self, z=None):
if z is None:
return self.x, self.P
z = reshape_z(z, self.dim_z, self.x.ndim)
R = self.R
H = self.H
P = self.P
x = self.x
y = z - dot(H, x)
PHT = dot(P, H.T)
S = dot... | Computes the new estimate based on measurement `z` and returns it
without altering the state of the filter.
Parameters
----------
z : (dim_z, 1): array_like
measurement for this update. z can be a scalar if dim_z is 1,
otherwise it must be convertible to a colum... |
366,394 | def request(self, url,
json="",
data="",
username="",
password="",
headers=None,
timout=30):
raise NotImplementedError(
... | This is overridden on module initialization. This function will make
an HTTP POST to a given url. Either json/data will be what is posted to
the end point. he HTTP request needs to be basicAuth when username and
password are provided. a headers dict maybe provided,
whatever the values ar... |
366,395 | def interlink_translated_content(generator):
inspector = GeneratorInspector(generator)
for content in inspector.all_contents():
interlink_translations(content) | Make translations link to the native locations
for generators that may contain translated content |
366,396 | def count_subgraph_sizes(graph: BELGraph, annotation: str = ) -> Counter[int]:
return count_dict_values(group_nodes_by_annotation(graph, annotation)) | Count the number of nodes in each subgraph induced by an annotation.
:param annotation: The annotation to group by and compare. Defaults to 'Subgraph'
:return: A dictionary from {annotation value: number of nodes} |
366,397 | def start_engine(self):
if self.disable_security is True:
log.warning()
else:
log.debug()
self.__priv_key = nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)
log.debug()
self.__signing_key = nacl.signing.SigningKey.generate()
... | Start the child processes (one per device OS) |
366,398 | def trigger_show_by_id(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/triggers
api_path = "/api/v2/triggers/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/triggers#getting-triggers |
366,399 | def save_screenshot(driver, name, folder=None):
if "." not in name:
name = name + ".png"
if folder:
abs_path = os.path.abspath()
file_path = abs_path + "/%s" % folder
if not os.path.exists(file_path):
os.makedirs(file_path)
screenshot_path = "%s/%s" % (fi... | Saves a screenshot to the current directory (or to a subfolder if provided)
If the folder provided doesn't exist, it will get created.
The screenshot will be in PNG format. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.