Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
338,800 | def normalize(url):
url = url.strip()
if url == :
return
parts = split(url)
if parts.scheme:
netloc = parts.netloc
if parts.scheme in SCHEMES:
path = normalize_path(parts.path)
else:
path = parts.path
else:
netloc = parts.pat... | Normalize a URL.
>>> normalize('hTtp://ExAMPLe.COM:80')
'http://example.com/' |
338,801 | def command_shell(self):
from code import interact
interact(.format(self.shell_namespace),
local=self.shell_namespace) | Shell command::
./manage.py app:shell
Executed with `self.shell_namespace` as local variables namespace. |
338,802 | def process_dir(self, dirname):
ret = []
sub_rec = [f for f in os.listdir(dirname)]
for fname in sub_rec:
full_path = os.path.join(dirname, fname)
if os.path.isfile(full_path):
with open(full_path, ) as fh:
sub = self.process_... | Directory processing
:param dirname:
:return: |
338,803 | def filter_by(cls, **kwargs):
limit = kwargs.pop(, None)
reverse = kwargs.pop(, False)
q = cls.query.filter_by(**kwargs)
if reverse:
q = q.order_by(cls.id.desc())
if limit:
q = q.limit(limit)
return q | Same as SQLAlchemy's filter_by. Additionally this accepts
two special keyword arguments `limit` and `reverse` for limiting
the results and reversing the order respectively.
Args:
**kwargs: filter parameters
Examples:
>>> user = User.filter_by(email="new@x.com"... |
338,804 | def download_url(url, save_as, iter_size=_default_iter_size, enable_verbose=True):
msg = Messenger()
if enable_verbose:
msg.on()
else:
msg.off()
msg.show("Downloading %s from %s..." % (save_as, url))
with open(save_as, "wb") as f:
response = requests.get(url, stream=Tr... | A simple url binary content download function with progress info.
Warning: this function will silently overwrite existing file. |
338,805 | def flatwrite(cls, table,
order=None,
header=None,
output="table",
sort_keys=True,
show_none="",
sep="."
):
flat = flatten(table, sep=sep)
return Printer.write(flat,
... | writes the information given in the table
:param table: the table of values
:param order: the order of the columns
:param header: the header for the columns
:param output: the format (default is table, values are raw, csv, json, yaml, dict
:param sort_keys: if true the table is s... |
338,806 | def loadItems(self, excludeRead=False, loadLimit=20, since=None, until=None):
self.clearItems()
self.loadtLoadOk = False
self.lastLoadLength = 0
self._itemsLoadedDone(self._getContent(excludeRead, None, loadLimit, since, until)) | Load items and call itemsLoadedDone to transform data in objects |
338,807 | def create_medium(self, format_p, location, access_mode, a_device_type_type):
if not isinstance(format_p, basestring):
raise TypeError("format_p can only be an instance of type basestring")
if not isinstance(location, basestring):
raise TypeError("location can only be an... | Creates a new base medium object that will use the given storage
format and location for medium data.
The actual storage unit is not created by this method. In order to
do it, and before you are able to attach the created medium to
virtual machines, you must call one of the foll... |
338,808 | def on_aborted(self):
print()
self.is_authenticating.acquire()
self.is_authenticating.notify_all()
self.is_authenticating.release() | Device authentication aborted.
Triggered when device authentication was aborted (either with `DeviceOAuthPoller.stop()`
or via the "poll" event) |
338,809 | def get_iterator(self, data, axis=0):
if isinstance(data, NDFrame):
slicer = lambda start, edge: data._slice(
slice(start, edge), axis=axis)
length = len(data.axes[axis])
else:
slicer = lambda start, edge: data[slice(start, edge)]
... | Groupby iterator
Returns
-------
Generator yielding sequence of (name, subsetted object)
for each group |
338,810 | def new(self, path, desc=None, bare=True):
if os.path.exists(path):
raise RepoError( % path)
try:
os.mkdir(path)
if bare:
Repo.init_bare(path)
else:
Repo.init(path)
repo = Local(path)
if desc... | Create a new bare repo.Local instance.
:param path: Path to new repo.
:param desc: Repo description.
:param bare: Create as bare repo.
:returns: New repo.Local instance. |
338,811 | def notify_multiple_devices(self,
registration_ids=None,
message_body=None,
message_title=None,
message_icon=None,
sound=None,
c... | Sends push notification to multiple devices, can send to over 1000 devices
Args:
registration_ids (list, optional): FCM device registration IDs
message_body (str, optional): Message string to display in the notification tray
message_title (str, optional): Message title to di... |
338,812 | def map_over_glob(fn, path, pattern):
return [fn(x) for x in glob.glob(os.path.join(path, pattern))] | map a function over a glob pattern, relative to a directory |
338,813 | def stylize(ax, name, feature):
ax.set_ylabel(feature)
ax.set_title(name, fontsize=) | Stylization modifications to the plots |
338,814 | def _chi_squared(self, proportions, margin, observed):
n = self._element_count
chi_squared = np.zeros([n, n])
for i in xrange(1, n):
for j in xrange(0, n - 1):
denominator = 1 / margin[i] + 1 / margin[j]
chi_squared[i, j] = chi_squared[j, i] =... | return ndarray of chi-squared measures for proportions' columns.
*proportions* (ndarray): The basis of chi-squared calcualations
*margin* (ndarray): Column margin for proportions (See `def _margin`)
*observed* (ndarray): Row margin proportions (See `def _observed`) |
338,815 | def discover() -> List[Tuple[str, str]]:
if IS_ROBOT and os.path.isdir():
devices = os.listdir()
else:
devices = []
discovered_modules = []
module_port_regex = re.compile(.join(MODULE_TYPES.keys()), re.I)
for port in devices:
match = module_port_regex.search(port)
... | Scan for connected modules and instantiate handler classes |
338,816 | def read_bdf(sdmpath, scan, nskip=0, readints=0, writebdfpkl=False, bdfdir=None):
assert os.path.exists(sdmpath), % sdmpath
scans, sources = read_metadata(sdmpath, scan, bdfdir=bdfdir)
assert scans[scan][], % scan
bdffile = scans[scan][]
assert os.path.exists(bdffile), % (scan, sca... | Reads given range of integrations from sdm of given scan.
Uses BDFData object to read.
readints=0 will read all of bdf (skipping nskip).
Option to write pkl to store bdf info for faster parse next time. |
338,817 | def ip_hide_community_list_holder_community_list_extended_ip_action(self, **kwargs):
config = ET.Element("config")
ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def")
hide_community_list_holder = ET.SubElement(ip, "hide-community-list-holder", xmlns="urn:br... | Auto Generated Code |
338,818 | def check_config_mode(self, check_string=">config", pattern=""):
return super(RadETXBase, self).check_config_mode(
check_string=check_string, pattern=pattern
) | Checks if the device is in configuration mode or not.
Rad config starts with baseprompt>config. |
338,819 | def download_and_convert_video(path, default_ext=file_formats.MP4, ffmpeg_settings=None):
ffmpeg_settings = ffmpeg_settings or {}
key = "DOWNLOAD:{}".format(path)
if not config.UPDATE and FILECACHE.get(key):
return FILECACHE.get(key).decode()
config.LOGGER.info("\tDownloading {}".format(pa... | download: downloads file
Args: None
Returns: filename |
338,820 | def _load_private_key(self, private_key, passphrase=None):
key = None
last_exception = None
for pkey_class in (RSAKey, DSSKey):
try:
key = pkey_class.from_private_key(StringIO(private_key),
passphrase)
except PasswordRequiredEx... | Load a SSH private key (DSA or RSA) from a string
The private key may be encrypted. In that case, a passphrase
must be supplied. |
338,821 | def set_maxlen(self, length):
with self.lock:
self._maxlen = length
while len(self.data) > length:
self._poplast() | Sets maxlen |
338,822 | def get_mac(self):
command = const.CMD_OPTIONS_RRQ
command_string = b
response_size = 1024
cmd_response = self.__send_command(command, command_string, response_size)
if cmd_response.get():
mac = self.__data.split(b, 1)[-1].split(b)[0]
return mac.... | :return: the machine's mac address |
338,823 | def _chunk_actions(actions, chunk_size, max_chunk_bytes, serializer):
bulk_actions, bulk_data = [], []
size, action_count = 0, 0
for action, data in actions:
raw_data, raw_action = data, action
action = serializer.dumps(action)
cur_size = len(action.encode("utf-8")) + 1... | Split actions into chunks by number or size, serialize them into strings in
the process. |
338,824 | def create(cls, data, **kwargs):
with db.session.begin_nested():
model = cls.dbmodel(**kwargs)
model.data = data
obj = cls(model)
db.session.add(obj.model)
return obj | Create a new Workflow Object with given content. |
338,825 | def value(self):
if self._value:
return self._value
if self.formatter:
return self.formatter(self.raw)
return self.raw | Get the value of the match, using formatter if defined.
:return:
:rtype: |
338,826 | def DeleteArtifact(self, name):
try:
del self.artifacts[name]
except KeyError:
raise db.UnknownArtifactError(name) | Deletes an artifact with given name from the database. |
338,827 | def upgrade_websocket(self, environ, start_response):
websocket_version = environ.get(, )
if not websocket_version:
raise UpgradeRequiredError
elif websocket_version not in self.WS_VERSIONS:
raise HandshakeError(.format(websocket_version))
key = environ.... | Attempt to upgrade the socket environ['wsgi.input'] into a websocket enabled connection. |
338,828 | def print_str(self, string):
x, y = self._cursor
for char in string:
if char == :
x = 0
y += 1
continue
if char == :
x = 0
continue
x, y = self._normalizeCursor(x, y)
... | Print a string at the virtual cursor.
Handles special characters such as '\\n' and '\\r'.
Printing past the bottom of the console will scroll everything upwards
if :any:`set_mode` is set to 'scroll'.
Colors can be set with :any:`set_colors` and the virtual cursor can
be moved w... |
338,829 | def alpha(self):
return round(
float(
self.calc_alpha(
self.annualize_return,
self.benchmark_annualize_return,
self.beta,
0.05
)
),
2
) | alpha比率 与市场基准收益无关的超额收益率 |
338,830 | def date_to_string(date, seasonal=False):
seasonal_key = config.get(, , )
if seasonal:
FORMAT = seasonal_key+
else:
FORMAT =
return date.strftime(FORMAT) | Convert a date to a standard string used by Hydra. The resulting string
looks like this::
'2013-10-03 00:49:17.568-0400'
Hydra also accepts seasonal time series (yearly recurring). If the flag
``seasonal`` is set to ``True``, this function will generate a string
recognised by Hydra as seasonal... |
338,831 | def login_user(server, login, password):
login_url = urljoin(server, login_url_prefix)
session = requests.session()
result = session.get(login_url)
if not result.ok:
message = (tr(
).format(
geonode_url=server,
status_code... | Get the login session.
:param server: The Geonode server URL.
:type server: basestring
:param login: The login to use on Geonode.
:type login: basestring
:param password: The password to use on Geonode.
:type password: basestring |
338,832 | def image1wrap(d, u, v, w, npixx, npixy, candint):
data_resamp = numpyview(data_resamp_mem, , datashape(d))
image = rtlib.imgonefullxy(n.outer(u, d[]/d[][0]), n.outer(v, d[]/d[][0]), data_resamp[candint], npixx, npixy, d[], verbose=1)
return image | Parallelizable function for imaging a chunk of data for a single dm.
Assumes data is dedispersed and resampled, so this just images each integration.
Simple one-stage imaging that returns dict of params.
returns dictionary with keys of cand location and values as tuple of features |
338,833 | def load_data(self):
for embed_type in self.ids.keys():
self.load_instances(embed_type, self.ids[embed_type]) | Load data in bulk for each embed block. |
338,834 | def get_method_contents(self, method):
if self._CONDITIONAL_IF in method:
return method[self._CONDITIONAL_IF][1:]
return [method] | Returns the swagger contents of the given method. This checks to see if a conditional block
has been used inside of the method, and, if so, returns the method contents that are
inside of the conditional.
:param dict method: method dictionary
:return: list of swagger component dictionari... |
338,835 | def update(self, td):
self.sprite.last_position = self.sprite.position
self.sprite.last_velocity = self.sprite.velocity
if self.particle_group != None:
self.update_particle_group(td) | Update state of ball |
338,836 | def update_image(self, image_id, **kwargs):
data = {}
for attr, value in kwargs.items():
data[self._underscore_to_camelcase(attr)] = value
response = self._perform_request(url= + image_id,
method=,
... | Replace all properties of an image. |
338,837 | def async_stats_job_result(klass, account, job_id, **kwargs):
params = {
: job_id
}
resource = klass.RESOURCE_ASYNC.format(account_id=account.id)
response = Request(account.client, , resource, params=params).perform()
return response.body[][0] | Returns the results of the specified async job IDs |
338,838 | def parse_from_parent(
self,
parent,
state
):
element = parent.find(self.element_path)
if element is None and self.required:
state.raise_error(
MissingValue, .format(self.element_path)
)
elif e... | Parse the primitive value under the parent XML element. |
338,839 | def write_block(self, block_, body):
self.write()
with self.indent_block():
self.write()
self.write()
for checkpoint in block_.checkpoints:
self.write_tmpl(, state=checkpoint)
self.write()
self.write()
with self.indent_block(-1):
self.write(body)
... | Outputs the boilerplate necessary for code blocks like functions.
Args:
block_: The Block object representing the code block.
body: String containing Go code making up the body of the code block. |
338,840 | def _check_index_within_index_pairs(index, index_ranges):
in_range = False
for index_range in index_ranges:
if index_range[0] < index < index_range[1]:
in_range = True
return in_range | Check that the index 'index' lies within the set of indexes.
:param index: Index to determine whether it falls within the range or index pairs.
:param index_ranges: A list of index pairs, monotonically increasing pairs.
:return: True if the given index lies within a range specified by an index pair, False o... |
338,841 | def dont_watch_buffer(self, bw, *argv, **argd):
if not (argv or argd):
self.__clear_buffer_watch(bw)
else:
argv = list(argv)
argv.insert(0, bw)
if in argd:
argv.insert(0, argd.pop())
if in argd:
... | Clears a page breakpoint set by L{watch_buffer}.
@type bw: L{BufferWatch}
@param bw:
Buffer watch identifier returned by L{watch_buffer}. |
338,842 | def get_reviewable_topics(self, lang):
return [topic[]
for topic in self.user_data.language_data[lang][]
if topic[] and topic[] < 1.0] | Return the topics learned but not golden by a user in a language. |
338,843 | def parse_tag_info_chrs(self, f, convChr=True):
parsed_data_total = OrderedDict()
parsed_data_uniq = OrderedDict()
remove = ["hap", "random", "chrUn", "cmd", "EBV", "GL", "NT_"]
for l in f[]:
s = l.split("\t")
key = s[0].strip()
i... | Parse HOMER tagdirectory taginfo.txt file to extract chromosome coverage. |
338,844 | def axis_names(self) -> Tuple[str, ...]:
default = ["axis{0}".format(i) for i in range(self.ndim)]
return tuple(self._meta_data.get("axis_names", None) or default) | Names of axes (stored in meta-data). |
338,845 | def put(self, path=None, method=, **options):
return self.route(path, method, **options) | Equals :meth:`route` with a ``PUT`` method parameter. |
338,846 | def generate_list_table_result(lexicon_logger, output=None, without_header=None):
if not isinstance(output, list):
lexicon_logger.debug(
)
return None
array = [[
row.get(, ),
row.get(, ),
row.get(, ),
row.get(, ),
row.get... | Convert returned data from list actions into a nice table for command line usage |
338,847 | def block_all(self):
self.block()
for em in self._emitters.values():
em.block() | Block all emitters in this group. |
338,848 | def select(self, meta_predicate=None, region_predicate=None,
semiJoinDataset=None, semiJoinMeta=None):
semiJoinDataset_exists = False
if isinstance(meta_predicate, MetaField):
meta_condition = Some(meta_predicate.getMetaCondition())
elif meta_predicate is No... | *Wrapper of* ``SELECT``
Selection operation. Enables to filter datasets on the basis of region features or metadata attributes. In
addition it is possibile to perform a selection based on the existence of certain metadata
:attr:`~.semiJoinMeta` attributes and the matching of their values with t... |
338,849 | def makefile(self):
return self.env.get_template().render(
metadata=self.metadata,
package=self.package) | Generate the documentation Makefile.
Returns:
(str): the contents of the `Makefile`. |
338,850 | def _pull_schedule_loop(self):
try:
self.pull_schedule()
delay = 16*60
except ScheduleError, e:
self.l.exception("ScheduleError while pulling schedule. "+
"Retrying in 5m")
delay = 5*60
if not self.running:
... | Called every 16 minutes to pull a new version of the schedule |
338,851 | def add_mag_drift_unit_vectors_ecef(inst, steps=None, max_steps=40000, step_size=10.,
ref_height=120.):
zvx, zvy, zvz, bx, by, bz, mx, my, mz = calculate_mag_drift_unit_vectors_ecef(inst[],
inst[], inst[], in... | Adds unit vectors expressing the ion drift coordinate system
organized by the geomagnetic field. Unit vectors are expressed
in ECEF coordinates.
Parameters
----------
inst : pysat.Instrument
Instrument object that will get unit vectors
max_steps : int
Maximum number of steps... |
338,852 | def to_masked_array(self, copy=True):
isnull = pd.isnull(self.values)
return np.ma.MaskedArray(data=self.values, mask=isnull, copy=copy) | Convert this array into a numpy.ma.MaskedArray
Parameters
----------
copy : bool
If True (default) make a copy of the array in the result. If False,
a MaskedArray view of DataArray.values is returned.
Returns
-------
result : MaskedArray
... |
338,853 | def subsample(self, rate):
if type(rate) != int and rate < 1:
raise ValueError()
subsample_inds = np.arange(self.num_points)[::rate]
subsampled_data = self._data[:,subsample_inds]
return NormalCloud(subsampled_data, self._frame) | Returns a subsampled version of the NormalCloud.
Parameters
----------
rate : int
Only every rate-th element of the NormalCloud is returned.
Returns
-------
:obj:`RateCloud`
A subsampled point cloud with N / rate total samples.
Raises
... |
338,854 | def lift(fn=None, state_fn=None):
if fn is None:
return partial(lift, state_fn=state_fn)
@wraps(fn)
def _lift(*args, **kwargs):
def _run(state):
ans = fn(*cons(state, args), **kwargs)
s = state_fn(state) if state_fn is not None else ans
return {: an... | The lift decorator function will be used to abstract away the management
of the state object used as the intermediate representation of actions.
:param function answer: a function to provide
the result of some action given a value
:param function state: a function to provide wha... |
338,855 | def codepointsInNamelist(namFilename, unique_glyphs=False, cache=None):
key = if not unique_glyphs else
internals_dir = os.path.dirname(os.path.abspath(__file__))
target = os.path.join(internals_dir, namFilename)
result = readNamelist(target, unique_glyphs, cache)
return result[key] | Returns the set of codepoints contained in a given Namelist file.
This is a replacement CodepointsInSubset and implements the "#$ include"
header format.
Args:
namFilename: The path to the Namelist file.
unique_glyphs: Optional, whether to only include glyphs unique to subset.
Returns:
A set cont... |
338,856 | def as_raw_link(self):
if self.link_type == "raw":
return self
if self.link_type != "blob":
raise ValueError("Cannot get a download link from a tree link")
return self.__class__(
self.gitid,
"raw",
self.branch_or_commit,
... | Returns a GithubLink to a raw content. |
338,857 | def main():
template = Template()
template.add_description(
)
template.add_mapping(, {
: {: },
: {: },
: {: },
: {: },
: {: },
: {: },
: {: },
: ... | Create a ElastiCache Redis Node and EC2 Instance |
338,858 | def do_check_pep8(files, status):
for file_name in files:
args = [, , .format(file_name)]
output = run(*args)
if output:
status.append("Python PEP8/Flake8: {0}: {1}".format(file_name,
output))
return stat... | Run the python pep8 tool against the filst of supplied files.
Append any linting errors to the returned status list
Args:
files (str): list of files to run pep8 against
status (list): list of pre-receive check failures to eventually print
to the user
Returns:
... |
338,859 | def services(self):
"Returns a list of Service objects available in this folder"
return [self._get_subfolder("%s/%s/" %
(s[].rstrip().split()[-1], s[]),
self._service_type_mapping.get(s[], Service)) for s
in self._json_struct.get(, [])] | Returns a list of Service objects available in this folder |
338,860 | def exec_before_request_actions(actions, **kwargs):
groups = ("before", "before_" + flask.request.method.lower())
return execute_actions(actions, limit_groups=groups, **kwargs) | Execute actions in the "before" and "before_METHOD" groups |
338,861 | def _FormatPackedIPv6Address(self, packed_ip_address):
octet_pairs = zip(packed_ip_address[0::2], packed_ip_address[1::2])
octet_pairs = [octet1 << 8 | octet2 for octet1, octet2 in octet_pairs]
return .join([
.format(octet_pair) for octet_pair in octet_pairs]) | Formats a packed IPv6 address as a human readable string.
Args:
packed_ip_address (list[int]): packed IPv6 address.
Returns:
str: human readable IPv6 address. |
338,862 | def rename_node(self, prefix):
node_map_dict = {}
for i in range(0, len(self.nodes)):
node_map_dict[self.nodes[i]] = prefix + str(i)
for i, v in enumerate(self.nodes):
self.nodes[i] = node_map_dict[v]
for node_relations in self.... | Rename AMR graph nodes to prefix + node_index to avoid nodes with the same name in two different AMRs. |
338,863 | def setup(basepath=DEFAULT_BASEPATH):
module_version = os.environ.get(, DEFAULT_VERSION)
moduleshome = os.path.join(basepath, module_version)
if not os.path.isdir(moduleshome):
print(
)
os.environ[] =
return
os.environ[] = module_version
os.environ... | Set the environment modules used by the Environment Module system. |
338,864 | def GetNTFSFileEntryByPathSpec(self, path_spec):
location = getattr(path_spec, , None)
mft_attribute = getattr(path_spec, , None)
mft_entry = getattr(path_spec, , None)
if mft_attribute is not None and mft_entry is not None:
fsntfs_file_entry = self._fsntfs_volume.get_file_entry(mf... | Retrieves the NTFS file entry for a path specification.
Args:
path_spec (PathSpec): a path specification.
Returns:
pyfsntfs.file_entry: NTFS file entry.
Raises:
PathSpecError: if the path specification is missing location and
MFT entry. |
338,865 | def fetch(self, cache=None):
self.reset()
soup = get(self.url).soup
details = soup.find(id="detailsframe")
getdef = lambda s: [elem
for elem in details.find("dt",
text=re.compile(s)).next_siblings
if elem.name == ][0]
getde... | Query the info page to fill in the property cache.
Return a dictionary with the fetched properties and values. |
338,866 | def _monitor_callback_wrapper(callback):
def callback_handle(name, array, _):
callback(name, array)
return callback_handle | A wrapper for the user-defined handle. |
338,867 | def build_access_required(function_or_param_name):
def get_wrapper(param_name, f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
g.build = can_user_access_build(param_name)
if not utils.is_production():
time.sleep(0.5)
ret... | Decorator ensures user has access to the build ID in the request.
May be used in two ways:
@build_access_required
def my_func(build):
...
@build_access_required('custom_build_id_param')
def my_func(build):
...
Always calls the given function with the m... |
338,868 | def formfield_for_manytomany(self, db_field, request, **kwargs):
if db_field.name == :
kwargs[] = Author.objects.filter(
Q(is_staff=True) | Q(entries__isnull=False)
).distinct()
return super(EntryAdmin, self).formfield_for_manytomany(
db_... | Filter the disposable authors. |
338,869 | def exists(cls, id):
return bool(redisco.get_client().exists(cls._key[str(id)]) or
redisco.get_client().sismember(cls._key[], str(id))) | Checks if the model with id exists. |
338,870 | def _auto_init(self, *args, **kwrds):
for fld in getattr(self, , []):
val = kwrds.get(fld.name, _NO_VAL)
if val is _NO_VAL:
val = fld.get_default_val()
setattr(self, fld.name, val)
if callable(getattr(self, , None)):
self.setup(*args, **kwrds) | Our decorator will add this as __init__ to target classes. |
338,871 | def RetrieveObject(self, ui, start=-1, length=-1):
if self.file and ui:
if length == -1:
len = ui.length
else:
len = length
if start == -1:
st = 0l
else:
st = long(start)
return c... | Retrieves the contents of a document.
This function takes a UnitInfo and two optional arguments, the first
being the start address and the second is the length. These define
the amount of data to be read from the archive. |
338,872 | def unassign_activity_from_objective_bank(self, activity_id, objective_bank_id):
mgr = self._get_provider_manager(, local=True)
lookup_session = mgr.get_objective_bank_lookup_session(proxy=self._proxy)
lookup_session.get_objective_bank(objective_bank_id)
self... | Removes a ``Activity`` from a ``ObjectiveBank``.
arg: activity_id (osid.id.Id): the ``Id`` of the ``Activity``
arg: objective_bank_id (osid.id.Id): the ``Id`` of the
``ObjectiveBank``
raise: NotFound - ``activity_id`` or ``objective_bank_id`` not
found or ... |
338,873 | def initialize_path(self, path_num=None):
for c in self.consumers:
c.initialize_path(path_num)
self.state = [c.state for c in self.consumers] | make the consumer_state ready for the next MC path
:param int path_num: |
338,874 | def set_menu_separator(self, img):
if img:
self.menu_separator_tag = .format(
self._rel(img))
else:
self.menu_separator_tag = None | Sets the menu separator.
Must be called before adding entries to the menu |
338,875 | def load_indices(self, primitive):
if getattr(primitive, "indices") is None:
return None, None
_, component_type, buffer = primitive.indices.read()
return component_type, buffer | Loads the index buffer / polygon list for a primitive |
338,876 | def update(self):
observed_arr = self.noise_sampler.generate()
inferenced_arr = self.inference(observed_arr)
error_arr = self.__encoder_decoder_controller.computable_loss.compute_loss(
observed_arr,
inferenced_arr
)
delta_arr = self.__en... | Update the encoder and the decoder
to minimize the reconstruction error of the inputs.
Returns:
`np.ndarray` of the reconstruction errors. |
338,877 | def get_alert_log(self,
current=0,
minimum=0,
maximum=100,
header="",
action_key=None):
return self.get_alert(current=current,
minimum=minimum,
... | Get the alert log. |
338,878 | def _set_initial_defaults(self):
t take up values left over by the
previous one.WIDTHHEIGHTWIDTHHEIGHTWIDTHHEIGHT'))
self._transformmode = Bot.CENTER
self._canvas.settings(
fontfile="assets/notcouriersans.ttf",
fontsize=16,
align=Bot.LEFT,
... | Set the default values. Called at __init__ and at the end of run(),
do that new draw loop iterations don't take up values left over by the
previous one. |
338,879 | def begin_state(self, func=symbol.zeros, **kwargs):
assert not self._modified, \
"After applying modifier cells (e.g. DropoutCell) the base " \
"cell cannot be called directly. Call the modifier cell instead."
states = []
for info in self.state_info:
... | Initial state for this cell.
Parameters
----------
func : callable, default symbol.zeros
Function for creating initial state. Can be symbol.zeros,
symbol.uniform, symbol.Variable etc.
Use symbol.Variable if you want to directly
feed input as state... |
338,880 | def plot(self, colorbar=True, cb_orientation=,
tick_interval=[60, 60], minor_tick_interval=[20, 20],
xlabel=, ylabel=,
axes_labelsize=9, tick_labelsize=8, show=True, fname=None,
**kwargs):
if colorbar is True:
if cb_orientation == :
... | Plot the three vector components of the gravity field and the gravity
disturbance.
Usage
-----
x.plot([tick_interval, minor_tick_interval, xlabel, ylabel,
colorbar, cb_orientation, cb_label, axes_labelsize,
tick_labelsize, show, fname, **kwargs])
... |
338,881 | def setproblem(self, target, inputs=None, exclude=()):
self.target = self.attrnum(target)
exclude = map(self.attrnum, exclude)
if inputs:
self.inputs = removeall(self.target, inputs)
else:
self.inputs = [a for a in self.attrs
if... | Set (or change) the target and/or inputs.
This way, one DataSet can be used multiple ways. inputs, if specified,
is a list of attributes, or specify exclude as a list of attributes
to not use in inputs. Attributes can be -n .. n, or an attrname.
Also computes the list of possible values,... |
338,882 | def fit_one_step(
model_matrix,
response,
model,
model_coefficients_start=None,
predicted_linear_response_start=None,
l2_regularizer=None,
dispersion=None,
offset=None,
learning_rate=None,
fast_unsafe_numerics=True,
name=None):
graph_deps = [model_matrix, response, model... | Runs one step of Fisher scoring.
Args:
model_matrix: (Batch of) `float`-like, matrix-shaped `Tensor` where each row
represents a sample's features.
response: (Batch of) vector-shaped `Tensor` where each element represents a
sample's observed response (to the corresponding row of features). Must
... |
338,883 | def rename(self, old_host, new_host):
if new_host in self.hosts_:
raise ValueError("Host %s: already exists." % new_host)
for line in self.lines_:
if line.host == old_host:
line.host = new_host
if line.key.lower() == "host":
... | Renames a host configuration.
Parameters
----------
old_host : the host to rename.
new_host : the new host value |
338,884 | def get_dataframe(self, *args, **kwargs):
columns = kwargs.get()
if columns:
del kwargs[]
else:
columns = self.default_titles
return pd.DataFrame(self.get_data(*args, **kwargs), columns=columns) | Retrieve data as a Pandas dataframe.
Args:
search: (dict) Search query like {"categ_A": "val_A", "categ_B": "val_B"},
documented at https://developer.mpds.io/#Categories
phases: (list) Phase IDs, according to the MPDS distinct phases concept
fields: (dict) Da... |
338,885 | def execute(self, *args, **kwargs):
args = self.parser.parse_args(*args, **kwargs)
self.process(args) | Initializes and runs the tool.
This is shorhand to parse command line arguments, then calling:
self.setup(parsed_arguments)
self.process() |
338,886 | async def get_user_locale(self, action: str, args: Tuple[Any]) -> str:
user: types.User = types.User.get_current()
locale: Locale = user.locale
if locale:
*_, data = args
language = data[] = locale.language
return language | User locale getter
You can override the method if you want to use different way of getting user language.
:param action: event name
:param args: event arguments
:return: locale name |
338,887 | def cybox_csv_handler(self, enrichment, fact, attr_info, add_fact_kargs):
if in fact[]:
separator =
else:
separator =
value_list = map(lambda x: x.strip(), fact[].split(separator))
add_fact_kargs[] = value_list
r... | Handler for dealing with comma-separated values.
Unfortunately, CybOX et al. sometimes use comma-separated
value lists. Or rather, since Cybox 2.0.1, '##comma##'-separated lists.
At least now we can easily recognize comma-separated lists ...
until one joker starts putting the string '... |
338,888 | def _split_string_to_tokens(text):
if not text:
return []
ret = []
token_start = 0
is_alnum = [c in _ALPHANUMERIC_CHAR_SET for c in text]
for pos in xrange(1, len(text)):
if is_alnum[pos] != is_alnum[pos - 1]:
token = text[token_start:pos]
if token != u" " or token_start == 0:
... | Splits text to a list of string tokens. |
338,889 | def _parse_response(proto, response):
try:
content = proto()
content.ParseFromString(response.content)
return content
except (DecodeError, AttributeError):
LOGGER.error(, response)
raise errors.ValidatorResponseInvalid() | Parses the content from a validator response Message. |
338,890 | def hetsmooth(args):
p = OptionParser(hetsmooth.__doc__)
p.add_option("-K", default=23, type="int",
help="K-mer size [default: %default]")
p.add_option("-L", type="int",
help="Bottom threshold, first min [default: %default]")
p.add_option("-U", type="int",
... | %prog hetsmooth reads_1.fq reads_2.fq jf-23_0
Wrapper against het-smooth. Below is the command used in het-smooth manual.
$ het-smooth --kmer-len=23 --bottom-threshold=38 --top-threshold=220
--no-multibase-replacements --jellyfish-hash-file=23-mers.jf
reads_1.fq reads_2.fq |
338,891 | def assert_no_js_errors(self):
try:
browser_logs = self.driver.get_log()
except (ValueError, WebDriverException):
return
messenger_library = "//cdnjs.cloudflare.com/ajax/libs/messenger"
errors = []
for entry in browser_logs:
... | Asserts that there are no JavaScript "SEVERE"-level page errors.
Works ONLY for Chrome (non-headless) and Chrome-based browsers.
Does NOT work on Firefox, Edge, IE, and some other browsers:
* See https://github.com/SeleniumHQ/selenium/issues/1161
Based on the followin... |
338,892 | def _generate_command(self, func, name=None, **kwargs):
func_pointer = name or func.__name__
storm_config = get_storm_config()
aliases, additional_kwarg = None, None
if in storm_config:
for command, alias_list in \
six.iteritems(storm_config.get(... | Generates a command parser for given func.
:param func: func to generate related command parser
:param type: function
:param name: command name
:param type: str
:param **kwargs: keyword arguments those passed through to
:py:class:``argparse.ArgumentPar... |
338,893 | def _get_labels(self, element, locations, mode):
r
locations = self._parse_indices(locations)
element = self._parse_element(element=element)
labels = self.keys(mode=, element=element)
labels.sort()
labels = sp.array(labels)
arr = sp.vs... | r"""
This is the actual label getter method, but it should not be called
directly. Use ``labels`` instead. |
338,894 | def visit_while(self, node):
branches = 1
if node.orelse:
branches += 1
self._inc_branch(node, branches) | increments the branches counter |
338,895 | def convert(value):
s0 = "Sbp" + value if value in COLLISIONS else value
s1 = re.sub(, r, s0)
return re.sub(, r, s1).lower() + "_t" | Converts to a C language appropriate identifier format. |
338,896 | def p_attr(self,t):
t[0] = AttrX(NameX(t[1]), AsterX() if t[3]== else NameX(t[3])) | attr : NAME '.' NAME
| NAME '.' '*' |
338,897 | def _get_decimal128(data, position, dummy0, dummy1, dummy2):
end = position + 16
return Decimal128.from_bid(data[position:end]), end | Decode a BSON decimal128 to bson.decimal128.Decimal128. |
338,898 | def mousePressEvent(self, event):
self._moveItemStarted = False
rect = QtCore.QRect(0, 0, 12, self.height())
if not self._locked and rect.contains(event.pos()):
tabbar = self.parent()
panel = tabbar.parent()
index = tabbar.indexOf(self)
... | Creates the mouse event for dragging or activating this tab.
:param event | <QtCore.QMousePressEvent> |
338,899 | def receive_message(self):
while not self.recv_message_queue:
self.transport.fill_inbuffer()
message = self.recv_message_queue.pop(0)
assert message is not None
if not message.verify(self.protocol.authenticators):
self.close()
raise OmapiError("bad omapi message signature")
return message | Read the next message from the connection.
@rtype: OmapiMessage
@raises OmapiError:
@raises socket.error: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.