content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_burn_inside(accounts, nftmint):
"""Burn inside"""
nftmint.mint(accounts[0], 10000, {"from": accounts[0]})
nftmint.burn(2000, 4000, {"from": accounts[0]})
assert nftmint.totalSupply() == 8000
assert nftmint.balanceOf(accounts[0]) == 8000
assert nftmint.rangesOf(accounts[0]) == [(1, 2000)... | 57,200 |
def webview_argv():
"""This is tied to a console script called webview. It just provides
a convenient way to pop up a browser to view a specified html file(s).
"""
for name in sys.argv[1:]:
if os.path.isfile(name):
webview(name) | 57,201 |
def Get_db_names():
"""
Get and return database name initials from the Cloudant storage for dataset initialization
"""
#return uniqueDbnames
return json.dumps(dataset.Get_db_names()) | 57,202 |
def map_remove_by_key(bin_name, key, return_type):
"""Creates a map_remove_by_key operation to be used with operate or operate_ordered
The operation removes an item, specified by the key from the map stored in the specified bin.
Args:
bin_name (str): The name of the bin containing the map.
... | 57,203 |
def eval_one_epoch(sess, ops, test_writer, test_data=True):
""" ops: dict mapping from string to tf ops """
if test_data:
current_data, current_label = data_utils.get_current_data_h5(
TEST_DATA, TEST_LABELS, NUM_POINT
)
else:
print("WARNING: Evaluating on train data")
... | 57,204 |
def decode_compress_to_multi_index(encoded, idxnames=None):
"""
Decode a compressed variable to a pandas MultiIndex.
Parameters
----------
encoded : xarray.Dataset
Encoded Dataset with variables that use "compression by gathering".capitalize
idxnames : hashable or iterable of hashable, ... | 57,205 |
def rank(X, cond=1.0e-12):
"""
Return the rank of a matrix X based on its generalized inverse,
not the SVD.
"""
X = np.asarray(X)
if len(X.shape) == 2:
D = scipy.linalg.svdvals(X)
return int(np.add.reduce(np.greater(D / D.max(), cond).astype(np.int32)))
else:
return i... | 57,206 |
def __virtual__():
"""
Only load this execution module if TTP is installed.
"""
if HAS_TTP:
return __virtualname__
return (False, " TTP execution module failed to load: TTP library not found.") | 57,207 |
def timeout_raiser(_signum, _frame):
"""Raise a timeout exception"""
raise Timeout() | 57,208 |
def _Region4(P, x):
"""Basic equation for region 4"""
T=_TSat_P(P)
P1=_Region1(T, P)
P2=_Region2(T, P)
propiedades={}
propiedades["T"]=T
propiedades["P"]=P
propiedades["v"]=P1["v"]+x*(P2["v"]-P1["v"])
propiedades["h"]=P1["h"]+x*(P2["h"]-P1["h"])
propiedades["s"]=P1["s"]+x*(P2["s... | 57,209 |
def registerExtensions():
"""Registers the macroserver extensions in the
:class:taurus.core.tango.TangoFactory`"""
import taurus
factory = taurus.Factory()
factory.registerDeviceClass('MacroServer', QMacroServer)
factory.registerDeviceClass('Door', QDoor)
# ugly access to qtgui level: in fu... | 57,210 |
def show_template_list():
"""Show available HTML templates."""
filenames = pkg_resources.resource_listdir(__name__, "data")
filenames = [f for f in filenames if f.endswith(".html")]
if not filenames:
print("No templates")
else:
for f in filenames:
print(f)
return True | 57,211 |
def test_lansweeper_mac_hunt_command_when_valid_response_is_returned(mocker_get_context, mocker):
"""
Test case scenario for successful execution of ls-mac-hunt command.
Given:
- command arguments for mac hunt command
When:
- Calling `ls-mac-hunt` command
Then:
- Returns the... | 57,212 |
def print_responsedata(responsedata, mmeta, call):
"""
prints out response data according to a jinja2 template
defined in the module directory
this frontend tries to use "vyvyan/<modulename>/template.cmdln.<call>"
for its template file. if it doesn't find a call-specific template, it will
attem... | 57,213 |
def load_map(
ebsd_path: str,
min_grain_size: int = 3,
boundary_tolerance: int = 3,
use_kuwahara: bool = False,
kuwahara_tolerance: int = 5
) -> ebsd.Map:
"""Load in EBSD data and do the required prerequisite computations."""
ebsd_path = pathlib.Path(ebsd_path)
if ebsd_path.suffix == ".... | 57,214 |
def temp_session(server, *args, **kwargs):
"""
Return a context manager with a temporary session.
If no ``session_name`` is entered, :func:`get_test_session_name` will make
an unused session name.
The session will destroy itself upon closing with :meth:`Session.
kill_session()`.
Parameter... | 57,215 |
def print_logo():
"""
print random ascii art
"""
logo = []
logo.append("""
.------..------..------..------.
|S.--. ||T.--. ||O.--. ||Q.--. |
| :/\: || :/\: || :/\: || (\/) |
| :\/: || (__) || :\/: || :\/: |
| '--'S|| '--'T|| '--'O|| '--'Q|
`------'`------'`------'`------'... | 57,216 |
def validate(number):
"""Checks to see if the number provided is a valid CNPJ. This checks the
length and whether the check digits are correct."""
number = compact(number)
if not number.isdigit() or int(number) <= 0:
raise InvalidFormat()
if len(number) != 14:
raise InvalidLength()
... | 57,217 |
def allow_http_requests(requests_mock: RequestsMock) -> None:
"""A pytest fixture which allows HTTP requests to the API to pass through the requests mock."""
requests_mock.add_passthru(API_BASE_URL) | 57,218 |
def proba2float(proba, values=None, K=None, names=None):
"""Replace mu_k by a numerical value and evaluation the formula."""
if hasattr(proba, "evalf"):
if values is None and K is not None:
values = uniform_means(nbArms=K)
if names is None:
K = len(values)
na... | 57,219 |
def ripemd160(msg):
"""one-line rmd160(msg) -> bytes"""
return hashlib.new('ripemd160', msg).digest() | 57,220 |
def where(condition, a, b): # pragma: no cover
"""In a broadcasting fashion, take from `x` if `condition` is true; otherwise,
take from `y`.
Args:
condition (tensor): Condition.
a (tensor): Tensor to take from if `condition` is true.
b (tensor): Tensor to take from if `condition` i... | 57,221 |
def render_fields_from_docrules(mdts_dict, init_dict=None, search=False):
"""
Create dictionary of additional fields for form,
according to MDT's provided.
Takes optional values dict to init prepopulated fields.
"""
log.debug('Rendering fields for docrules: "%s", init_dict: "%s", search: "%s"'%... | 57,222 |
def run_ibmcloud_cmd(cmd, secrets=None, timeout=600, ignore_error=False, **kwargs):
"""
Wrapper function for `run_cmd` which if needed will perform IBM Cloud login
command before running the ibmcloud command. In the case run_cmd will fail
because the IBM cloud got disconnected, it will login and re-try.... | 57,223 |
def quartznet15x5_es(classes=36, **kwargs):
"""
QuartzNet 15x5 model for Spanish language from 'QuartzNet: Deep Automatic Speech Recognition with 1D Time-Channel
Separable Convolutions,' https://arxiv.org/abs/1910.10261.
Parameters:
----------
classes : int, default 36
Number of classif... | 57,224 |
def converge(model, k_on_state=None, image_directory=None,
pre_equilibrium_approx=False, verbose=False):
"""
Perform all convergence steps: a generic analysis of convergence
of quantities such as N_ij, R_i, k_off, and k_on.
"""
curdir = os.getcwd()
k_on_conv, k_off_conv, N_ij_conv... | 57,225 |
def create_sprite_image(images):
"""Returns a sprite image consisting of images passed as argument.
Images should be count x width x height"""
if isinstance(images, list):
images = np.array(images)
img_h = images.shape[1]
img_w = images.shape[2]
n_plots = int(np.ceil(np.sqrt(images.shape[0])))
if l... | 57,226 |
def seconds_benchmark(function_wrapper):
"""
outer wrapper function to perform inner wrap for seconds benchmark.
:param function_wrapper: The entire function object.
:return:
"""
@wraps(function_wrapper)
def wrap(*args, **kwargs):
"""
:param args: positional args
:p... | 57,227 |
def lineage(taxonomy, data):
"""
Get a standardized lineage for the given taxon id.
"""
if data["ncbi_tax_id"] in taxonomy:
return taxonomy["ncbi_tax_id"].lineage
return phy.lineage(data["ncbi_tax_id"]) | 57,228 |
def analyze(configfile, ignore_changes, snakemake_args):
"""
Perform statistical analysis on candidate taxa.\n
Additional Snakemake parameters should be passed
at the command line.
Runs:\n
'snakemake --snakefile SNAKEPATH
--configfile CONFIGFILE'
"""
cmd = get_cmd(configfile.name, s... | 57,229 |
def hasattr(object: Any, name: _str) -> _bool:
"""
The result is ``True`` if the string is the name of one of the objectβs
attributes, ``False`` if not.
""" | 57,230 |
async def _prepare():
"""Prepare EQ window to receive input"""
loc, size = await _geometry()
x = loc[0] + (size[0]//3 + random.randint(0, size[0]//3))
y = loc[1] + (size[1]//3 + random.randint(0, size[1]//3))
await _eqxdo("mousemove %d %d" % (x, y))
await _eqxdo("click 1")
await asyncio.slee... | 57,231 |
def label_accuracy_score(label_trues, label_preds, n_class):
"""Returns accuracy score evaluation result.
- overall accuracy
- mean accuracy
- mean I0U
- fwavacc
"""
hist = np.zeros((n_class, n_class))
for lt, lp in zip(label_trues, label_preds):
hist += _fast_his... | 57,232 |
def _module_fuel(mass):
"""Yields the `n+1` fuel requirements, starting with the `n+1` of `mass`."""
while True:
mass = _fuel_requirement(mass)
yield mass | 57,233 |
def candidates(address, text, confidence=0.0, support=0,
spotter='Default', disambiguator='Default',
filters=None, headers=None):
"""
Get the candidate entities from a text.
Uses the same arguments as :meth:`annotate`.
:rtype: list of surface forms
"""
payload = {... | 57,234 |
def service_account_permissions(session, service_account):
# type: (Session, ServiceAccount) -> List[ServiceAccountPermission]
"""Return the permissions of a service account."""
permissions = session.query(Permission, ServiceAccountPermissionMap).filter(
Permission.id == ServiceAccountPermissionMap.... | 57,235 |
def compete_metabolite(model, metabolite, reference_dist, fraction=0.5, allow_accumulation=True, constant=1e4):
"""
Increases the usage of a metabolite based on a reference flux distributions.
Parameters
----------
model : Model
A constraint-based model.
metabolite : cobra.Metabolite
... | 57,236 |
def init_times_list():
"""
Initializes the free times list.
"""
busy_dict = get_times_db()
busy = get_busy_times(busy_dict)
flask.session['free_times'] = get_free_times(busy,
flask.session['begin_date'],
... | 57,237 |
def check_angle_sampling(nvecs, angles):
"""
Returns a list of the index of elements of n which do not have adequate
toy angle coverage. The criterion is that we must have at least one sample
in each Nyquist box when we project the toy angles along the vector n.
Parameters
----------
nvecs ... | 57,238 |
def saveLocationHistory(history, filename):
"""Saves the given location ``history`` to the given ``filename``. See
:func:`loadLocationHistory` and :meth:`LocationHistoryPanel.getHistory`.
"""
lines = []
for loc, comment in history:
loc = '{:0.8f} {:0.8f} {:0.8f}'.format(*loc)
lines... | 57,239 |
def corrfrac(filelist):
"""Invokes validate() on the given list of file names.
Returns the fraction of correct predictions.
"""
return float(len(validate(filelist))) / len(filelist) | 57,240 |
def create_graph(workspace: str, graph_name: str, edge_table: str) -> bool:
"""Create a graph."""
resp = requests.post(
f"{root_api_endpoint()}/workspaces/{workspace}/graphs/{graph_name}",
params={"edge_table": edge_table},
)
if resp.ok:
return True
return False | 57,241 |
def main():
"""Main method of this script."""
# Use the directory that contains recordings on Dreamboxes as default.
default_directory = '/media/hdd/movie'
# Per default we want to have 50GB of free space.
min_avail_space = 50*1024
# Override defaults with values given on the command line.
... | 57,242 |
def extraer_numero_iniciativa(numero_evento: str) -> Optional[int]:
"""Algunos numeros de evento traen la iniciativa a la
que pertenecen, esta funciΓ³n intenta extraer el ID
Returns
-------
int or None
ID de iniciative o None si no existe un numero con las
caracteristicas buscadas
... | 57,243 |
def assert_le(a, b, message=""):
"""Check if a and b are equal."""
assert a <= b, "Error: %s > %s ! %s" % (a, b, message)
return | 57,244 |
def next_key(tuple_of_tuples, key):
"""Processes a tuple of 2-element tuples and returns the key which comes
after the given key.
"""
for i, t in enumerate(tuple_of_tuples):
if t[0] == key:
try:
return tuple_of_tuples[i + 1][0]
except IndexError:
... | 57,245 |
def wpe_client():
""" launches the wpe client """
wpe_main() | 57,246 |
def sort_crt(crt):
"""Sort df by CRT"""
return (crt[1],) + get_name_sortkey(crt[0]) | 57,247 |
def user_registered_sighandler(app, user, confirm_token):
"""Deactivates new users"""
changeUser = dbSession.query(User).filter(User.id == user.id).one()
newCompany = Company(company_name = user.username, email = user.email)
dbSession.add(newCompany)
dbSession.commit()
changeUser.company_name = ... | 57,248 |
def parse_args():
"""
Parses passed in CLI arguments.
Output: tuple: YouTube playlist URL string, VLC Install Directory
"""
parser = argparse.ArgumentParser(description="Streams YouTube Playlist in VLC")
parser.add_argument(
"youtube_playlist_URL",
metavar="YouTube Playlist URL",... | 57,249 |
def zd_to_airmass(zd):
""" conversion of zenith airmass into airmass assuming Pickering (2002). """
alt = 90. - zd # Altitude in degrees
return 1. / np.sin((alt + 244. / (165. + 47. * alt**1.1)) / RAD2DEG) | 57,250 |
def remove_files_on_timestamp_delta(
directory: str,
mac_type: str = "ctime",
years: int = 0,
days: int = 0,
hours: int = 0,
minutes: int = 0,
seconds: int = 0,
) -> None:
"""
Remove files older than given delta from now
"""
if not os.path.isdir(directory):
raise Fil... | 57,251 |
def create_final_generator_network(
Z, projection_layer, to_rgb_conv_layers, blocks, original_image_size, params):
"""Creates base generator network.
Args:
Z: tensor, latent vectors of shape [cur_batch_size, latent_size].
projection_layer: `Dense` layer for projection of noise into imag... | 57,252 |
def test__troe_rate_constants():
""" test chemkin_io.mechparser.reaction.calculate_rate_constants
for a reaction with only high-pressure, low-pressure, and Troe params
"""
units = chemkin_io.mechparser.reaction.units(
SYNGAS_REACTION_BLOCK)
ktp_dct = chemkin_io.mechparser.reaction.calcul... | 57,253 |
def test_trf_with_guiding_output(thr):
"""
Test the creation of ``PureParallel`` out of a transformation,
with an output parameter as a guiding array.
"""
N = 1000
coeff = 3
dtype = numpy.float32
arr_t = Type(dtype, shape=N)
trf = mul_param(arr_t, dtype)
p = PureParallel.from_t... | 57,254 |
def write_crtf(regions, filename, coordsys='fk5', fmt='.6f', radunit='deg'):
"""
Converts a `list` of `~regions.Region` to CRTF string and write to file.
See :ref:`gs-crtf`
Parameters
----------
regions : `list`
List of `~regions.Region` objects
filename : `str`
Filename in... | 57,255 |
def rss(app, request):
"""Dump the last N days' updates as an RSS feed.
"""
releases = app.db.packaging.get_recently_updated(num=40)
for release in releases:
values = dict(project_name=release['name'], version=release['version'])
url = app.urls.build('warehouse.packaging.views.project_de... | 57,256 |
def delete_redshift_cluster(config, redshift):
""" Deletes the Redshift cluster specified in config
Args:
config: a ConfigParser object
redshift: a boto3 client object for the AWS Redshift service
"""
try:
print("Deleting Redshift Cluster: ", config['CLUSTER']['IDENTIFIER'])
... | 57,257 |
def NaturalColor(C, gamma=0.8, pseudoGreen=True, night_IR=False, **kwargs):
"""
Natural Color RGB based on CIMSS method. Thanks Rick Kohrs!
(See `Quick Guide <http://cimss.ssec.wisc.edu/goes/OCLOFactSheetPDFs/ABIQuickGuide_CIMSSRGB_v2.pdf>`__ for reference)
Check out Rick Kohrs `merged GOES images <htt... | 57,258 |
def _get_adjacency_list(graph):
"""Convert a list of edges into an adjacency list."""
adj = {}
for i, j in graph:
if i in adj:
ni = adj[i]
else:
ni = adj[i] = set()
if j in adj:
nj = adj[j]
else:
nj = adj[j] = set()
ni.a... | 57,259 |
def serialize_service(sidebar, device_name, service):
"""serialize_service(sidebar_str, device_name_str, service_Service)
Serializes the service, creating the .json and .html representations of it
"""
docstring = [
create_docblock(method, "Service Method")
for method in service.methods.... | 57,260 |
def behavior_of(classname):
"""
Finds and loads the behavior class for C++ (decoded) classname or returns
None if there isn't one.
Behaviors do not have a required base class, and they may be used with
Awkward Array's ``ak.behavior``.
The search strategy for finding behavior classes is:
1... | 57,261 |
def pareto_rank(df: pd.DataFrame, objectives: list, max_rank: int = 10) -> pd.DataFrame:
"""
Rank solutions based on pareto dominance
:param df:
:param objectives:
:return: DataFrame with additional column 'pareto_rank'
"""
df['pareto_rank'] = np.nan
rank = 0
evaluating = df[objecti... | 57,262 |
def get_domain_notes(domain):
"""
Combine all domain notes if there are any.
"""
all_notes = domain.http.notes + domain.httpwww.notes + domain.https.notes + domain.httpswww.notes
all_notes = all_notes.replace(',', ';')
return all_notes | 57,263 |
def main(args=None):
"""
Main function for obtaining user arguments, controling workflow and recording log file.
Args:
None
Returns:
None
"""
### open app if need
if '--app' in sys.argv:
str_command = str(sys.executable) + " " + os.path.join(os.path.dirname(_... | 57,264 |
def add_trailing_load(axle_spacing, axle_wt, space_to_trailing_load,
distributed_load, span1_begin, span2_end, pt_load_spacing=0.5):
"""Approximates the distributed trailing load as closely spaced point loads.
The distributed trailing load is approximated as discretly spaced point
loads. The point ... | 57,265 |
def str_append(string, add):
"""Append add in end string. Example: str_append('hou', 'se'); Return='house'"""
return string + str(add) + "\n" | 57,266 |
def parse_trigger_plugin(trigger_path, plugin_config, parse_only=False):
"""Parse plugin file and return the trigger config."""
# Open and exec plugin definitions
with open(trigger_path, 'r') as f:
trigger_code = f.read()
trigger_vars = {}
exec(trigger_code, trigger_vars)
# Get trigger... | 57,267 |
def signout():
"""Signout. ιεΊγ
"""
session.pop('kb', None)
session.pop('islogin', None)
database.skb = ''
state = {
'success' : 1,
'message' : "ιεΊζε"
}
return json.dumps(state) | 57,268 |
def task_output_results(msg):
"""
This worker will forward results to the outside
exchange (typically an ADSMasterPipeline) to be
incorporated into the storage
:param msg: a protobuf containing the non-bibliographic metadata
{'bibcode': '....',
'reads': [....],
... | 57,269 |
async def make_spray(message):
"""
Creates a Source engine spray from an image.
Example::
/drawtext Hello there! | make spray
You can also upload an image as an attachment and then use this command.
"""
if not os.path.exists(VTFCMD_PATH):
raise IOError("Cannot find VTFCmd (tr... | 57,270 |
def plot_axis_angle(ax=None, a=a_id, p=p0, s=1.0, ax_s=1, **kwargs):
"""Plot rotation axis and angle.
Parameters
----------
ax : Matplotlib 3d axis, optional (default: None)
If the axis is None, a new 3d axis will be created
a : array-like, shape (4,), optional (default: [1, 0, 0, 0])
... | 57,271 |
def test_tagid_observed_but_not_reported(client, db_setup):
"""The details page for a tag that has been observed by the OMNR but
not reported by the general public should contain information
about the OMNR tag encounter but will also contain a message
indicating the tag has not been reported by the gene... | 57,272 |
def generate_hash_rates(hash_rate_parameter: int, number_of_honest_miners: int, malicious_hash_ratio: float) -> \
Tuple[List[float], List[float]]:
"""
:param number_of_honest_miners:
:param malicious_hash_ratio:
:return:
"""
honest_hash_rates = [numpy.random.poisson(hash_rate_parameter)... | 57,273 |
def test_update_as_admin(api_rf, team_member_factory):
"""
Admins should be able to update other members' information.
"""
admin = team_member_factory(is_admin=True)
member = team_member_factory(team=admin.team)
data = {
'pk': member.pk,
'member_type': models.TeamMember.COACH,
... | 57,274 |
def _get_unique_entity(
entity_name: str, collection: Sequence[E], ensure_exists: bool = False
) -> Optional[E]:
"""Type annotations in case of `ensure_exists=False`."""
... | 57,275 |
def create_function(treatment_system, parameter, values):
"""
Creates a function based on user input
"""
func = str(treatment_system.loc[0, parameter])
func = func.replace(' ', '')
for key, value in values.items():
func = func.replace(key, str(value))
return func | 57,276 |
def _ResourceGraphvizNode(resource, request, resource_to_index):
"""Returns the node description for a given resource.
Args:
resource: Resource.
request: RequestData associated with the resource.
resource_to_index: {Resource: int}.
Returns:
A string describing the resource in graphviz format.
... | 57,277 |
def checker_with_multi_thread(hosts):
"""
multi thread analyze
:param hosts: [[]]
:return:
"""
import threading
for item in hosts:
checker = SSLChecker()
t = threading.Thread(target=checker.show_result, args=({'hosts': item},))
t.setDaemon(False)
t.start() | 57,278 |
def unformat(combination: str) -> str:
"""Unformats a formatted string to it's original state"""
return str(combination).replace("<", "").replace(">", "") | 57,279 |
def common_base(cls: type, *clss: type) -> type:
"""
Overview:
Get common base class of the given classes.
Only ``__base__`` is considered.
Arguments:
- cls (:obj:`type`): First class.
- clss (:obj:`type`): Other classes.
Returns:
- base (:obj:`type`): Common ba... | 57,280 |
def test_stack_wrong_name(mock_aws_stack_exists):
"""Create a new stack"""
with cfhelper_mocks() as (boto3_mock, session_mock, client_mock):
with pytest.raises(
Exception, match=r"Could not find stack config named 'IamNotAStack'"
):
call_cfhelper(
[
... | 57,281 |
def get_all_configs() -> Response:
"""Get and return all configs by name"""
return flask.jsonify(config.get_config_names()) | 57,282 |
def check_shapes():
"""Check shapes of everything in model files"""
for model in ["smbld_model/new_model/model.pkl", SMPL_MODEL_PATH]:
print("----")
print(model)
with open(model, "rb") as f:
dd = pkl.load(f, fix_imports = True, encoding="latin1")
for k in dd.keys(... | 57,283 |
def moves_to(target, result_func):
"""A simple co-routine that yields a result and transitions to another co-routine."""
yield
yield result_func(target) | 57,284 |
def dewpoint(temperature, humidity, *, model='hardy', isdew=True):
"""Calculate the dew point.
Parameters
----------
temperature : :class:`float`
The temperature [degree C].
humidity : :class:`float`
The humidity [%RH].
model : :class:`str`
The dew point model, valid mod... | 57,285 |
def parse_list_marker(line, offset):
"""
Parse a list marker and return data on the marker (type,
start, delimiter, bullet character, padding) or null.
"""
rest = line[offset:]
spaces_after_marker = None
data = ListData()
if reHrule.search(rest):
return None
match = re.... | 57,286 |
def resize(img, height=800, allways=False):
"""Resize image to given height."""
if (img.shape[0] > height or allways):
rat = height / img.shape[0]
return cv.resize(img, (int(rat * img.shape[1]), height))
return img | 57,287 |
def _size_to_bytes(size):
"""
Parse a string with a size into a number of bytes. I.e. parses "10m", "10MB", "10 M" and other variations into the
number of bytes in ten megabytes. Floating-point numbers are rounded to the nearest byte.
:type size: ``str``
:param size: The size to parse, given as a string with byte... | 57,288 |
def writetofile(filename, string_to_write):
"""Takes a string and writes to a filename
TODO: Figure out why os.path.exists is not WORKING
Example: writetofile("myfile.html", htmlbuffer)
"""
if os.path.exists(filename):
return f"Error: {filename} exists already"
else:
with open(f... | 57,289 |
def process_brown():
"""Read, convert and save the Brown corpus"""
tags = []
logging.info("Reading Brown corpus....")
for word, tag in nltk.corpus.brown.tagged_words(tagset="universal"):
t = Tag(word, tag)
tags.append(t)
logging.info("Saving....")
with open("Data/brown.pkl", "w")... | 57,290 |
def transform_to_tensor_per_dataset(feature, label, drug,device, basal_expression_file):
"""
:param feature: features like pertid, dosage, cell id, etc. will be used to transfer to tensor over here
:param label:
:param drug: ??? a drug dictionary mapping drug name into smile strings
:param device: ... | 57,291 |
def isbn_gendigit (numStr):
"""
(string)-->(string + 1-digit)
Generates the 10th digit in a given 9-digit isbn string. Multiplies the values of individual digits within the given 9-digit string to determine the 10th digit.
Prints the original string with its additional 10th digit.
('123456788')-->12... | 57,292 |
def count_unique_sequences_per_otu(otu_ids, otu_map_file, input_seqs_file):
"""Counts unique sequences per-OTU for a given set of OTUs
otu_ids: a set of OTU IDs
otu_map_file: file-like object in the format of an OTU map
input_seqs_file: FASTA containing sequences that were used to generate
... | 57,293 |
def fetch_add_portmapping_services() -> Tuple[UPnPServiceNames, ...]:
"""
:return: returns the available devices and services for which the action 'AddPortMapping' exists
"""
devices = upnpclient.discover()
if not devices:
raise NoPortMapServiceFound("No UPnP devices available")
service... | 57,294 |
def is_valid_group(group_name, nova_creds):
"""
Checks to see if the configuration file contains a SUPERNOVA_GROUP
configuration option.
"""
valid_groups = [value['SUPERNOVA_GROUP'] for key, value in
nova_creds.items() if 'SUPERNOVA_GROUP'
in nova_creds[key].k... | 57,295 |
def update_document_with_partial(doc_id, doc, object_type, *, retry_on_conflict=0):
"""
Makes a request to ES to update an existing document
Args:
doc_id (str): The ES document id
doc (dict): Full or partial ES document
object_type (str): The object type to update (post, comment, et... | 57,296 |
def read_config(env):
"""
Read the build configuration file and creates a dictionary to be used
throughout the project
Args:
env: Environmental variable where the config file is
Return:
Dictionary of the configuration
Raises:
ConfigurationError
"""
#Open the c... | 57,297 |
def Make_scroll_bar(self, scroll_bar):
"""
Make a scroll_bar for a Text object.
For internal use only. This function is therefore also not imported by __init__.py
"""
if isinstance(scroll_bar, Slider):
scroll_bar.right = self.width - self.text_offset[0]
scroll_bar.centery = math.floo... | 57,298 |
def value_iteration(env, rewards):
""" Computes a policy using value iteration given a list of rewards (one reward per state) """
n_states = env.observation_space.n
n_actions = env.action_space.n
V_states = np.zeros(n_states)
theta = 1e-8
gamma = .9
maxiter = 1000
policy = np.zeros(n_sta... | 57,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.