Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
356,100 | def remove_neighbours(self):
ipix = self._best_res_pixels()
hp = HEALPix(nside=(1 << self.max_order), order=)
extend_ipix = AbstractMOC._neighbour_pixels(hp, ipix)
neigh_ipix = np.setxor1d(extend_ipix, ipix)
border_ipix = AbstractMO... | Removes from the MOC instance the HEALPix cells located at its border.
The depth of the HEALPix cells removed is equal to the maximum depth of the MOC instance.
Returns
-------
moc : `~mocpy.moc.MOC`
self minus its HEALPix cells located at its border. |
356,101 | def sync_deps(self, path):
if not exists(path):
os.mkdir(path, 0o755)
self._load_old_vals(path)
for sym in self.unique_defined_syms:
val = sym.str_value
if sym._write_to_con... | Creates or updates a directory structure that can be used to avoid
doing a full rebuild whenever the configuration is changed, mirroring
include/config/ in the kernel.
This function is intended to be called during each build, before
compiling source files that depend on configuration sy... |
356,102 | def get_session(session, baseurl, config):
if environ.get("HTTP_PROXY"):
myProxy = environ.get("HTTP_PROXY")
proxy = Proxy({
: ProxyType.MANUAL,
: myProxy,
: myProxy,
: myProxy,
:
})
else:
proxy = None
... | Try to get a valid session for this baseurl, using login found in config.
This function invoques Firefox if necessary |
356,103 | def exact(self, *args, **kwargs):
compare = Exact(*args, **kwargs)
self.add(compare)
return self | Compare attributes of pairs exactly.
Shortcut of :class:`recordlinkage.compare.Exact`::
from recordlinkage.compare import Exact
indexer = recordlinkage.Compare()
indexer.add(Exact()) |
356,104 | def switch_to_plugin(self):
if (self.main.last_plugin is not None and
self.main.last_plugin.ismaximized and
self.main.last_plugin is not self):
self.main.maximize_dockwidget()
if self.get_option():
if not self.to... | Switch to plugin. |
356,105 | def propagate(cls, date):
date = date.change_scale()
t_tdb = date.julian_century
def cos(angle):
return np.cos(np.radians(angle))
def sin(angle):
return np.sin(np.radians(angle))
lambda_el = 218.32 + 481267.8813 * t_t... | Compute the Moon position at a given date
Args:
date (~beyond.utils.date.Date)
Return:
~beyond.orbits.orbit.Orbit: Position of the Moon in EME2000 frame
Example:
.. code-block:: python
from beyond.utils.date import Date
MoonP... |
356,106 | def _get_coordinates_for_dataset_key(self, dsid):
ds_info = self.ids[dsid]
cids = []
for cinfo in ds_info.get(, []):
if not isinstance(cinfo, dict):
cinfo = {: cinfo}
cinfo[] = ds_info[]
if in ds_info:
cinfo[] = ds_i... | Get the coordinate dataset keys for *dsid*. |
356,107 | def play(self):
colors = [lambda: self.white_move(), lambda: self.black_move()]
colors = itertools.cycle(colors)
while True:
color_fn = next(colors)
if game_state.no_moves(self.position):
if self.position.get_king(color.white).in_check(self.posit... | Starts game and returns one of 3 results .
Iterates between methods ``white_move()`` and
``black_move()`` until game ends. Each
method calls the respective player's ``generate_move()``
method.
:rtype: int |
356,108 | def getFlag(self, flagName):
assert (len(flagName) > 0)
return Flag(os.path.join(self._variablesDirPath, flagName)) | Creates a flag having path <variables dir path><os.sep><flagName> |
356,109 | def convert2dbus(value, signature):
if len(signature) == 2 and signature.startswith():
return dbus.Array(value, signature=signature[-1])
dbus_string_type = dbus.String if PY3 else dbus.UTF8String
type_map = {
: dbus.Boolean, : dbus.Byte, : dbus.Int16,
: dbus.Int32, : dbus.Int64,... | Converts `value` type from python to dbus according signature.
:param value: value to convert to dbus object
:param str signature: dbus type signature.
:returns: value in dbus type. |
356,110 | def _compat_name(new_name, compat_name=None):
if compat_name is not None:
assert "slave" in compat_name.lower()
assert new_name == "" or "worker" in new_name.lower(), new_name
return compat_name
compat_replacements = {
"worker": "slave",
"Worker": "Slave",
}
... | Returns old API ("slave") name for new name ("worker").
>>> assert _compat_name("Worker") == "Slave"
>>> assert _compat_name("SomeWorkerStuff") == "SomeSlaveStuff"
>>> assert _compat_name("SomeWorker", compat_name="SomeBuildSlave") == \
"SomeBuildSlave"
If `compat_name` is not specified old na... |
356,111 | def update(self, task_name, task_json):
r = self.gbdx_connection.put(self._base_url + + task_name, json=task_json)
raise_for_status(r)
return r.json() | Updates a GBDX task.
Args:
task_name (str): Task name.
task_json (dict): Dictionary representing updated task definition.
Returns:
Dictionary representing the updated task definition. |
356,112 | def build(self, builder):
builder.start("mdsol:ReviewGroup", {})
builder.data(self.name)
builder.end("mdsol:ReviewGroup") | Build XML by appending to builder |
356,113 | def _decode_step(self,
prev_word: mx.nd.NDArray,
step: int,
source_length: int,
states: List[ModelState],
models_output_layer_w: List[mx.nd.NDArray],
models_output_layer_b: List[mx.nd.NDArray]) ... | Returns decoder predictions (combined from all models), attention scores, and updated states.
:param prev_word: Previous words of hypotheses. Shape: (batch_size * beam_size,).
:param step: Beam search iteration.
:param source_length: Length of the input sequence.
:param states: List of ... |
356,114 | def spendables_for_address(self, address):
URL = self.api_domain + "/unspent?active=%s" % address
r = json.loads(urlopen(URL).read().decode("utf8"))
spendables = []
for u in r["unspent_outputs"]:
coin_value = u["value"]
script = h2b(u["script"])
... | Return a list of Spendable objects for the
given bitcoin address. |
356,115 | def full_newton(s, nodes1, t, nodes2):
r
if s < ZERO_THRESHOLD:
reversed1 = np.asfortranarray(nodes1[:, ::-1])
if t < ZERO_THRESHOLD:
reversed2 = np.asfortranarray(nodes2[:, ::-1])
refined_s, refined_t = full_newton_nonzero(
1.0 - s, reversed1, 1.0 - t, re... | r"""Perform a Newton iteration until convergence to a solution.
This assumes :math:`s` and :math:`t` are sufficiently close to an
intersection. It **does not** govern the maximum distance away
that the solution can lie, though the subdivided intervals that contain
:math:`s` and :math:`t` could be used.... |
356,116 | def _count_async(self, limit=None, **q_options):
if in q_options:
raise NotImplementedError(
)
if in q_options:
raise TypeError(
)
elif limit is None:
limit = _MAX_LIMIT
if self._needs_multi_query():
... | Internal version of count_async(). |
356,117 | def expose(url="/", methods=("GET",)):
def wrap(f):
if not hasattr(f, "_urls"):
f._urls = []
f._urls.append((url, methods))
return f
return wrap | Use this decorator to expose API endpoints on your API classes.
:param url:
Relative URL for the endpoint
:param methods:
Allowed HTTP methods. By default only GET is allowed. |
356,118 | def create_audit_student_enrollment(self, course_id):
audit_enrollment = {
"mode": "audit",
"course_details": {"course_id": course_id}
}
resp = self.requester.post(
urljoin(self.base_url, self.enrollment_url),
json=audit_enrollmen... | Creates an audit enrollment for the user in a given course
Args:
course_id (str): an edX course id
Returns:
Enrollment: object representing the student enrollment in the provided course |
356,119 | def _replace_fields(self, json_dict):
for key in self._json_dict.keys():
if not key.startswith("_"):
delattr(self, key)
self._json_dict = json_dict
self._set_fields(json_dict) | Delete this object's attributes, and replace with
those in json_dict. |
356,120 | def _assignSignature(self, chip):
sci_chip = self._image[self.scienceExt,chip]
ny=sci_chip._naxis1
nx=sci_chip._naxis2
detnum = sci_chip.detnum
instr=self._instrument
sig=(instr+self._detector,(nx,ny),int(detnum))
sci_chip.signature=sig | Assign a unique signature for the image based
on the instrument, detector, chip, and size
this will be used to uniquely identify the appropriate
static mask for the image.
This also records the filename for the static mask to the outputNames dictionary. |
356,121 | def distance(self, other=None):
t = 0
if other is None:
other = self.__class__()
for axisName in set(self.keys()) | set(other.keys()):
t += (other.get(axisName,0)-self.get(axisName,0))**2
return math.sqrt(t) | Return the geometric distance to the other location.
If no object is provided, this will calculate the distance to the origin.
::
>>> l = Location(pop=100)
>>> m = Location(pop=200)
>>> l.distance(m)
100.0
>>> l = Location()
>>> m... |
356,122 | def reset_interface(self):
self.data[] = []
if self.typeof != :
self.data[] = []
self.update()
self.delete_invalid_route() | Reset the interface by removing all assigned addresses and VLANs.
This will not delete the interface itself, only the sub interfaces that
may have addresses assigned. This will not affect inline or capture
interfaces.
Note that if this interface is used as a primary control, auth request... |
356,123 | def sum_combined_sp_values(self, other):
if self.values is None:
ret = IdValues()
else:
ret = IdValues({: sum(int(x) for x in
{k: int(v) * int(other.values[k]) for k, v
in self.values.items()}.val... | sum(sp_values * sp_values) |
356,124 | def _create_initial_state(self, initial_ids, initial_cache):
cur_index = tf.constant(0)
alive_seq = _expand_to_beam_size(initial_ids, self.beam_size)
alive_seq = tf.expand_dims(alive_seq, axis=2)
initial_log_probs = tf.constant(
[[0.] + [-float("inf")] * (self.beam_siz... | Return initial state dictionary and its shape invariants.
Args:
initial_ids: initial ids to pass into the symbols_to_logits_fn.
int tensor with shape [batch_size, 1]
initial_cache: dictionary storing values to be passed into the
symbols_to_logits_fn.
Returns:
state and shap... |
356,125 | def handle(self, path, method=):
depr("This method will change semantics in 0.10. Try to avoid it.")
if isinstance(path, dict):
return self._handle(path)
return self._handle({: path, : method.upper()}) | (deprecated) Execute the first matching route callback and return
the result. :exc:`HTTPResponse` exceptions are catched and returned.
If :attr:`Bottle.catchall` is true, other exceptions are catched as
well and returned as :exc:`HTTPError` instances (500). |
356,126 | def _args_checks_gen(self, decorated_function, function_spec, arg_specs):
inspected_args = function_spec.args
args_check = {}
for i in range(len(inspected_args)):
arg_name = inspected_args[i]
if arg_name in arg_specs.keys():
args_check[arg_name] = self.check(arg_specs[arg_name], arg_name, decorated... | Generate checks for positional argument testing
:param decorated_function: function decorator
:param function_spec: function inspect information
:param arg_specs: argument specification (same as arg_specs in :meth:`.Verifier.decorate`)
:return: internal structure, that is used by :meth:`.Verifier._args_checks... |
356,127 | def get_cds_time(days, msecs):
return datetime(1958, 1, 1) + timedelta(days=float(days),
milliseconds=float(msecs)) | Get the datetime object of the time since epoch given in days and
milliseconds of day |
356,128 | def get_fields(catalog, filter_in=None, filter_out=None, meta_field=None,
only_time_series=False, distribution_identifier=None):
filter_in = filter_in or {}
filter_out = filter_out or {}
catalog = read_catalog_obj(catalog)
if distribution_identifier:
if "distribution" ... | Devuelve lista de campos del catálogo o de uno de sus metadatos.
Args:
catalog (dict, str or DataJson): Representación externa/interna de un
catálogo. Una representación _externa_ es un path local o una
URL remota a un archivo con la metadata de un catálogo, en
formato J... |
356,129 | def copy(self, pk=None, new_name=None, **kwargs):
orig = self.read(pk, fail_on_no_results=True, fail_on_multiple_results=True)
orig = orig[][0]
self._pop_none(kwargs)
newresource = copy(orig)
newresource.pop()
basename = newresource[].split(, 1)[0].stri... | Copy an object.
Only the ID is used for the lookup. All provided fields are used to override the old data from the
copied resource.
=====API DOCS=====
Copy an object.
:param pk: Primary key of the resource object to be copied
:param new_name: The new name to give the r... |
356,130 | def _ser_script_to_sh_address(script_bytes, witness=False, cashaddr=True):
if witness:
script_hash = utils.sha256(script_bytes)
else:
script_hash = utils.hash160(script_bytes)
return _hash_to_sh_address(
script_hash=script_hash,
witness=witness,
cashaddr=cashaddr... | makes an p2sh address from a serialized script |
356,131 | def make_case2(context):
query = context.session.query(models.IPAddress)
period_start, period_end = billing.calc_periods()
ip_list = billing.build_full_day_ips(query, period_start, period_end)
import random
ind = random.randint(0, len(ip_list) - 1)
address = ip_list[ind]
address.allocat... | This is a helper method for testing.
When run with the current context, it will create a case 2 entries
in the database. See top of file for what case 2 is. |
356,132 | def is_prefix(pre_path, path):
pre_path = pre_path.strip()
path = path.strip()
return not pre_path or path.startswith(pre_path + ) | Return True if pre_path is a path-prefix of path. |
356,133 | def findInvariant(self, symclasses):
get = primes.primes.get
disambiguate = self.disambiguate
breakRankTies = self.breakRankTies
while 1:
newSyms = map(get, symclasses)
newSyms = disambiguate(newSyms)
breakRankTies(symclasses, newSyms)
... | (symclasses) -> converge the disambiguity function
until we have an invariant |
356,134 | def _get_cpu_info_from_cat_var_run_dmesg_boot():
if not DataSource.has_var_run_dmesg_boot():
return {}
returncode, output = DataSource.cat_var_run_dmesg_boot()
if output == None or returncode != 0:
return {}
return _parse_dmesg_output(output) | Returns the CPU info gathered from /var/run/dmesg.boot.
Returns {} if dmesg is not found or does not have the desired info. |
356,135 | def explode(self):
for tmp_sg in list(self.items.values()):
tmp_sg.already_exploded = False
for servicegroup in list(self.items.values()):
if servicegroup.already_exploded:
continue
for tmp_sg in l... | Get services and put them in members container
:return: None |
356,136 | def _make_valid_if_necessary(shape):
if shape.type in (, ) and not shape.is_valid:
shape = shape.buffer(0)
if not shape.is_valid:
return None
return shape | attempt to correct invalid shapes if necessary
After simplification, even when preserving topology, invalid
shapes can be returned. This appears to only occur with polygon
types. As an optimization, we only check if the polygon types are
valid. |
356,137 | def list_courses(self):
course = CourseraOnDemand(session=self._session,
course_id=None,
course_name=None)
return course.list_courses() | List enrolled courses.
@return: List of enrolled courses.
@rtype: [str] |
356,138 | def process_file(self):
try:
self.filename = self.generate_graphie_file()
config.LOGGER.info("\t--- Generated graphie {}".format(self.filename))
return self.filename
except (HTTPError, ConnectionError, InvalidURL, UnicodeDecodeError, UnicodeError, In... | download: download a web+graphie file
Args: None
Returns: None |
356,139 | def save_wrapper(cls, save, new_class):
def _wrapped(self, *args, **kwargs):
if not self.installed:
raise AssertionError( %
self.verbose_name)
logger.info("Saving %s module" % self.verbose_name)
pre_save.send(send... | Wrap the save method to call pre and post enable signals and update
module status |
356,140 | def elements(self):
ABCABCAABBCCs count has been set to zero or is a negative number,
elements() will ignore it.
'
try:
iteritems = self.iteritems()
except AttributeError:
iteritems = iter(self)
for elem, count in iteritems:
for... | Iterator over elements repeating each as many times as its count.
>>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C']
If an element's count has been set to zero or is a negative number,
elements() will ignore it. |
356,141 | def remove_outlier(self, data, sd_val):
data = data.dropna()
data = data[(np.abs(stats.zscore(data)) < float(sd_val)).all(axis=1)]
return data | Remove outliers from dataframe.
Note
----
1. This function excludes all lines with NA in all columns.
Parameters
----------
data : pd.DataFrame()
Dataframe to remove outliers from.
sd_val : int
Standard Deviation Value (specifices how... |
356,142 | def get_ip4():
addresses = []
shell_cmd = "ifconfig | awk "
proc = subprocess.Popen([shell_cmd], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
ip_addresses = out.split()
for addr in ip_addresses:
if re.match(r, addr):
addresses.append(addr)
re... | return all ip v4 address of current computer
:return: |
356,143 | def intervals_to_bed(intervals):
import re
strand = re.compile()
no_strand = re.compile()
bed_lines = []
s = False
for i in intervals:
m = strand.match(i)
if m:
bed_lines.append(.join([m.group(x) for x in range(1, 5)]))
else:
m = no_strand.mat... | Convert list of intervals of format chr1:100-200 or chr1:100-200:+ to
BedTool object.
Parameters
----------
intervals : array-like
List of intervals.
Returns
-------
bt : pybedtools.BedTool
BedTool with one line for each interval. |
356,144 | def get(self, document=None, plugin=None):
if plugin is not None:
if document is None:
documents_list = {}
for key in self.documents.keys():
if self.documents[key].plugin == plugin:
documents_list[key] = self.docume... | Get one or more documents.
:param document: Name of the document
:type document: str
:param plugin: Plugin object, under which the document was registered
:type plugin: GwBasePattern |
356,145 | def quantile_1D(data, weights, quantile):
if not isinstance(data, np.matrix):
data = np.asarray(data)
if not isinstance(weights, np.matrix):
weights = np.asarray(weights)
nd = data.ndim
if nd != 1:
raise TypeError("data must be a one dimensional array")
ndw = weight... | Compute the weighted quantile of a 1D numpy array.
Parameters
----------
data : ndarray
Input array (one dimension).
weights : ndarray
Array with the weights of the same size of `data`.
quantile : float
Quantile to compute. It must have a value between 0 and 1.
Returns
... |
356,146 | def decompress_array(str_list):
global _compress_thread_pool
if not str_list:
return str_list
if not ENABLE_PARALLEL or len(str_list) <= LZ4_N_PARALLEL:
return [lz4_decompress(chunk) for chunk in str_list]
if _compress_thread_pool is None:
_compress_thread_pool = ThreadPo... | Decompress a list of strings |
356,147 | def lowest_common_hypernyms(self,target_synset):
self_hypernyms = self._recursive_hypernyms(set())
other_hypernyms = target_synset._recursive_hypernyms(set())
common_hypernyms = self_hypernyms.intersection(other_hypernyms)
annot_common_hypernyms = [(hypernym, hypernym.... | Returns the common hypernyms of the synset and the target synset, which are furthest from the closest roots.
Parameters
----------
target_synset : Synset
Synset with which the common hypernyms are sought.
Returns
-------
list of Synsets
... |
356,148 | def cookie(self, k, v, expires=None, domain=None, path=, secure=False):
ls = [.format(k, v)]
if expires is not None:
dt = format_date_time(mktime(expires.timetuple()))
ls.append(.format(dt))
if domain is not None:
ls.append(.format(domain))
... | Sets cookie value.
:param k: Name for cookie value
:param v: Cookie value
:param expires: Cookie expiration date
:param domain: Cookie domain
:param path: Cookie path
:param secure: Flag for `https only`
:type k: str
:type v: str
:type expires: da... |
356,149 | def get(self, patch, default=None):
try:
return self.__getitem__(patch)
except KeyError as error:
return default | Returns given patch value.
:param patch: Patch name.
:type patch: unicode
:param default: Default value if patch is not found.
:type default: object
:return: Action.
:rtype: QAction |
356,150 | def _basic_login(self):
_LOGGER.debug("No/Expired/Invalid access_token, re-authenticating...")
self.access_token = self.access_token_expires = None
if self.refresh_token:
_LOGGER.debug("Trying refresh_token...")
credentials = {: "refresh_token",
... | Obtain a new access token from the vendor.
First, try using the refresh_token, if one is available, otherwise
authenticate using the user credentials. |
356,151 | def transform_33_32(inst, new_inst, i, n, offset,
instructions, new_asm):
add_size = xdis.op_size(new_inst.opcode, opcode_33)
if inst.opname in (,):
prev_inst = instructions[i-1]
assert prev_inst.opname ==
assert isinstance(prev_inst.arg, int)
... | MAKE_FUNCTION, and MAKE_CLOSURE have an additional LOAD_CONST of a name
that are not in Python 3.2. Remove these. |
356,152 | def has_frames(self, destination):
return (destination in self.queue_metadata) and bool(self.queue_metadata[destination][]) | Whether specified queue has any frames.
@param destination: The queue name (destinationination).
@type destination: C{str}
@return: Whether there are any frames in the specified queue.
@rtype: C{bool} |
356,153 | def GetSecurityToken(self, username, password):
url =
body = % (username, password, self.share_point_site)
headers = {: }
response = requests.post(url, body, headers=headers)
xmldoc = etree.fromstring(response.content)
token = xmldoc.find(
... | Grabs a security Token to authenticate to Office 365 services |
356,154 | def get(self, name):
return self.prepare_model(self.client.api.inspect_image(name)) | Gets an image.
Args:
name (str): The name of the image.
Returns:
(:py:class:`Image`): The image.
Raises:
:py:class:`docker.errors.ImageNotFound`
If the image does not exist.
:py:class:`docker.errors.APIError`
If t... |
356,155 | def handle_fobj(backend, f, **kwargs):
if not is_binary(f):
raise AssertionError()
if callable(getattr(backend, , None)):
LOGGER.debug("using handle_fobj")
return backend.handle_fobj(f)
elif callable(getattr(backend, , None)):
LOGGER.debug("u... | Handle a file-like object.
Called by `get()` when provided a file-like. This function will prefer the
backend's `handle_fobj()` if one is provided. Otherwise, it will write the
data to a temporary file and call `handle_path()`. |
356,156 | def dispatch(self, request, *args, **kwargs):
self.request = DownstreamRequest(request)
self.args = args
self.kwargs = kwargs
self._verify_config()
self.middleware = MiddlewareSet(self.proxy_middleware)
return self.proxy() | Dispatch all HTTP methods to the proxy. |
356,157 | def _update_meta(self,directory,filename):
if not self._connectToFlickr():
print("%s - Couldnphotoid.titletrying to open [%s].description%s - updating metadata (title=%s) (description=%s)statokstat']);
return False
else:
return True | Opens up filename.title and
filename.description, updates on flickr |
356,158 | def get_build_template():
base = get_installdir()
name = "%s/main/templates/build/singularity-cloudbuild.json" % base
if os.path.exists(name):
bot.debug("Found template %s" %name)
return read_json(name)
bot.warning("Template %s not found." % name) | get default build template. |
356,159 | def build_preauth_str(preauth_key, account_name, timestamp, expires,
admin=False):
if admin:
s = .format(account_name, expires, timestamp)
else:
s = .format(account_name, expires, timestamp)
return hmac.new(preauth_key.encode(), s.encode(),
has... | Builds the preauth string and hmac it, following the zimbra spec.
Spec and examples are here http://wiki.zimbra.com/wiki/Preauth |
356,160 | def in_hull_volume(self):
r
i = self.network[]
s = self.network[]
d = self.network[]
Ps = self.network.pores()[np.logical_and(d, np.logical_or(i, s))]
inds = self.network._map(ids=self[][Ps], element=,
filtered=True)
self.... | r"""
Work out the voxels inside the convex hull of the voronoi vertices of
each pore |
356,161 | def _request_activity_data(self, athlete, filename):
response = self._get_request(self._activity_endpoint(athlete, filename)).json()
activity = pd.DataFrame(response[][])
activity = activity.rename(columns=ACTIVITY_COLUMN_TRANSLATION)
activity.index = pd.to_timedelta(activity.... | Actually do the request for activity filename
This call is slow and therefore this method is memory cached.
Keyword arguments:
athlete -- Full name of athlete
filename -- filename of request activity (e.g. \'2015_04_29_09_03_16.json\') |
356,162 | def _fit_tfa(self, data, R, template_prior=None):
if template_prior is None:
template_centers = None
template_widths = None
template_centers_mean_cov = None
template_widths_mean_var_reci = None
else:
template_centers = self.get_centers... | TFA main algorithm
Parameters
----------
data: 2D array, in shape [n_voxel, n_tr]
The fMRI data from one subject.
R : 2D array, in shape [n_voxel, n_dim]
The voxel coordinate matrix of fMRI data
template_prior : 1D array,
The template prior... |
356,163 | def _set_master_vlan(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=master_vlan.master_vlan, is_container=, presence=False, yang_name="master-vlan", rest_name="master-vlan", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, reg... | Setter method for master_vlan, mapped from YANG variable /topology_group_state/topology_group_data/master_vlan (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_master_vlan is considered as a private
method. Backends looking to populate this variable should
do ... |
356,164 | def reorder_dag(sequence,
depends_getter=lambda x: x.depends_on,
name_getter=lambda x: x.app_name,
impatience_max=100):
jobs = collections.defaultdict(list)
map_ = {}
_count_roots = 0
for each in sequence:
name = name_getter(each)
dep... | DAG = Directed Acyclic Graph
If we have something like:
C depends on B
B depends on A
A doesn't depend on any
Given the order of [C, B, A] expect it to return [A, B, C]
parameters:
:sequence: some sort of iterable list
:depends_getter: a callable that extracts the... |
356,165 | def upload(ctx, check, sdist, dry_run):
if check in get_valid_checks():
check_dir = os.path.join(get_root(), check)
else:
check_dir = resolve_path(check)
if not dir_exists(check_dir):
abort(.format(check))
check = basepath(check_dir)
pypi_config = ctx.... | Release a specific check to PyPI as it is on the repo HEAD. |
356,166 | def main():
run_config = _parse_args(sys.argv[1:])
if run_config.debug:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
gitlab_config = GitLabConfig(run_config.url, run_config.token)
project_updater_builder = FileBasedProjectVariablesUpdaterBuilder(
s... | Main method. |
356,167 | def push(self, *args, **kwargs):
stdout = six.b()
cmd = self.git.push(as_process=True, *args, **kwargs)
while True:
output = cmd.stdout.read(1)
sys.stdout.write(output.decode())
sys.stdout.flush()
stdout +... | Push commits to remote |
356,168 | def action(name, factory, label=None, desc=None):
_annotate("action", name, factory,
label=label, desc=desc) | Annotate a model's action.
@param name: the name of the model's action.
@type name: str or unicode
@param factory: a factory to create actions.
@type factory: IActionFactory
@param label: the action label if specified.
@type label: str or unicode or None
@param desc: the action description i... |
356,169 | def fromstring(cls, ptb_string, namespace=, precedence=False,
ignore_traces=True):
temp = tempfile.NamedTemporaryFile(delete=False)
temp.write(ptb_string)
temp.close()
ptb_docgraph = cls(ptb_filepath=temp.name, namespace=namespace,
pr... | create a PTBDocumentGraph from a string containing PTB parses. |
356,170 | def array_of_vstr(lst):
ls = []
for el in lst:
try:
ls.append(el.encode())
except AttributeError:
ls.append(el)
return numpy.array(ls, vstr) | :param lst: a list of strings or bytes
:returns: an array of variable length ASCII strings |
356,171 | def get_remote_file_size(self, url):
headers = requests.head(url).headers
return int(headers[]) | Gets the filesize of a remote file.
:param url:
The url that has to be checked.
:type url:
String
:returns:
int |
356,172 | def _sigmainf(N, h, m, dW, Km0, Pm0):
M = m*(m-1)//2
Im = broadcast_to(np.eye(m), (N, m, m))
IM = broadcast_to(np.eye(M), (N, M, M))
Ims0 = np.eye(m**2)
factor1 = broadcast_to((2.0/h)*np.dot(Km0, Ims0 - Pm0), (N, M, m**2))
factor2 = _kp2(Im, _dot(dW, _t(dW)))
factor3 = broadcast_to(np.d... | Asymptotic covariance matrix \Sigma_\infty Wiktorsson2001 eqn (4.5) |
356,173 | def collect(self, attrs):
for name, value in attrs.items():
if self.should_collect(value):
transition = self.workflow.transitions[value.trname]
if (
value.trname in self.implementations
and value.trname in sel... | Collect the implementations from a given attributes dict. |
356,174 | def calcphot(log, wavelengthArray, fluxArray, obsmode, extrapolate=False):
import pysynphot as syn
if extrapolate:
force = "extrapolate"
else:
force = None
sp = syn.ArraySpectrum(
wave=wavelengthArray, flux=fluxArray, waveunits=, fluxunits=)
... | *Run calcphot on single spectrum and filter.*
**Key Arguments:**
- ``log`` -- logger
- ``wavelengthArray`` -- the array containing the wavelength range of the spectrum
- ``fluxArray`` -- the array contain the respective spectrum flux (as function of wavelength)
- ``obsmode`` -- the ... |
356,175 | def send_message_and_wait(self, message, response_emsg, body_params=None, timeout=None, raises=False):
self.send(message, body_params)
response = self.wait_event(response_emsg, timeout, raises=raises)
if response is None:
return None
return response[0].body | .. versionchanged:: 0.8.4
Send a message to CM and wait for a defined answer.
:param message: a message instance
:type message: :class:`.Msg`, :class:`.MsgProto`
:param response_emsg: emsg to wait for
:type response_emsg: :class:`.EMsg`,:class:`int`
:param body_params: a... |
356,176 | def build_pipeline_string(self, forks):
final_forks = []
for i in range(0, len(forks)):
needs_merge = [False, 0, 0, 0, 0, ""]
is_merged = False
for i2 in range(0, len(forks[i])):
for j in range(i, len(forks)):
needs_merge... | Parses, filters and merge all possible pipeline forks into the
final pipeline string
This method checks for shared start and end sections between forks
and merges them according to the shared processes::
[[spades, ...], [skesa, ...], [...,[spades, skesa]]]
-> [..., ... |
356,177 | def drop_user(self, name):
statement = ddl.DropUser(name)
self._execute(statement) | Drop an MapD user
Parameters
----------
name : string
Database name |
356,178 | async def copy_to_table(self, table_name, *, source,
columns=None, schema_name=None, timeout=None,
format=None, oids=None, freeze=None,
delimiter=None, null=None, header=None,
quote=None, escape=None, force_q... | Copy data to the specified table.
:param str table_name:
The name of the table to copy data to.
:param source:
A :term:`path-like object <python:path-like object>`,
or a :term:`file-like object <python:file-like object>`, or
an :term:`asynchronous iterab... |
356,179 | def secure_channel(target, credentials, options=None, *, loop=None, executor=None,
standalone_pool_for_streaming=False):
return Channel(_grpc.secure_channel(target, credentials, options),
loop, executor, standalone_pool_for_streaming) | Creates a secure Channel to a server.
Args:
target: The server address.
credentials: A ChannelCredentials instance.
options: An optional list of key-value pairs (channel args in gRPC runtime)
to configure the channel.
Returns:
A Channel object. |
356,180 | def _retrieve_result(endpoints, token_header):
request_list = [
(url, token_header)
for (task_id, url) in endpoints
]
responses = concurrent_get(request_list)
assert len(endpoints) == len(responses)
responses_dic = {
task_i... | Prepare the request list and execute them concurrently. |
356,181 | def watch(self, resource, namespace=None, name=None, label_selector=None, field_selector=None, resource_version=None, timeout=None):
watcher = watch.Watch()
for event in watcher.stream(
resource.get,
namespace=namespace,
name=name,
field_selector=... | Stream events for a resource from the Kubernetes API
:param resource: The API resource object that will be used to query the API
:param namespace: The namespace to query
:param name: The name of the resource instance to query
:param label_selector: The label selector with which to filte... |
356,182 | def search_users(self, user):
user_url = "%s/%s/%s" % (self.url, "user", user)
response = self.jss.get(user_url)
return LDAPUsersResults(self.jss, response) | Search for LDAP users.
Args:
user: User to search for. It is not entirely clear how the
JSS determines the results- are regexes allowed, or
globbing?
Returns:
LDAPUsersResult object.
Raises:
Will raise a JSSGetError if no res... |
356,183 | def get_parser():
parser = argparse.ArgumentParser(
description="Reverse, undo, and calculate CRC32 checksums")
subparsers = parser.add_subparsers(metavar=)
poly_flip_parser = argparse.ArgumentParser(add_help=False)
subparser_group = poly_flip_parser.add_mutually_exclusive_group()
subp... | Return the command-line parser |
356,184 | def _is_uuid(uuid):
if uuid and list((len(x) for x in uuid.split())) == [8, 4, 4, 4, 12]:
return True
return False | Check if uuid is a valid smartos uuid
Example: e69a0918-055d-11e5-8912-e3ceb6df4cf8 |
356,185 | def ChunkedAttentionSelector(x, params, selector=None, **kwargs):
del params, kwargs
selector = selector or (lambda x: [] if x < 1 else [x-1])
triples, masks = zip(*x)
(queries, keys, values) = zip(*triples)
result = []
for i in range(len(x)):
selected = selector(i)
new_key_list = [keys... | Select which chunks to attend to in chunked attention.
Args:
x: inputs, a list of elements of the form (q, k, v), mask for each chunk.
params: parameters (unused).
selector: a function from chunk_number -> list of chunk numbers that says
which other chunks should be appended to the given one (previ... |
356,186 | def plot(self, plot_grouped=False, dates=None, min_dets=1, rate=False,
**kwargs):
all_dets = []
if dates:
new_party = self.filter(dates=dates, min_dets=min_dets)
for fam in new_party.families:
all_dets.extend(fam.detections)
else:
... | Plot the cumulative detections in time.
:type plot_grouped: bool
:param plot_grouped:
Whether to plot all families together (plot_grouped=True), or each
as a separate line.
:type dates: list
:param dates: list of obspy.core.UTCDateTime objects bounding the
... |
356,187 | def in_file(self, fn: str) -> Iterator[Statement]:
yield from self.__file_to_statements.get(fn, []) | Returns an iterator over all of the statements belonging to a file. |
356,188 | def _NormalizeDiscoveryUrls(discovery_url):
if discovery_url.startswith():
return [discovery_url]
elif not in discovery_url:
raise ValueError()
api_name, _, api_version = discovery_url.partition()
return [
% (
api_name, api_version),
% (
ap... | Expands a few abbreviations into full discovery urls. |
356,189 | def add_child(self, widget):
li_itm = _li(id=self.id + str(self._count))
li_itm.add_child(widget)
super(List, self).add_child(li_itm)
self._items.append((widget, li_itm))
self._count += 1 | Append a widget to the list.
:param widget: Object inheriting :class:`~.widgets.base.BaseElement` |
356,190 | def rise(self, crd, ev=):
if not is_measure(crd):
raise TypeError()
ps = self._getwhere()
self._fillnow()
hd = self.measure(crd, "hadec")
c = self.measure(crd, "app")
evq = dq.quantity(ev)
hdm1 = dq.quantity(hd["m1"])
psm1 = dq.quantit... | This method will give the rise/set hour-angles of a source. It
needs the position in the frame, and a time. If the latter is not
set, the current time will be used.
:param crd: a direction measure
:param ev: the elevation limit as a quantity or string
:returns: `dict` with rise ... |
356,191 | def get_historic_prices(self, **params):
if in params:
currency_pair = params[]
else:
currency_pair =
response = self._get(, , currency_pair, , params=params)
return self._make_api_object(response, APIObject) | https://developers.coinbase.com/api/v2#get-historic-prices |
356,192 | def benchmark_process_and_backend(exe, backend):
env = dict(os.environ)
env[] = backend
args = [exe, , ]
return get_benchproc_results(args, env=env) | Returns BenchmarkResults for a given executable and backend. |
356,193 | def add_section(self, section):
section, _, _ = self._validate_value_types(section=section)
super(ConfigParser, self).add_section(section) | Create a new section in the configuration. Extends
RawConfigParser.add_section by validating if the section name is
a string. |
356,194 | def format_value(value, error, plus_error=None, use_scientific_notation=3,
include_error=True, use_relative_error=False, ndecs=None):
minus_sign = if value < 0. else
value = abs(value)
minus_err = abs(error)
if plus_error is None:
plus_err = minus_err
else:
plus_err = ... | Given a numerical value and some bound on it, formats the number into a
string such that the value is rounded to the nearest significant figure,
which is determined by the error = abs(value-bound).
Note: if either use_scientific_notation or include_error are True, the
returned string will include LaTeX... |
356,195 | def get_context(self):
context = super(MailListView, self).get_context()
mail_list = registered_mails_names()
context[] = mail_list
return context | Add mails to the context |
356,196 | def draw(self, X, y, **kwargs):
if is_dataframe(X):
X = X.values
| Called from the fit method, this method creates the radviz canvas and
draws each instance as a class or target colored point, whose location
is determined by the feature data set. |
356,197 | def _provision_network(self, port_id, net_uuid, network_type,
physical_network, segmentation_id):
LOG.info("Provisioning network %s", net_uuid)
vswitch_name = self._get_vswitch_name(network_type, physical_network)
vswitch_map = {
: network_type,
... | Provision the network with the received information. |
356,198 | def spanstring2text(docgraph, span_string):
token_node_ids = spanstring2tokens(docgraph, span_string)
return u.join(docgraph.node[tok_node_id][docgraph.ns+]
for tok_node_id in token_node_ids) | converts a span of tokens (str, e.g. 'word_88..word_91') into a string
that contains the tokens itself. |
356,199 | def smoothed(mesh, angle):
if len(mesh.face_adjacency) == 0:
return mesh.copy()
angle_ok = mesh.face_adjacency_angles <= angle
adjacency = mesh.face_adjacency[angle_ok]
components = connected_components(adjacency,
min_len=1,
... | Return a non- watertight version of the mesh which will
render nicely with smooth shading by disconnecting faces
at sharp angles to each other.
Parameters
---------
mesh : trimesh.Trimesh
Source geometry
angle : float
Angle in radians, adjacent faces which have normals
below t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.