Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
10,700 | def _create_link(self, act_node, name, instance):
act_node._links[name] = instance
act_node._children[name] = instance
full_name = instance.v_full_name
if full_name not in self._root_instance._linked_by:
self._root_instance._linked_by[full_name] = {}
linkin... | Creates a link and checks if names are appropriate |
10,701 | def _encode_utf8(self, **kwargs):
if is_py3:
return kwargs
unencoded_pairs = kwargs
for i in unencoded_pairs.keys():
if isinstance(unencoded_pairs[i], types.UnicodeType):
unencoded_pairs[i] = unencoded_pairs... | UTF8 encodes all of the NVP values. |
10,702 | def predict_survival_function(self, X, times=None):
return np.exp(-self.predict_cumulative_hazard(X, times=times)) | Predict the survival function for individuals, given their covariates. This assumes that the individual
just entered the study (that is, we do not condition on how long they have already lived for.)
Parameters
----------
X: numpy array or DataFrame
a (n,d) covariate numpy a... |
10,703 | def track_from_file(file_object, filetype, timeout=DEFAULT_ASYNC_TIMEOUT, force_upload=False):
if not force_upload:
try:
md5 = hashlib.md5(file_object.read()).hexdigest()
return track_from_md5(md5)
except util.EchoNestAPIError:
... | Create a track object from a file-like object.
NOTE: Does not create the detailed analysis for the Track. Call
Track.get_analysis() for that.
Args:
file_object: a file-like Python object
filetype: the file type. Supported types include mp3, ogg, wav, m4a, mp4, au
force_upload: skip... |
10,704 | def guess_labels(self, doc):
if doc.nb_pages <= 0:
return set()
self.label_guesser.total_nb_documents = len(self._docs_by_id.keys())
label_names = self.label_guesser.guess(doc)
labels = set()
for label_name in label_names:
label = self.labels[labe... | return a prediction of label names |
10,705 | def do_workers(self, args):
workers = self.task_master.workers(alive=not args.all)
for k in sorted(workers.iterkeys()):
self.stdout.write(.format(k, workers[k]))
if args.details:
heartbeat = self.task_master.get_heartbeat(k)
for hk, hv in ... | list all known workers |
10,706 | def addOntology(self):
self._openRepo()
name = self._args.name
filePath = self._getFilePath(self._args.filePath,
self._args.relativePath)
if name is None:
name = getNameFromPath(filePath)
ontology = ontologies.Ontology(nam... | Adds a new Ontology to this repo. |
10,707 | def load_data_file(filename, encoding=):
data = pkgutil.get_data(PACKAGE_NAME, os.path.join(DATA_DIR, filename))
return data.decode(encoding).splitlines() | Load a data file and return it as a list of lines.
Parameters:
filename: The name of the file (no directories included).
encoding: The file encoding. Defaults to utf-8. |
10,708 | def _onMessageNotification(self, client, userdata, pahoMessage):
try:
note = Notification(pahoMessage, self._messageCodecs)
except InvalidEventException as e:
self.logger.critical(str(e))
else:
self.logger.debug("Received Notification")
if... | Internal callback for gateway notification messages, parses source device from topic string and
passes the information on to the registered device command callback |
10,709 | def open_imports(self, imported_definitions):
for imp in self.imports:
imp.load(self, imported_definitions) | Import the I{imported} WSDLs. |
10,710 | def _get_all_attributes(network):
attrs = network.attributes
for n in network.nodes:
attrs.extend(n.attributes)
for l in network.links:
attrs.extend(l.attributes)
for g in network.resourcegroups:
attrs.extend(g.attributes)
return attrs | Get all the complex mode attributes in the network so that they
can be used for mapping to resource scenarios later. |
10,711 | def list(gandi, domain, zone_id, output, format, limit):
options = {
: limit,
}
output_keys = [, , , ]
if not zone_id:
result = gandi.domain.info(domain)
zone_id = result[]
if not zone_id:
gandi.echo(t seems to be managed at Gandi.w%s %s IN %s %snamettltypevalu... | List DNS zone records for a domain. |
10,712 | def add_child_catalog(self, catalog_id, child_id):
if self._catalog_session is not None:
return self._catalog_session.add_child_catalog(catalog_id=catalog_id, child_id=child_id)
return self._hierarchy_session.add_child(id_=catalog_id, child_id=child_id) | Adds a child to a catalog.
arg: catalog_id (osid.id.Id): the ``Id`` of a catalog
arg: child_id (osid.id.Id): the ``Id`` of the new child
raise: AlreadyExists - ``catalog_id`` is already a parent of
``child_id``
raise: NotFound - ``catalog_id`` or ``child_id`` not... |
10,713 | def _update_field(self, action, field, value, max_tries, tries=0):
self.fetch()
action(self, field, value)
try:
self.save()
except requests.HTTPError as ex:
if tries < max_tries and ex.response.status_code == 409:
... | Private update_field method. Wrapped by Document.update_field.
Tracks a "tries" var to help limit recursion. |
10,714 | def convert_to_spaces(cls, ops, kwargs):
from qnet.algebra.core.hilbert_space_algebra import (
HilbertSpace, LocalSpace)
cops = [o if isinstance(o, HilbertSpace) else LocalSpace(o) for o in ops]
return cops, kwargs | For all operands that are merely of type str or int, substitute
LocalSpace objects with corresponding labels:
For a string, just itself, for an int, a string version of that int. |
10,715 | def get(self, filename):
timer = Timer()
self.check_prerequisites()
with PatchedBotoConfig():
raw_key = self.get_cache_key(filename)
logger.info("Checking if distribution archive is available in S3 bucket: %s", raw_key)
key = self.s3_buck... | Download a distribution archive from the configured Amazon S3 bucket.
:param filename: The filename of the distribution archive (a string).
:returns: The pathname of a distribution archive on the local file
system or :data:`None`.
:raises: :exc:`.CacheBackendError` when any un... |
10,716 | def generate_neuroml2_from_network(nl_model,
nml_file_name=None,
print_summary=True,
seed=1234,
format=,
base_dir=None,
... | Generate and save NeuroML2 file (in either XML or HDF5 format) from the
NeuroMLlite description |
10,717 | def write_list(path_out, image_list):
with open(path_out, ) as fout:
for i, item in enumerate(image_list):
line = % item[0]
for j in item[2:]:
line += % j
line += % item[1]
fout.write(line) | Hepler function to write image list into the file.
The format is as below,
integer_image_index \t float_label_index \t path_to_image
Note that the blank between number and tab is only used for readability.
Parameters
----------
path_out: string
image_list: list |
10,718 | def tag(self, value):
if value is None:
value = sys.argv[0]
self._tag = value[:self.MAX_TAG_LEN] | The name of the program that generated the log message.
The tag can only contain alphanumeric
characters. If the tag is longer than {MAX_TAG_LEN} characters
it will be truncated automatically. |
10,719 | def get_record(self, msg_id):
r = self._records.find_one({: msg_id})
if not r:
raise KeyError(msg_id)
return r | Get a specific Task Record, by msg_id. |
10,720 | def _non_framed_body_length(header, plaintext_length):
body_length = header.algorithm.iv_len
body_length += 8
body_length += plaintext_length
body_length += header.algorithm.auth_len
return body_length | Calculates the length of a non-framed message body, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:param int plaintext_length: Length of plaintext in bytes
:rtype: int |
10,721 | def hdrval(cls):
hdrmap = {: , : , : ,
u(): , : , : ,
u(): }
return hdrmap | Construct dictionary mapping display column title to
IterationStats entries. |
10,722 | def _merge_nested_if_from_else(self, ifStm: "IfContainer"):
self.elIfs.append((ifStm.cond, ifStm.ifTrue))
self.elIfs.extend(ifStm.elIfs)
self.ifFalse = ifStm.ifFalse | Merge nested IfContarner form else branch to this IfContainer
as elif and else branches |
10,723 | def dskstl(keywrd, dpval):
keywrd = ctypes.c_int(keywrd)
dpval = ctypes.c_double(dpval)
libspice.dskstl_c(keywrd, dpval) | Set the value of a specified DSK tolerance or margin parameter.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskstl_c.html
:param keywrd: Code specifying parameter to set.
:type keywrd: int
:param dpval: Value of parameter.
:type dpval: float
:return: |
10,724 | def remove(self, member):
if not self.client.zrem(self.name, member):
raise KeyError(member) | Remove member. |
10,725 | def header_output(self):
result = []
for key in self.keys():
result.append(key + + self.get(key).value)
return .join(result) | 只输出cookie的key-value字串.
比如: HISTORY=21341; PHPSESSION=3289012u39jsdijf28; token=233129 |
10,726 | def as_alias_handler(alias_list):
list_ = list()
for alias in alias_list:
if alias.asname:
list_.append(alias.asname)
else:
list_.append(alias.name)
return list_ | Returns a list of all the names that will be called. |
10,727 | def loads(cls, data, store_password, try_decrypt_keys=True):
try:
pos = 0
version = b4.unpack_from(data, pos)[0]; pos += 4
if version != 1:
raise UnsupportedKeystoreVersionExcepti... | See :meth:`jks.jks.KeyStore.loads`.
:param bytes data: Byte string representation of the keystore to be loaded.
:param str password: Keystore password string
:param bool try_decrypt_keys: Whether to automatically try to decrypt any encountered key entries using the same password
... |
10,728 | def _get_disk_size(self, device):
out = __salt__[]("df {0}".format(device))
if out[]:
msg = "Disk size info error: {0}".format(out[])
log.error(msg)
raise SIException(msg)
devpath, blocks, used, available, used_p, mountpoint = [elm for elm in
... | Get a size of a disk. |
10,729 | def folderitem(self, obj, item, index):
fullname = obj.getFullname()
if fullname:
item["Fullname"] = fullname
item["replace"]["Fullname"] = get_link(
obj.absolute_url(), value=fullname)
else:
item["Fullname"] = ""
default_dep... | Service triggered each time an item is iterated in folderitems.
The use of this service prevents the extra-loops in child objects.
:obj: the instance of the class to be foldered
:item: dict containing the properties of the object to be used by
the template
:index: current ind... |
10,730 | def poll_parser(poll):
if __is_deleted(poll):
return deleted_parser(poll)
if poll[] not in poll_types:
raise Exception()
return Poll(
poll[],
poll[],
__check_key(, poll),
__check_key(, poll),
poll[],
poll[],
poll[],
pol... | Parses a poll object |
10,731 | def get_css(self):
css = {}
print_css = os.path.join(self.theme_dir, , )
if not os.path.exists(print_css):
print_css = os.path.join(THEMES_DIR, , , )
if not os.path.exists(print_css):
raise IOError(u"Cannot find css/print.css in de... | Fetches and returns stylesheet file path or contents, for both
print and screen contexts, depending if we want a standalone
presentation or not. |
10,732 | def load_toml_validator_config(filename):
if not os.path.exists(filename):
LOGGER.info(
"Skipping validator config loading from non-existent config file:"
" %s", filename)
return ValidatorConfig()
LOGGER.info("Loading validator information from config: %s", filename... | Returns a ValidatorConfig created by loading a TOML file from the
filesystem. |
10,733 | def open_file(self, fname, external=False):
fname = to_text_string(fname)
ext = osp.splitext(fname)[1]
if encoding.is_text_file(fname):
self.editor.load(fname)
elif self.variableexplorer is not None and ext in IMPORT_EXT:
self.variableexplorer.impo... | Open filename with the appropriate application
Redirect to the right widget (txt -> editor, spydata -> workspace, ...)
or open file outside Spyder (if extension is not supported) |
10,734 | def round(self, value_array):
min_value = self.domain[0]
max_value = self.domain[1]
rounded_value = value_array[0]
if rounded_value < min_value:
rounded_value = min_value
elif rounded_value > max_value:
rounded_value = max_value
return ... | If value falls within bounds, just return it
otherwise return min or max, whichever is closer to the value
Assumes an 1d array with a single element as an input. |
10,735 | def get_binfo(self):
try:
return self.binfo
except AttributeError:
pass
binfo = self.new_binfo()
self.binfo = binfo
executor = self.get_executor()
ignore_set = self.ignore_set
if self.has_builder():
binfo.bact = str(... | Fetch a node's build information.
node - the node whose sources will be collected
cache - alternate node to use for the signature cache
returns - the build signature
This no longer handles the recursive descent of the
node's children's signatures. We expect that they're
... |
10,736 | def add_equad(psr, equad, flagid=None, flags=None, seed=None):
if seed is not None:
N.random.seed(seed)
equadvec = N.zeros(psr.nobs)
if flags is None:
if not N.isscalar(equad):
raise ValueError()
else:
equadvec = N.ones(psr.nobs) * equad... | Add quadrature noise of rms `equad` [s].
Optionally take a pseudorandom-number-generator seed. |
10,737 | def set_is_immediate(self, value):
if value is None:
self.__is_immediate = value
elif not isinstance(value, bool):
raise TypeError("IsImediate must be set to a bool")
else:
self.__is_immediate = value | Setter for 'is_immediate' field.
:param value - a new value of 'is_immediate' field. Must be a boolean type. |
10,738 | def _from_dict(cls, _dict):
args = {}
xtra = _dict.copy()
if in _dict:
args[] = _dict.get()
del xtra[]
if in _dict:
args[] = _dict.get()
del xtra[]
if in _dict:
args[] = _dict.get()
del xtra[]
... | Initialize a QueryResult object from a json dictionary. |
10,739 | def postinit(self, args, body):
self.args = args
self.body = body | Do some setup after initialisation.
:param args: The arguments that the function takes.
:type args: Arguments
:param body: The contents of the function body.
:type body: list(NodeNG) |
10,740 | def widgets(self):
widgets = []
for i, chart in enumerate(most_visited_pages_charts()):
widgets.append(Widget(html_id= % i,
content=json.dumps(chart),
template=,
js_code=[]))
... | Get the items. |
10,741 | def _maketicks_selected(self, plt, branches):
ticks = self.get_ticks()
distance = []
label = []
rm_elems = []
for i in range(1, len(ticks[])):
if ticks[][i] == ticks[][i - 1]:
rm_elems.append(i)
for i in range(len(ticks[])):
... | utility private method to add ticks to a band structure with selected branches |
10,742 | def find_method_params(self):
req = self.request
args = req.controller_info["method_args"]
kwargs = req.controller_info["method_kwargs"]
return args, kwargs | Return the method params
:returns: tuple (args, kwargs) that will be passed as *args, **kwargs |
10,743 | def get_active_trips_df(trip_times: DataFrame) -> DataFrame:
active_trips = (
pd.concat(
[
pd.Series(1, trip_times.start_time),
pd.Series(-1, trip_times.end_time),
]
)
.groupby(level=0, sort=True)
.sum()
.cumsum... | Count the number of trips in ``trip_times`` that are active
at any given time.
Parameters
----------
trip_times : DataFrame
Contains columns
- start_time: start time of the trip in seconds past midnight
- end_time: end time of the trip in seconds past midnight
Returns
... |
10,744 | def connect_job(job_id,
deployment_name,
token_manager=None,
app_url=defaults.APP_URL,
persist=False,
websocket=None,
data_url=None):
if data_url == None:
data_url = get_data_url_for_job(job_id,
... | connect to a running Juttle program by job_id |
10,745 | def get(self, task_id):
request = TOPRequest()
request[] = task_id
self.create(self.execute(request)[])
return self | taobao.topats.result.get 获取异步任务结果
使用指南:http://open.taobao.com/doc/detail.htm?id=30
- 1.此接口用于获取异步任务处理的结果,传入的task_id必需属于当前的appKey才可以
- 2.此接口只返回执行完成的任务结果,未执行完的返回结果里面不包含任务结果,只有任务id,执行状态
- 3.执行完成的每个task的子任务结果内容与单个任务的结果结构一致。如:taobao.topats.trades.fullinfo.get返回的子任务结果就会是Tra... |
10,746 | def get(self):
self.log.info()
ra = self.ra
dec = self.dec
if self.covered == False or self.covered == 999 or self.covered == "999":
return self.covered
self._download_sdss_image()
self.log.info()
return self.covered | *download the image* |
10,747 | def _two_to_one(datadir):
_, env_name = _split_path(datadir)
print
remove_container(.format(env_name))
remove_container(.format(env_name))
remove_container(.format(env_name))
print
if exists(path_join(datadir, )):
os.remove(path_join(datadir, ))
to_move = ([, , , ... | After this command, your environment will be converted to format version {}
and will not work with Datacats versions beyond and including 1.0.0.
This format version doesn't support multiple sites, and after this only your
"primary" site will be usable, though other sites will be maintained if you
wish to do a migration... |
10,748 | def run(self):
prev_frame_time = time.time()
while True:
self._win.switch_to()
self._win.dispatch_events()
now = time.time()
self._update(now - prev_frame_time)
prev_frame_time = now
self._draw()
... | Run the interactive window until the user quits |
10,749 | def parse(cls, line, ns={}):
parses = [p for p in cls.opts_spec.scanString(line)]
if len(parses) != 1:
raise SyntaxError("Invalid specification syntax.")
else:
e = parses[0][2]
processed = line[:e]
if (processed.strip() != line.strip()):
... | Parse an options specification, returning a dictionary with
path keys and {'plot':<options>, 'style':<options>} values. |
10,750 | def unschedule(self, campaign_id):
self.campaign_id = campaign_id
return self._mc_client._post(url=self._build_path(campaign_id, )) | Unschedule a scheduled campaign that hasn’t started sending.
:param campaign_id: The unique id for the campaign.
:type campaign_id: :py:class:`str` |
10,751 | def has_storage(func):
@wraps(func)
def wrapped(*args, **kwargs):
me = args[0]
if not hasattr(me, ) or \
not me._storage:
raise exceptions.ImproperConfigurationError(
.format(me._name.upper())
)
return func... | Ensure that self/cls contains a Storage backend. |
10,752 | def pixels_connectivity_compute(raster, i, j, idx):
nrows, ncols = raster.shape
value = raster[i][j]
for di in [-1, 0, 1]:
for dj in [-1, 0, 1]:
if 0 <= i + di < nrows and 0 <= j + dj < ncols:
if raster[i + di][j + dj] == value and not (di == dj and di == 0):
... | Compute if the two given value's pixels have connectivity
Compute if the two given value's pixels of raster have connectivity between
the [i.j]pixel and its 8-neighborhood. If they have connectivity,
then put its neighborhood to List idx and go in a recursion. If the [i,
j]pixel and its neighborh... |
10,753 | def _update_record_with_name(self, old_record, rtype, new_name, content):
new_type = rtype if rtype else old_record[]
new_ttl = self._get_lexicon_option()
if new_ttl is None and in old_record:
new_ttl = old_record[]
new_priority = self._get_lexicon_option()
... | Updates existing record and changes it's sub-domain name |
10,754 | def _determine_types(start_node, first_name, add_leaf, add_link):
if start_node.v_is_root:
where = first_name
else:
where = start_node._branch
if where in SUBTREE_MAPPING:
type_tuple = SUBTREE_MAPPING[where]
else:
type_tuple = (GR... | Determines types for generic additions |
10,755 | def p_qualifierType_1(p):
dv = None
if len(p) == 5:
dv = p[4]
p[0] = (p[2], True, p[3], dv) | qualifierType_1 : ':' dataType array
| ':' dataType array defaultValue |
10,756 | def result_key_for(self, op_name):
ops = self.resource_data.get(, {})
op = ops.get(op_name, {})
key = op.get(, None)
return key | Checks for the presence of a ``result_key``, which defines what data
should make up an instance.
Returns ``None`` if there is no ``result_key``.
:param op_name: The operation name to look for the ``result_key`` in.
:type op_name: string
:returns: The expected key to look for d... |
10,757 | def extra_prepare(self, configuration, args_dict):
harpoon = self.find_harpoon_options(configuration, args_dict)
self.register = self.setup_addon_register(harpoon)
if "images" not in self.configuration:
self.configuration["images"] = {}
self.confi... | Called before the configuration.converters are activated
Here we make sure that we have harpoon options from ``args_dict`` in
the configuration.
We then load all the harpoon modules as specified by the
``harpoon.addons`` setting.
Finally we inject into the configuration:
... |
10,758 | def connectExec(connection, protocol, commandLine):
deferred = connectSession(connection, protocol)
@deferred.addCallback
def requestSubsystem(session):
return session.requestExec(commandLine)
return deferred | Connect a Protocol to a ssh exec session |
10,759 | def dcc(self):
if self._dcc is None:
self._dcc = DCCManager(self)
return self._dcc | return the :class:`~irc3.dcc.DCCManager` |
10,760 | def corners(self):
corners = []
for ind in itertools.product(*((0,1),)*self.dim):
ind = np.array(ind)
corners.append(self.l + ind*self.r)
return np.array(corners) | Iterate the vector of all corners of the hyperrectangles
>>> Tile(3, dim=2).corners
array([[0, 0],
[0, 3],
[3, 0],
[3, 3]]) |
10,761 | def sargasso_chart (self):
config = {
: ,
: ,
: ,
:
}
return bargraph.plot(self.sargasso_data, [name for name in self.sargasso_keys if in name], config) | Make the sargasso plot |
10,762 | def airplane(self, model_mask: str = ) -> str:
model = self.random.custom_code(mask=model_mask)
plane = self.random.choice(AIRPLANES)
return .format(plane, model) | Generate a dummy airplane model.
:param model_mask: Mask of truck model. Here '@' is a
placeholder of characters and '#' is a placeholder of digits.
:return: Airplane model.
:Example:
Boeing 727. |
10,763 | def save_beat(
self,
output_file_name,
frequencys,
play_time,
sample_rate=44100,
volume=0.01
):
left_frequency, right_frequency = frequencys
left_chunk = self.__create_chunk(left_frequency, play_time, sample_rate)
right_chun... | 引数で指定した条件でビートを鳴らす
Args:
frequencys: (左の周波数(Hz), 右の周波数(Hz))のtuple
play_time: 再生時間(秒)
sample_rate: サンプルレート
volume: 音量
Returns:
void |
10,764 | def register_postloop_hook(self, func: Callable[[None], None]) -> None:
self._validate_prepostloop_callable(func)
self._postloop_hooks.append(func) | Register a function to be called at the end of the command loop. |
10,765 | def build_msg_fmtstr2(lbl, length, invert_rate, backspace):
r
with_wall = True
tzname = time.tzname[0]
if util_cplat.WIN32:
tzname = tzname.replace(, )
CLEARLINE_EL0 =
CLEARLINE_EL2 =
CLEAR_BEFORE = ... | r"""
Args:
lbl (str):
invert_rate (bool):
backspace (bool):
Returns:
str: msg_fmtstr_time
CommandLine:
python -m utool.util_progress --exec-ProgressIter.build_msg_fmtstr2
Setup:
>>> from utool.util_progress import... |
10,766 | def convert_attribute_name_to_tag(value):
if not isinstance(value, six.string_types):
raise ValueError("The attribute name must be a string.")
for entry in attribute_name_tag_table:
if value == entry[0]:
return entry[1]
raise ValueError("Unrecognized attribute name: ".form... | A utility function that converts an attribute name string into the
corresponding attribute tag.
For example: 'State' -> enums.Tags.STATE
Args:
value (string): The string name of the attribute.
Returns:
enum: The Tags enumeration value that corresponds to the attribute
name... |
10,767 | def _config_convert_to_address_helper(self) -> None:
to_address = self._socket_factory.to_address
for k, v in self.config.items():
if k == :
continue
if k.endswith():
self.config[k] = to_address(v) | converts the config from ports to zmq ip addresses
Operates on `self.config` using `self._socket_factory.to_address` |
10,768 | def _WebSafeComponent(c, alt=False):
sc = c * 100.0
d = sc % 20
if d==0: return c
l = sc - d
u = l + 20
if alt:
if (sc-l) >= (u-sc): return l/100.0
else: return u/100.0
else:
if (sc-l) >= (u-sc): return u/100.0
else: return l/100.... | Convert a color component to its web safe equivalent.
Parameters:
:c:
The component value [0...1]
:alt:
If True, return the alternative value instead of the nearest one.
Returns:
The web safe equivalent of the component value. |
10,769 | def iter_follower_file(fname):
with open(fname, ) as f:
for line in f:
parts = line.split()
if len(parts) > 3:
yield parts[1].lower(), set(int(x) for x in parts[2:]) | Iterator from a file of follower information and return a tuple of screen_name, follower ids.
File format is:
<iso timestamp> <screen_name> <follower_id1> <follower_ids2> ... |
10,770 | def generate_additional_properties(self):
self.create_variable_is_dict()
with self.l():
self.create_variable_keys()
add_prop_definition = self._definition["additionalProperties"]
if add_prop_definition:
properties_keys = list(self._definition.... | Means object with keys with values defined by definition.
.. code-block:: python
{
'properties': {
'key': {'type': 'number'},
}
'additionalProperties': {'type': 'string'},
}
Valid object is containing key call... |
10,771 | def retarget_with_change_points(song, cp_times, duration):
analysis = song.analysis
beat_length = analysis[BEAT_DUR_KEY]
beats = np.array(analysis["beats"])
cps = np.array(novelty(song, nchangepoints=4))
cp_times = np.array(cp_times)
def music_labels(t):
closes... | Create a composition of a song of a given duration that reaches
music change points at specified times. This is still under
construction. It might not work as well with more than
2 ``cp_times`` at the moment.
Here's an example of retargeting music to be 40 seconds long and
hit a change point at the... |
10,772 | def _mk_range_bucket(name, n1, n2, r1, r2):
d = {}
if r1 is not None:
d[n1] = r1
if r2 is not None:
d[n2] = r2
if not d:
raise TypeError()
d[] = name
return d | Create a named range specification for encoding.
:param name: The name of the range as it should appear in the result
:param n1: The name of the lower bound of the range specifier
:param n2: The name of the upper bound of the range specified
:param r1: The value of the lower bound (user value)
:par... |
10,773 | def get_enclosed_object(self):
if self._enclosed_object is None:
enclosed_object_id = self.get_enclosed_object_id()
package_name = enclosed_object_id.get_identifier_namespace().split()[0]
obj_name = enclosed_object_id.get_identifier_namespace().split()[1]
... | Return the enclosed object |
10,774 | def get_cp2k_structure(atoms):
from cp2k_tools.generator import dict2cp2k
},
},
},
}
) | Convert the atoms structure to a CP2K input file skeleton string |
10,775 | def create_order(self, oid, price, context=None, expires=None):
expires = absdatetime(expires, default=self.EXP_ORDER)
orders = self.request(
,
safeformat(, oid),
json.dumps({
: price,
: expires.isoformat(),
: c... | CREATES a single order for object ``oid``, with price set to ``price``
and validity until ``expires``.
:type oid: ``bigint``
:param oid:
Object ID.
:type price: ``bigint``
:param price:
Vingd amount (in cents) the user/buyer shall be charged upon
... |
10,776 | def new(project_name):
try:
locale.setlocale(locale.LC_ALL, )
except:
print("Warning: Unable to set locale. Expect encoding problems.")
config = utils.get_config()
config[][] = project_name
values = new_project_ui(config)
if type(values) is not str:
print()
... | Creates a new project |
10,777 | def put_on_top(self, request, queryset):
queryset.update(publication_date=timezone.now())
self.ping_directories(request, queryset, messages=False)
self.message_user(request, _(
)) | Put the selected entries on top at the current date. |
10,778 | def comment_request(self, request_id, body, commit=None,
filename=None, row=None):
request_url = ("{}pull-request/{}/comment"
.format(self.create_basic_url(), request_id))
payload = {: body}
if commit is not None:
payload[] = c... | Create a comment on the request.
:param request_id: the id of the request
:param body: the comment body
:param commit: which commit to comment on
:param filename: which file to comment on
:param row: which line of code to comment on
:return: |
10,779 | def calculate_month(birth_date):
year = int(birth_date.strftime())
month = int(birth_date.strftime()) + ((int(year / 100) - 14) % 5) * 20
return month | Calculates and returns a month number basing on PESEL standard. |
10,780 | def Connect(self, Username, WaitConnected=False):
if WaitConnected:
self._Connect_Event = threading.Event()
self._Connect_Stream = [None]
self._Connect_Username = Username
self._Connect_ApplicationStreams(self, self.Streams)
self._Owner.Regist... | Connects application to user.
:Parameters:
Username : str
Name of the user to connect to.
WaitConnected : bool
If True, causes the method to wait until the connection is established.
:return: If ``WaitConnected`` is True, returns the stream which can be used... |
10,781 | def _is_noop_timeperiod(self, process_name, timeperiod):
time_grouping = context.process_context[process_name].time_grouping
if time_grouping == 1:
return False
process_hierarchy = self.timetable.get_tree(process_name).process_hierarchy
timeperiod_dict = process_hie... | method verifies if the given timeperiod for given process is valid or falls in-between grouping checkpoints
:param process_name: name of the process
:param timeperiod: timeperiod to verify
:return: False, if given process has no time_grouping set or it is equal to 1.
False, if t... |
10,782 | def replace(self, new_node):
cur_node = self.cur_node
nodestack = self.nodestack
cur = nodestack.pop()
prev = nodestack[-1]
index = prev[-1] - 1
oldnode, name = prev[-2][index]
assert cur[0] is cur_node is oldnode, (cur[0], cur_node, prev[-2],
... | Replace a node after first checking integrity of node stack. |
10,783 | def handle_cmd(self, cmd):
cmd = cmd.strip()
segments = []
for s in cmd.split():
if s.startswith():
break
segments.append(s)
args = []
if not len(segments):
return
while segmen... | Handles a single server command. |
10,784 | def mapPartitions(self, f, preservesPartitioning=False):
def func(s, iterator):
return f(iterator)
return self.mapPartitionsWithIndex(func, preservesPartitioning) | Return a new RDD by applying a function to each partition of this RDD.
>>> rdd = sc.parallelize([1, 2, 3, 4], 2)
>>> def f(iterator): yield sum(iterator)
>>> rdd.mapPartitions(f).collect()
[3, 7] |
10,785 | def get_rendition_url(self, width=0, height=0):
if width == 0 and height == 0:
return self.get_master_url()
target_width, target_height = self.get_rendition_size(width, height)
key = % (target_width, target_height)
if not self.renditions:
self.renditio... | get the rendition URL for a specified size
if the renditions does not exists it will be created |
10,786 | def _read_as_table(self):
rows = list()
for row in self._rows:
rows.append([row[i].get() for i in range(self.num_of_columns)])
return rows | Read the data contained in all entries as a list of
lists containing all of the data
:return: list of dicts containing all tabular data |
10,787 | def get_cts_metadata(self, key: str, lang: str = None) -> Literal:
return self.metadata.get_single(RDF_NAMESPACES.CTS.term(key), lang) | Get easily a metadata from the CTS namespace
:param key: CTS property to retrieve
:param lang: Language in which it should be
:return: Literal value of the CTS graph property |
10,788 | def reorient_image(image, axis1, axis2=None, doreflection=False, doscale=0, txfn=None):
inpixeltype = image.pixeltype
if image.pixeltype != :
image = image.clone()
axis_was_none = False
if axis2 is None:
axis_was_none = True
axis2 = [0]*image.dimension
axis1 = np.array... | Align image along a specified axis
ANTsR function: `reorientImage`
Arguments
---------
image : ANTsImage
image to reorient
axis1 : list/tuple of integers
vector of size dim, might need to play w/axis sign
axis2 : list/tuple of integers
vector of size dim f... |
10,789 | def probes_used_extract_scores(full_scores, same_probes):
if full_scores.shape[1] != same_probes.shape[0]: raise "Size mismatch"
import numpy as np
model_scores = np.ndarray((full_scores.shape[0],np.sum(same_probes)), )
c=0
for i in range(0,full_scores.shape[1]):
if same_probes[i]:
for j in range... | Extracts a matrix of scores for a model, given a probes_used row vector of boolean |
10,790 | def _call(self, x, out):
if self.domain.is_real:
out.real = self.scalar.real * x
out.imag = self.scalar.imag * x
else:
out.lincomb(self.scalar, x) | Return ``self(x)``. |
10,791 | def acknowledge(self, request, *args, **kwargs):
alert = self.get_object()
if not alert.acknowledged:
alert.acknowledge()
return response.Response(status=status.HTTP_200_OK)
else:
return response.Response({: _()}, status=status.HTTP_409_CONFLICT) | To acknowledge alert - run **POST** against */api/alerts/<alert_uuid>/acknowledge/*. No payload is required.
All users that can see alerts can also acknowledge it. If alert is already acknowledged endpoint
will return error with code 409(conflict). |
10,792 | def play_song(self, song):
if song is not None and song == self.current_song:
logger.warning()
else:
self._playlist.current_song = song | 播放指定歌曲
如果目标歌曲与当前歌曲不相同,则修改播放列表当前歌曲,
播放列表会发出 song_changed 信号,player 监听到信号后调用 play 方法,
到那时才会真正的播放新的歌曲。如果和当前播放歌曲相同,则忽略。
.. note::
调用方不应该直接调用 playlist.current_song = song 来切换歌曲 |
10,793 | def set_branding(self, asset_ids):
if asset_ids is None:
raise NullArgument()
if self.get_branding_metadata().is_read_only():
raise NoAccess()
if not isinstance(asset_ids, list):
raise InvalidArgument()
if not self.my_osid_object_form._is_vali... | Sets the branding.
arg: asset_ids (osid.id.Id[]): the new assets
raise: InvalidArgument - ``asset_ids`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``asset_ids`` is ``null``
*compliance: mandatory -- This method must be implemen... |
10,794 | def set_connection(host=None, database=None, user=None, password=None):
c.CONNECTION[] = host
c.CONNECTION[] = database
c.CONNECTION[] = user
c.CONNECTION[] = password | Set connection parameters. Call set_connection with no arguments to clear. |
10,795 | def _von_mises_cdf_series(x, concentration, num_terms, dtype):
num_terms = tf.cast(num_terms, dtype=dtype)
def loop_body(n, rn, drn_dconcentration, vn, dvn_dconcentration):
denominator = 2. * n / concentration + rn
ddenominator_dk = -2. * n / concentration ** 2 + drn_dconcentration
rn = ... | Computes the von Mises CDF and its derivative via series expansion. |
10,796 | def get_assessment_offered_mdata():
return {
: {
: {
: ,
: str(DEFAULT_LANGUAGE_TYPE),
: str(DEFAULT_SCRIPT_TYPE),
: str(DEFAULT_FORMAT_TYPE),
},
: {
: ,
: str(DEFAULT_LAN... | Return default mdata map for AssessmentOffered |
10,797 | def add_arguments(cls, parser, sys_arg_list=None):
parser.add_argument(, , dest=, required=True,
help="config file for routing groups "
"(only in configfile mode)")
return ["file"] | Arguments for the configfile mode. |
10,798 | def extract_words(string):
string
return re.findall(r % (A, A, A), string, flags=FLAGS) | Extract all alphabetic syllabified forms from 'string'. |
10,799 | def _underscore_to_camelcase(value):
def camelcase():
yield str.lower
while True:
yield str.capitalize
c = camelcase()
return "".join(next(c)(x) if x else for x in value.split("_")) | Convert Python snake case back to mixed case. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.