Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
337,800 | def _setse(self, i):
if i > 0:
u = (i * 2) - 1
else:
u = -2 * i
self._setue(u) | Initialise bitstring with signed exponential-Golomb code for integer i. |
337,801 | def generate_dmu_over_dt(species, propensity, n_counter, stoichiometry_matrix):
r
derives =[derive_expr_from_counter_entry(reac, species, c.n_vector) for (reac, c) in itertools.product(propensity, n_counter)]
factorial_terms = [get_one_over_n_factorial(tuple(c.n_vector)) for c in ... | r"""
Calculate :math:`\frac{d\mu_i}{dt}` in eq. 6 (see Ale et al. 2013).
.. math::
\frac{d\mu_i}{dt} = S \begin{bmatrix} \sum_{l} \sum_{n_1=0}^{\infty} ...
\sum_{n_d=0}^{\infty}
\frac{1}{\mathbf{n!}}
\frac{\partial^n \mathbf{n}a_l(\mathbf{x})}{\partial \mathbf{x^n}} |... |
337,802 | def generate_py_abilities(data):
def print_action(func_id, name, func, ab_id, general_id):
args = [func_id, % name, func, ab_id]
if general_id:
args.append(general_id)
print(" Function.ability(%s)," % ", ".join(str(v) for v in args))
func_ids = itertools.count(12)
for ability in sorted... | Generate the list of functions in actions.py. |
337,803 | def resolve_deep(values, max_depth=5, types=None):
def _resolve_sub(v, level):
l1 = level + 1
res_val = resolve_value(v, all_types)
if l1 < max_depth:
if isinstance(res_val, (list, tuple)):
return [_resolve_sub(item, l1) for item in res_val]
elif ... | Resolves all late-resolving types into their current values to a certain depth in a dictionary or list.
:param values: Values to resolve of any type.
:param max_depth: Maximum depth to recurse into nested lists, tuples and dictionaries. Below that depth values are
returned as they are.
:type max_depth... |
337,804 | def _validate_select_where(self):
| Checks that a filterset will not create invalid select statement |
337,805 | def QA_fetch_index_min_adv(
code,
start, end=None,
frequence=,
if_drop_index=True,
collections=DATABASE.index_min):
获取股票分钟线
if frequence in [, ]:
frequence =
elif frequence in [, ]:
frequence =
elif frequence in [, ]:
frequence =
eli... | '获取股票分钟线'
:param code:
:param start:
:param end:
:param frequence:
:param if_drop_index:
:param collections:
:return: |
337,806 | def _decode_request(self, encoded_request):
obj = self.serializer.loads(encoded_request)
return request_from_dict(obj, self.spider) | Decode an request previously encoded |
337,807 | def log10(x):
if isinstance(x, UncertainFunction):
mcpts = np.log10(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.log10(x) | Base-10 logarithm |
337,808 | def hdrmap(xmethod, dmethod, opt):
hdr = {: , : , : ,
u(): , : }
if xmethod == :
hdr.update({: , : , u(): })
else:
if opt[, , ]:
hdr.update({: , : ,
: , : })
else:
hdr.update({: })
if dmethod != :
hdr.update... | Return ``hdrmap`` argument for ``.IterStatsConfig`` initialiser. |
337,809 | def parse_samtools_flagstats(self):
self.samtools_flagstat = dict()
for f in self.find_log_files():
parsed_data = parse_single_report(f[])
if len(parsed_data) > 0:
if f[] in self.samtools_flagstat:
log.debug("Duplicate sample name fou... | Find Samtools flagstat logs and parse their data |
337,810 | def files_comments_delete(self, *, file: str, id: str, **kwargs) -> SlackResponse:
kwargs.update({"file": file, "id": id})
return self.api_call("files.comments.delete", json=kwargs) | Deletes an existing comment on a file.
Args:
file (str): The file id. e.g. 'F1234467890'
id (str): The file comment id. e.g. 'Fc1234567890' |
337,811 | def _update_simulation_start(self, simulation_start):
self.simulation_start = simulation_start
if self.simulation_duration is not None and self.simulation_start is not None:
self.simulation_end = self.simulation_start + self.simulation_duration
self._update_simulation_start_... | Update GSSHA simulation start time |
337,812 | def light_on(self, button: Button):
self.outport.send(mido.Message(, note=button.light, value=1)) | Turn the light on for the given Button.
NOTE! If yuo turn the "Off" button light on, the fader won't
report value updates when it's moved. |
337,813 | def dump(db, f, **options):
global enum_dict
global enums
sym_encoding = options.get(, )
enum_dict = {}
enums = "{ENUMS}\n"
header =
f.write(header.encode(sym_encoding))
def send_receive(for_frame):
return (
for_frame.attributes.get(, ) == ,
for... | export canmatrix-object as .sym file (compatible to PEAK-Systems) |
337,814 | def team(self, name=None, id=None, is_hidden=False, **kwargs):
_teams = self.teams(name=name, id=id, **kwargs)
if len(_teams) == 0:
raise NotFoundError("No team criteria matches")
if len(_teams) != 1:
raise MultipleFoundError("Multiple teams fit criteria")
... | Team of KE-chain.
Provides a team of :class:`Team` of KE-chain. You can filter on team name or provide id.
:param name: (optional) team name to filter
:type name: basestring or None
:param id: (optional) id of the user to filter
:type id: basestring or None
:param is_hi... |
337,815 | def parse_compound(s, global_compartment=None):
m = re.match(r, s)
if m:
s = m.group(1)
m = re.match(r, s)
if m:
compound_id = m.group(1)
compartment = m.group(2)
else:
compound_id = s
compartment = global_compartment
return Compound(compound_id, co... | Parse a compound specification.
If no compartment is specified in the string, the global compartment
will be used. |
337,816 | def walk_subclasses(root):
classes = [root]
visited = set()
while classes:
cls = classes.pop()
if cls is type or cls in visited:
continue
classes.extend(cls.__subclasses__())
visited.add(cls)
if cls is not root:
yield cls | Does not yield the input class |
337,817 | def _from_pointer(pointer, incref):
if pointer == ffi.NULL:
raise ValueError()
if incref:
cairo.cairo_pattern_reference(pointer)
self = object.__new__(PATTERN_TYPE_TO_CLASS.get(
cairo.cairo_pattern_get_type(pointer), Pattern))
Pattern.__init__... | Wrap an existing :c:type:`cairo_pattern_t *` cdata pointer.
:type incref: bool
:param incref:
Whether increase the :ref:`reference count <refcounting>` now.
:return:
A new instance of :class:`Pattern` or one of its sub-classes,
depending on the pattern’s type... |
337,818 | def get_initial_status_brok(self, extra=None):
if extra and isinstance(extra, Items):
members = []
for member_id in self.members:
member = extra[member_id]
members.append((member.uuid, member.get_name()))
extra = {: members}
... | Get a brok with the group properties
`members` contains a list of uuid which we must provide the names. Thus we will replace
the default provided uuid with the members short name. The `extra` parameter, if present,
is containing the Items to search for...
:param extra: monitoring item... |
337,819 | def on_mouse_motion(x, y, dx, dy):
mouse.x, mouse.y = x, y
mouse.move()
window.update_caption(mouse) | 当鼠标没有按下时移动的时候触发 |
337,820 | def processPreKeyBundle(self, preKey):
if not self.identityKeyStore.isTrustedIdentity(self.recipientId, preKey.getIdentityKey()):
raise UntrustedIdentityException(self.recipientId, preKey.getIdentityKey())
if preKey.getSignedPreKey() is not None and\
not Curve.verifySig... | :type preKey: PreKeyBundle |
337,821 | def main():
e = mod_env.Internet(, )
e.create(800)
print(e)
print(npc.web_users.params) | generates a virtual internet, sets pages and runs web_users on it |
337,822 | def remove_pattern(self, pattern):
for index, node in enumerate(self.root_node.children):
if node.name != pattern:
continue
LOGGER.debug("> Removing at index.".format(pattern, index))
self.beginRemoveRows(self.get_node_index(self.root_node), inde... | Removes given pattern from the Model.
:param pattern: Pattern.
:type pattern: unicode
:return: Method success.
:rtype: bool |
337,823 | def rpoplpush(self, sourcekey, destkey, *, encoding=_NOTSET):
return self.execute(b, sourcekey, destkey,
encoding=encoding) | Atomically returns and removes the last element (tail) of the
list stored at source, and pushes the element at the first element
(head) of the list stored at destination. |
337,824 | def link_markdown_cells(cells, modules):
"Create documentation links for all cells in markdown with backticks."
for i, cell in enumerate(cells):
if cell[] == :
cell[] = link_docstring(modules, cell[]) | Create documentation links for all cells in markdown with backticks. |
337,825 | def get_json(url, auth=None, data=None):
headers = {
: ,
: ,
}
if auth:
headers[] = .format(auth=auth)
params = {}
if data:
headers[] =
params[] = json.dumps(data).encode()
request = urllib2.Request(url, headers=headers, **params)
resp... | Make a GET request, and return the response as parsed JSON. |
337,826 | def split(self, data):
line = deepcopy(data)
line_width = (self.width() - 1)
lines = []
while len(line):
new_line = line[:line_width]
new_line_pos = new_line.find()
if new_line_pos >= 0:
new_line = line[:new_line_pos]
line = line[(new_line_pos + 1):]
else:
line = line[line_width:]
... | Split data into list of string, each (self.width() - 1) length or less. If nul-length string
specified then empty list is returned
:param data: data to split
:return: list of str |
337,827 | def getExtensions(self, extname=, section=None):
if section is None:
numext = 0
section = []
for hdu in self._image:
if in hdu.header and hdu.header[] == extname:
section.append(hdu.header[])
else:
if not isins... | Return the list of EXTVER values for extensions with name specified
in extname. |
337,828 | def bands(self):
bands = []
for c in self.stars.columns:
if re.search(,c):
bands.append(c)
return bands | Bandpasses for which StarPopulation has magnitude data |
337,829 | def __check_port(self, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((_host(), port))
return True
except socket.error:
return False
finally:
s.close() | check port status
return True if port is free, False else |
337,830 | def get_area(self, area_id, resolve_missing=False):
areas = self.get_areas(area_id=area_id)
if len(areas) == 0:
if resolve_missing is False:
raise exception.DataIncomplete("Resolve missing area is disabled")
query = ("\n"
"[out:json]... | Get an area by its ID.
:param area_id: The area ID
:type area_id: Integer
:param resolve_missing: Query the Overpass API if the area is missing in the result set.
:return: The area
:rtype: overpy.Area
:raises overpy.exception.DataIncomplete: The requested way is not avai... |
337,831 | def set_state(self, state):
if self.index() == 0:
values = {"outlets": [{"desired_state": {"powered": state}}, {}]}
else:
values = {"outlets": [{}, {"desired_state": {"powered": state}}]}
response = self.api_interface.set_device_state(self, values, id_ove... | :param state: a boolean of true (on) or false ('off')
:return: nothing |
337,832 | def short_codes(self):
if self._short_codes is None:
self._short_codes = ShortCodeList(self._version, service_sid=self._solution[], )
return self._short_codes | Access the short_codes
:returns: twilio.rest.proxy.v1.service.short_code.ShortCodeList
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeList |
337,833 | def get_states(self, n):
return self.states[len(self.new_states):len(self.new_states) + n] | Get the next n recurrent states.
Called by layers in "incremental" mode.
Args:
n: an integer
Returns:
a list of n Tensors |
337,834 | def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=compat_get_request_data(request))
compat_serializer_check_is_valid(serializer)
self.perform_create(request, serializer)
headers = self.get_success_headers(serializer.data)
return Response(s... | We ensure the Thread only involves eligible participants. |
337,835 | def check_value(self, value):
if value and self.size:
if not is_string(value):
raise ValueError("Value supplied has to be a string")
if len(value) > self.size:
raise ValueError(
"Lenght of th... | Check the validity of a value for the field. |
337,836 | def palette(self, alpha=):
if not self.plte:
raise FormatError(
"Required PLTE chunk is missing in colour type 3 image.")
plte = group(array(, self.plte), 3)
if self.trns or alpha == :
trns = array(, self.trns or )
trns.extend([255]*(... | Returns a palette that is a sequence of 3-tuples or 4-tuples,
synthesizing it from the ``PLTE`` and ``tRNS`` chunks. These
chunks should have already been processed (for example, by
calling the :meth:`preamble` method). All the tuples are the
same size: 3-tuples if there is no ``tRNS``... |
337,837 | def parse_csv_dataset(data, handle_units):
fobj = BytesIO(data)
names, units = parse_csv_header(fobj.readline().decode())
arrs = np.genfromtxt(fobj, dtype=None, names=names, delimiter=, unpack=True,
converters={: lambda s: parse_iso_date(s.decode())})
d = {}
for f in ar... | Parse CSV data into a netCDF-like dataset. |
337,838 | def get_int(self, input_string):
if input_string in (, ):
try:
index = self.args.index(input_string) + 1
except ValueError:
if input_string in self.required:
print("\n {flag} is required\n".forma... | Return integer type user input |
337,839 | def unflatten(flat_weights):
if flat_weights.columns.contains("key"):
weights = {}
for key in flat_weights.loc[:, "key"].unique():
flt_wts = flat_weights.loc[flat_weights.loc[:, "key"] == key, :]
flt_wts = flt_wts.drop(labels="key", axis=1)
wts = flt_wts.pi... | Pivot weights from long DataFrame into weighting matrix.
Parameters
----------
flat_weights: pandas.DataFrame
A long DataFrame of weights, where columns are "date", "contract",
"generic", "weight" and optionally "key". If "key" column is
present a dictionary of unflattened DataFrame... |
337,840 | def _add_value_to_dophot_table(
self):
self.log.info()
sqlQuery = % locals()
writequery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.atlasMoversDBConn
)
sqlQuery = % locals()
writequery(
lo... | *add value to dophot table* |
337,841 | def array_append(path, *values, **kwargs):
return _gen_4spec(LCB_SDCMD_ARRAY_ADD_LAST, path,
MultiValue(*values),
create_path=kwargs.pop(, False),
**kwargs) | Add new values to the end of an array.
:param path: Path to the array. The path should contain the *array itself*
and not an element *within* the array
:param values: one or more values to append
:param create_parents: Create the array if it does not exist
.. note::
Specifying multipl... |
337,842 | def make_multiscale_dilated(image, resolutions, num_channels=3):
image_height = common_layers.shape_list(image)[0]
scaled_images = []
for height in resolutions:
dilation_rate = image_height // height
scaled_image = image[::dilation_rate, ::dilation_rate]
scaled_image = tf.to_int64(scaled_image)
... | Returns list of scaled images, one for each resolution.
Resizes by skipping every nth pixel.
Args:
image: Tensor of shape [height, height, num_channels].
resolutions: List of heights that image's height is resized to. The function
assumes VALID padding, so the original image's height must be divisib... |
337,843 | def sharepoint(self, *, resource=):
if not isinstance(self.protocol, MSGraphProtocol):
raise RuntimeError(
)
return Sharepoint(parent=self, main_resource=resource) | Get an instance to read information from Sharepoint sites for the
specified account resource
:param str resource: Custom resource to be used in this sharepoint
object (Defaults to parent main_resource)
:return: a representation of Sharepoint Sites
:rtype: Sharepoint
:ra... |
337,844 | def prices(self):
if not self.__prices_aggregate:
self.__prices_aggregate = PricesAggregate(self.book)
return self.__prices_aggregate | Prices aggregate |
337,845 | def select_current_cell(self):
cursor = self.textCursor()
cursor.movePosition(QTextCursor.StartOfBlock)
cur_pos = prev_pos = cursor.position()
while self.is_cell_separator(cursor):
cursor.movePosition(QTextCursor.NextBlock)
prev... | Select cell under cursor
cell = group of lines separated by CELL_SEPARATORS
returns the textCursor and a boolean indicating if the
entire file is selected |
337,846 | def create_bioset_lookup(lookupdb, spectrafns, set_names):
unique_setnames = set(set_names)
lookupdb.store_biosets(((x,) for x in unique_setnames))
set_id_map = lookupdb.get_setnames()
mzmlfiles = ((os.path.basename(fn), set_id_map[setname])
for fn, setname in zip(spectrafns, set_n... | Fills lookup database with biological set names |
337,847 | def Convert(self, wave, flux, target_units, area=None):
try:
return self.Dispatch[target_units](wave, flux, area=area)
except KeyError:
raise TypeError("%s is not a valid flux unit" % (target_units)) | Perform unit conversion.
Parameters
----------
wave, flux : number or array_like
Wavelength and flux values to be used for conversion.
target_units : str
Unit to convert to.
area : number or `None`
Telescope :ref:`area <pysynphot-area>`, if ... |
337,848 | def set_primary_heartbeat(self, interface_id):
self.interface.set_unset(interface_id, )
self._engine.update() | Set this interface as the primary heartbeat for this engine.
This will 'unset' the current primary heartbeat and move to
specified interface_id.
Clusters and Master NGFW Engines only.
:param str,int interface_id: interface specified for primary mgmt
:raises InterfaceNot... |
337,849 | def only_pallets_theme(default=None):
def decorator(f):
@wraps(f)
def wrapped(app, *args, **kwargs):
if not app.config.is_pallets_theme:
return default
return f(app, *args, **kwargs)
return wrapped
return decorator | Create a decorator that calls a function only if the
``is_pallets_theme`` config is ``True``.
Used to prevent Sphinx event callbacks from doing anything if the
Pallets themes are installed but not used. ::
@only_pallets_theme()
def inject_value(app):
...
app.connect("b... |
337,850 | def post_field_cache(self, field_cache):
index_pattern = self.field_cache_to_index_pattern(field_cache)
resp = requests.post(self.post_url, data=index_pattern).text
resp = json.loads(resp)
return 0 | Where field_cache is a list of fields' mappings |
337,851 | def T_converter(T, current, desired):
rITS-90ITS-68ITS-48ITS-76ITS-27ITS-76ITS-90ITS-90ITS-68ITS-48ITS-76ITS-27ITS-90ITS-68ITS-48ITS-76ITS-27ITS-68ITS-48
def range_check(T, Tmin, Tmax):
if T < Tmin or T > Tmax:
raise Exception()
try:
if current == :
pass
elif... | r'''Converts the a temperature reading made in any of the scales
'ITS-90', 'ITS-68','ITS-48', 'ITS-76', or 'ITS-27' to any of the other
scales. Not all temperature ranges can be converted to other ranges; for
instance, 'ITS-76' is purely for low temperatures, and 5 K on it has no
conversion to 'ITS-90' ... |
337,852 | def set_theme(self, theme):
if theme in THEMES:
self.palette = THEMES[theme]
if self._scroll_bar:
self._scroll_bar._palette = self.palette | Pick a palette from the list of supported THEMES.
:param theme: The name of the theme to set. |
337,853 | def match(self, path, **kw):
m = self._pattern.match(path)
if m:
kwargs = m.groupdict()
for url_arg_name, value_urlencoded in kwargs.items():
conv_obj = self._url_params[url_arg_name]
unicode_value = unquote(value_urlencoded)
... | path - str (urlencoded) |
337,854 | def create_source_table(scan_shape):
cols_dict = collections.OrderedDict()
cols_dict[] = dict(dtype=, format=)
cols_dict[] = dict(dtype=, format=)
cols_dict[] = dict(dtype=, format=)
cols_dict[] = dict(dtype=, format=)
cols_dict[] = dict(dtype=, format=)
cols_dict[] = dict(dtype=, form... | Create an empty source table.
Returns
-------
tab : `~astropy.table.Table` |
337,855 | def prepare(ctx, new_version=None, version_part=None, hide=True,
dry_run=False):
if new_version is not None:
bump_version(ctx, new_version, version_part=version_part,
dry_run=dry_run)
build_packages(ctx, hide=hide)
packages = ensure_packages_exist(ctx, check_onl... | Prepare the release: bump version, build packages, ... |
337,856 | def run(self):
self._logger.info("Parsing data files for ssGSEA...........................")
data = self.load_data()
normdat = self.norm_samples(data)
gmt = self.load_gmt(gene_list=normdat.index.values, gmt=self.gene_sets)
self._logger.info("%0... | run entry |
337,857 | def update(self, obj_id, is_public=NotUpdated, is_protected=NotUpdated):
data = {}
self._copy_if_updated(data, is_public=is_public,
is_protected=is_protected)
return self._patch( % obj_id, data) | Update a Job Execution. |
337,858 | def create_launch_configuration(self, launch_config):
params = {: launch_config.image_id,
: launch_config.name,
: launch_config.instance_type}
if launch_config.key_name:
params[] = launch_config.key_name
if launch_config.user_data:
... | Creates a new Launch Configuration.
:type launch_config: :class:`boto.ec2.autoscale.launchconfig.LaunchConfiguration`
:param launch_config: LaunchConfiguration object. |
337,859 | def _to_python(input_string):
python_string =
for i in range(len(input_string)):
if not python_string:
python_string += input_string[i].lower()
elif input_string[i].isupper():
python_string += % input_string[i].lower()
else:
python_string += inp... | a helper method to convert camelcase to python |
337,860 | def deconv_rl(data, h, Niter = 10):
if isinstance(data,np.ndarray):
return _deconv_rl_np(data,h, Niter)
elif isinstance(data,OCLArray):
return _deconv_rl_gpu_conv(data,h, Niter)
else:
raise TypeError("array argument (1) has bad type: %s"%type(arr_obj)) | richardson lucy deconvolution of data with psf h
using spatial convolutions (h should be small then) |
337,861 | def update_ckan_ini(self, skin=True):
command = [
, , ,
, ,
,
,
,
,
,
,
+
( if exists(self.target + ) else )
+
+ (.format(self.name) if skin else ),
... | Use config-tool to update development.ini with our environment settings
:param skin: use environment template skin plugin True/False |
337,862 | def parseRCDataRawtext(self, token, contentType):
assert contentType in ("RAWTEXT", "RCDATA")
self.tree.insertElement(token)
if contentType == "RAWTEXT":
self.tokenizer.state = self.tokenizer.rawtextState
else:
self.tokenizer.state = self.tokenizer.rcda... | Generic RCDATA/RAWTEXT Parsing algorithm
contentType - RCDATA or RAWTEXT |
337,863 | def itertuples(self, index=True, name="Pandas"):
arrays = []
fields = list(self.columns)
if index:
arrays.append(self.index)
fields.insert(0, "Index")
arrays.extend(self.iloc[:, k] for k in range(len(self.columns)))
if name is ... | Iterate over DataFrame rows as namedtuples.
Parameters
----------
index : bool, default True
If True, return the index as the first element of the tuple.
name : str or None, default "Pandas"
The name of the returned namedtuples or None to return regular
... |
337,864 | def fit(
self,
data,
states,
estimator=None,
complete_samples_only=True,
**kwargs):
if estimator == :
mean, variance = self.maximum_likelihood_estimator(data, states)
elif estimator == :
raise NotImp... | Determine βs from data
Parameters
----------
data: pandas.DataFrame
Dataframe containing samples from the conditional distribution, p(Y|X)
estimator: 'MLE' or 'MAP'
completely_samples_only: boolean (True or False)
Are they downsampled or complete? De... |
337,865 | def createLoanOffer(self, currency, amount, duration, autoRenew,
lendingRate):
return self._private(, currency=currency,
amount=amount, duration=duration,
autoRenew=autoRenew, lendingRate=lendingRate) | Creates a loan offer for a given currency. Required POST parameters
are "currency", "amount", "duration", "autoRenew" (0 or 1), and
"lendingRate". |
337,866 | def sixteensreporter(self, analysistype=):
make_path(self.reportpath)
header =
data =
with open(os.path.join(self.reportpath, analysistype + ), ) as report:
with open(os.path.join(self.reportpath, analysistype + ), ) as sequences:
... | Creates a report of the results
:param analysistype: The variable to use when accessing attributes in the metadata object |
337,867 | def kernels_output_cli(self,
kernel,
kernel_opt=None,
path=None,
force=False,
quiet=False):
kernel = kernel or kernel_opt
self.kernels_output(kernel, path, forc... | client wrapper for kernels_output, with same arguments. Extra
arguments are described below, and see kernels_output for others.
Parameters
==========
kernel_opt: option from client instead of kernel, if not defined |
337,868 | def resolve(self):
s = self._flavour.resolve(self)
if s is None:
normed = self._flavour.pathmod.normpath(s)
obj = self._from_parts((normed,), init=False)
obj._init(template=self)
return obj | Make the path absolute, resolving all symlinks on the way and also
normalizing it (for example turning slashes into backslashes under
Windows). |
337,869 | def cosine_similarity_vec(num_tokens, num_removed_vec):
remaining = -np.array(num_removed_vec) + num_tokens
return remaining / (np.sqrt(num_tokens + 1e-6) * np.sqrt(remaining + 1e-6)) | Return cosine similarity between a binary vector with all ones
of length ``num_tokens`` and vectors of the same length with
``num_removed_vec`` elements set to zero. |
337,870 | def parse_width(width, n):
if isinstance(width, int):
widths = [width] * n
else:
assert len(width) == n, "Widths and data do not match"
widths = width
return widths | Parses an int or array of widths
Parameters
----------
width : int or array_like
n : int |
337,871 | def deform2curve(script, curve=mp_func.torus_knot(), step=0.001):
curve_step = []
for idx, val in enumerate(curve):
curve[idx] = val.replace(, )
curve_step.append(val.replace(, .format(step)))
tangent = mp_func.v_subtract(curve_step, curve)
normal1 = mp_func.v_add(curve_step, curve... | Deform a mesh along a parametric curve function
Provide a parametric curve function with z as the parameter. This will
deform the xy cross section of the mesh along the curve as z increases.
Source: http://blackpawn.com/texts/pqtorus/
Methodology:
T = P' - P
N1 = P' + P
B = T x N1
N... |
337,872 | def tx_xml(self):
return self._tx_tmpl.format(**{
: self._series.name_ref,
: self.name,
: ,
}) | Return the ``<c:tx>`` (tx is short for 'text') element for this
series as unicode text. This element contains the series name. |
337,873 | def _set_cos_threshold(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=cos_threshold.cos_threshold, is_container=, presence=False, yang_name="cos-threshold", rest_name="cos-threshold", parent=self, path_helper=self._path_helper, extmethods=self._extme... | Setter method for cos_threshold, mapped from YANG variable /interface/gigabitethernet/qos/rcv_queue/cos_threshold (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_cos_threshold is considered as a private
method. Backends looking to populate this variable should
... |
337,874 | def node_is_upstream_leaf(graph: BELGraph, node: BaseEntity) -> bool:
return 0 == len(graph.predecessors(node)) and 1 == len(graph.successors(node)) | Return if the node is an upstream leaf.
An upstream leaf is defined as a node that has no in-edges, and exactly 1 out-edge. |
337,875 | def get_container(self, name):
name = adapt_name_for_rest(name)
url = .format(self._instance, name)
response = self._client.get_proto(url)
message = mdb_pb2.ContainerInfo()
message.ParseFromString(response.content)
return Container(message) | Gets a single container by its unique name.
:param str name: Either a fully-qualified XTCE name or an alias in the
format ``NAMESPACE/NAME``.
:rtype: .Container |
337,876 | def tailf(
filepath,
lastn=0,
timeout=60,
stopon=None,
encoding="utf8",
delay=0.1
):
if not os.path.isfile(filepath):
raise ShCmdError("[{0}] not exists".format(filepath))
if consts.TIMEOUT_MAX > timeout:
timeout = consts.TIMEOUT_DEFAULT
delay = delay if consts... | provide a `tail -f` like function
:param filepath: file to tail -f, absolute path or relative path
:param lastn: lastn line will also be yield
:param timeout: (optional)
stop tail -f when time's up [timeout <= 10min, default = 1min]
:param stopon: (optional) stops when the stopon(output) return... |
337,877 | def push_async_exit(self, exit):
_cb_type = type(exit)
try:
exit_method = _cb_type.__aexit__
except AttributeError:
self._push_exit_callback(exit, False)
else:
self._push_async_cm_exit(exit, exit_method)
return exit | Registers a coroutine function with the standard __aexit__ method
signature.
Can suppress exceptions the same way __aexit__ method can.
Also accepts any object with an __aexit__ method (registering a call
to the method instead of the object itself). |
337,878 | def add_stats_table(self):
totals = {sample: sum(counts.values())
for sample, counts in self.data.items()}
percentages = {sample: {k: (v / totals[sample]) * 100
for k, v in counts.items()}
for sample, counts in self.data... | Adds stats to general table. |
337,879 | def read_json(self, file_name=None, input_json=None, imported_data=pd.DataFrame()):
if not file_name and not input_json or file_name and input_json:
raise TypeError()
if file_name:
if not isinstance(file_name, str) or not file_name.endswith() or not os... | Read input json file.
Notes
-----
The input json file should include ALL parameters.
Parameters
----------
file_name : str
Filename to be read.
input_json : dict
JSON object to be read.
imported_data : pd.DataFrame()
... |
337,880 | def GetSource(self, row, col, table=None):
if table is None:
table = self.grid.current_table
value = self.code_array((row, col, table))
if value is None:
return u""
else:
return value | Return the source string of a cell |
337,881 | def complex_files(script=, escript=None, paths=None, **kwargs):
ds = _data.load_multiple(paths=paths)
if len(ds) == 0: return
if not in kwargs: kwargs[] = _os.path.split(ds[0].path)[0]
return complex_databoxes(ds, script=script, **kwargs) | Loads files and plots complex data in the real-imaginary plane.
Parameters
----------
script='d[1]+1j*d[2]'
Complex-valued script for data array.
escript=None
Complex-valued script for error bars
paths=None
List of paths to open. None means use a dialog
Se... |
337,882 | def open(self):
request = urllib.request.Request(self.uri)
if self.server_data.authorization_header() is not None:
request.add_header(, self.server_data.authorization_header())
request.add_header(, )
return urllib.request.urlopen(request) | Opens the URL associated with the GPFile and returns a file-like object
with three extra methods:
* geturl() - return the ultimate URL (can be used to determine if a
redirect was followed)
* info() - return the meta-information of the page, such as headers
... |
337,883 | def cal_position(self, text, has_toplinks, has_bottomlinks, head_len, head_start):
if head_len == 0:
top_start = top_end = bottom_start = bottom_end = 0
else:
top_start = top_end = head_start + 6
bottom_start = bottom_end = head_start + head_len - 7
... | Calculate the position of toplinks and bottomlinks, if there is not
toplinks and bottomlinks then toplinks position will be the position after <head>
and if there is no bottomlinks, the bottomlinks position will be the
position before </head>. |
337,884 | def applyFlatIncomeTax(IncomeDstn,tax_rate,T_retire,unemployed_indices=[],transitory_index=2):
IncomeDstn_new = deepcopy(IncomeDstn)
i = transitory_index
for t in range(len(IncomeDstn)):
if t < T_retire:
for j in range((IncomeDstn[t][i]).size):
if j not in unemployed... | Applies a flat income tax rate to all employed income states during the working
period of life (those before T_retire). Time runs forward in this function.
Parameters
----------
IncomeDstn : [income distributions]
The discrete approximation to the income distribution in each time period.
t... |
337,885 | def destroy(self, request, *args, **kwargs):
obj = self.get_object()
user = request.user
if strtobool(request.query_params.get(, )):
for entity in obj.entity_set.all():
if user.has_perm(, entity):
entity.delete()
for data in ... | Destroy a model instance.
If ``delete_content`` flag is set in query parameters, also all
Data objects and Entities, on which user has ``EDIT``
permission, contained in collection will be deleted. |
337,886 | def guess_import_format(filename, **kwargs):
(_,filename) = os.path.split(filename)
if in filename:
fnm = filename.lower()
fmt = next((k for (k,(_,es,_)) in six.iteritems(importers)
if any(fnm.endswith( + e) for e in es)),
None)
if fmt: r... | guess_import_format(filename) attempts to guess the file format for the given filename; it does
this guessing by looking at the file extension and using registered sniff-tests from
importers. It will not attempt to load the file, so if the extension of the filename is
missing, it is unlikely that this... |
337,887 | def dump_nt_sorted(g: Graph) -> List[str]:
return [l.decode() for l in sorted(g.serialize(format=).splitlines()) if l] | Dump graph g in a sorted n3 format
:param g: graph to dump
:return: stringified representation of g |
337,888 | def merge(self, ref_name: str):
if self.is_dirty():
LOGGER.error(, ref_name)
sys.exit(-1)
LOGGER.info(, ref_name, self.get_current_branch())
self.repo.git.merge(ref_name) | Merges two refs
Args:
ref_name: ref to merge in the current one |
337,889 | def operate(self, vala, valb, oper):
operation = {
: operator.add,
: operator.sub,
: operator.mul,
: operator.truediv,
: operator.eq,
: operator.gt,
: operator.lt,
: operator.ge,
: operator.le,
... | Perform operation
args:
vala (mixed): 1st value
valb (mixed): 2nd value
oper (str): operation
returns:
mixed |
337,890 | async def remove(self, path):
if await self.exists(path):
info = await self.stat(path)
if info["type"] == "file":
await self.remove_file(path)
elif info["type"] == "dir":
for name, info in (await self.list(path)):
i... | :py:func:`asyncio.coroutine`
High level remove method for removing path recursively (file or
directory).
:param path: path to remove
:type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath` |
337,891 | def transform(curve, tf):
def to_point(p):
return np.array([[p.real], [p.imag], [1.0]])
def to_vector(z):
return np.array([[z.real], [z.imag], [0.0]])
def to_complex(v):
return v.item(0) + 1j * v.item(1)
if isinstance(curve, Path):
return Path(*[transform(segment,... | Transforms the curve by the homogeneous transformation matrix tf |
337,892 | def setHookName(self, name: str):
self.isHook = True
self.messengerName = name | Specify that the message will be delivered with the hook ``name``. |
337,893 | def _render_map(self, surface, rect, surfaces):
self._tile_queue = self.data.process_animation_queue(self._tile_view)
self._tile_queue and self._flush_tile_queue(self._buffer)
if not self._anchored_view:
self._clear_surface(surface, self._previous... | Render the map and optional surfaces to destination surface
:param surface: pygame surface to draw to
:param rect: area to draw to
:param surfaces: optional sequence of surfaces to interlace between tiles |
337,894 | def parallel_periodicvar_recovery(simbasedir,
period_tolerance=1.0e-3,
liststartind=None,
listmaxobjects=None,
nworkers=None):
recovered
pfpkldir = os.path.join(simbasedi... | This is a parallel driver for `periodicvar_recovery`.
Parameters
----------
simbasedir : str
The base directory where all of the fake LCs and period-finding results
are.
period_tolerance : float
The maximum difference that this function will consider between an
actual ... |
337,895 | def create_repository(self, path, info=None, verbose=True):
try:
info = copy.deepcopy( info )
except:
raise Exception("Repository info must be a copyable python object.")
if path.strip() in (,):
path = os.getcwd()
realPath = os.path.r... | create a repository in a directory.
This method insures the creation of the directory in the system if it is missing.\n
**N.B. This method erases existing pyrep repository in the path but not the repository files.**
:Parameters:
#. path (string): The real absolute path where to cre... |
337,896 | def block_sep0(self, Y):
r
return np.swapaxes(
Y[(slice(None),)*self.blkaxis + (slice(0, self.blkidx),)],
self.cri.axisK, self.cri.axisM) | r"""Separate variable into component corresponding to
:math:`\mathbf{y}_0` in :math:`\mathbf{y}\;\;`. The method from
parent class :class:`.ADMMTwoBlockCnstrnt` is overridden here to
allow swapping of K (multi-image) and M (filter) axes in block 0
so that it can be concatenated on axis M... |
337,897 | def send_job(self, message, body_params=None):
jobid = self.current_jobid = ((self.current_jobid + 1) % 10000) or 1
self.remove_all_listeners( % jobid)
if message.proto:
message.header.jobid_source = jobid
else:
message.header.sourceJobID = jobid
... | .. versionchanged:: 0.8.4
Send a message as a job
.. note::
Not all messages are jobs, you'll have to find out which are which
:param message: a message instance
:type message: :class:`.Msg`, :class:`.MsgProto`
:param body_params: a dict with params to the body (onl... |
337,898 | def matplotlibensure(func):
@wraps(func)
def wrap(*args):
if MPLINSTALLED == False:
raise ImportError(msg)
return func(*args)
return wrap | If matplotlib isn't installed, this decorator alerts the user and
suggests how one might obtain the package. |
337,899 | def dockerCall(*args, **kwargs):
logger.warn("WARNING: dockerCall() using subprocess.check_output() "
"is deprecated, please switch to apiDockerCall().")
return subprocessDockerCall(*args, checkOutput=False, **kwargs) | Deprecated. Runs subprocessDockerCall() using 'subprocess.check_output()'.
Provided for backwards compatibility with a previous implementation that
used 'subprocess.check_call()'. This has since been supplanted and
apiDockerCall() is recommended. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.