content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def load_appdata():
"""load application data from json file
"""
try:
_in = open(FNAME)
except FileNotFoundError:
return
with _in:
appdata = json.load(_in)
return appdata | 5,331,600 |
def compute_couplings(models_a, models_b):
"""
Given logistic models for two multiple sequence alignments, calculate all
intermolecular coupling strengths between residues.
The coupling strength between positions i and j is calculated as the 2-norm
of the concatenation of the coefficient submatrices... | 5,331,601 |
def update_checkout_line(request, checkout, variant_id):
"""Update the line quantities."""
if not request.is_ajax():
return redirect("checkout:index")
checkout_line = get_object_or_404(checkout.lines, variant_id=variant_id)
discounts = request.discounts
status = None
form = ReplaceCheck... | 5,331,602 |
def merge_df(
df: Optional[pd.DataFrame], new_df: Optional[pd.DataFrame], how="left"
):
"""
join two dataframes. Assumes the dataframes are indexed on datetime
Args:
df: optional dataframe
new_df: optional dataframe
Returns:
The merged dataframe
"""
if df is None:
... | 5,331,603 |
async def test_heartbeat_unload(opp):
"""Test that the heartbeat is deactivated when the last config entry is removed."""
device = get_device("Office")
_, mock_entry = await device.setup_entry(opp)
await opp.async_block_till_done()
await opp.config_entries.async_remove(mock_entry.entry_id)
awa... | 5,331,604 |
def render(a: Optional[str], b: Optional[str], writer: IO[str]) -> None:
"""
Renders the differences between `a` and `b` to `writer`.
Treats the inputs as marked-up data if possible.
"""
ta, da = deserialize_value(a)
tb, db = deserialize_value(b)
tv = ta or tb
if not tv:
# No... | 5,331,605 |
def load_settings(settings_path: str = CHAOSTOOLKIT_CONFIG_PATH) -> Settings:
"""
Load chaostoolkit settings as a mapping of key/values or return `None`
when the file could not be found.
"""
if not os.path.exists(settings_path):
logger.debug(
"The Chaos Toolkit settings file coul... | 5,331,606 |
def _is_leaf(tree: DecisionTreeClassifier, node_id: int) -> bool:
"""
Determines if a tree node is a leaf.
:param tree: an `sklearn` decision tree classifier object
:param node_id: an integer identifying a node in the above tree
:return: a boolean `True` if the node is a leaf, `False` otherwise
... | 5,331,607 |
async def commission_reset(bot, context):
"""Resets a given user's post cooldown manually."""
advertisement_data = await _get_advertisement_data(bot, context.guild)
deleted_persistence = data.get(
bot, __name__, 'recently_deleted', guild_id=context.guild.id, default={})
user_id = context.argumen... | 5,331,608 |
def prog_start(prog):
"""
This functions starts a `prog` by sending a command to the slave.
The program can only be started if the program is currently not running.
If the slave is offline an error will be returned.
Parameters
----------
prog: ProgramModel
A valid `ProgramMo... | 5,331,609 |
def set_out_string():
"""Set output string
This method checks if an output string has been specified and if not
creates and ouput string from the input string and the mode
"""
if isinstance(opts.output, type(None)):
opts.output = splitext(opts.input)[0] + '_' + opts.mode | 5,331,610 |
def test_sample_problems_auto_1d_maximization(max_iter, max_response, error_lim, model_type, capsys):
"""
solve a sample problem in two different conditions.
test that auto method works for a particular single-covariate (univariate) function
"""
# define data
x_input = [(0.5, 0,
... | 5,331,611 |
def partition_round(elms, percent, exact=-1, total=100, *args, **kwargs):
"""
Partitions dataset in a predictable way.
:param elms: Total Number of elements
:type elms: Integer
:param percent: Percentage of problem space to be processed on one device
:param type: Integer
:param exact: Flag ... | 5,331,612 |
def heatmap_numeric_w_dependent_variable(df, dependent_variable):
"""
Takes df, a dependant variable as str
Returns a heatmap of all independent variables' correlations with dependent variable
"""
plt.figure(figsize=(10, 5.5))
figure = sns.heatmap(
df.corr()[[dependent_variable]].sort_v... | 5,331,613 |
def compute_stats(
cfg: Dict[str, dict],
dem: xr.Dataset,
ref: xr.Dataset,
final_dh: xr.Dataset,
display: bool = False,
final_json_file: str = None,
):
"""
Compute Stats on final_dh
:param cfg: configuration dictionary
:type cfg: dict
:param dem: dem raster
:type dem: xr... | 5,331,614 |
def _handle_rpm(
rpm: Rpm,
universe: str,
repo_url: str,
rpm_table: RpmTable,
all_snapshot_universes: Set[str],
cfg: DownloadConfig,
) -> Tuple[Rpm, MaybeStorageID, float]:
"""Fetches the specified RPM from the repo DB and downloads it if needed.
Returns a 3-tuple of the hydrated RPM, s... | 5,331,615 |
def main(options,args):
"""Extract mutations from a multiple sequence alignment"""
import PEATDB.sequence_alignment as SA
if not options.fasta:
alignment=SA.read_clustal_aln_file(args[0])
else:
alignment=SA.read_fasta_aln_file(args[0])
print sorted(alignment.keys())
HEWL_seq=ali... | 5,331,616 |
def test_add_list_s3_repos() -> None:
"""
Tests adding and listing repos from S3.
"""
client = RedunClient()
s3_client = boto3.client("s3", region_name="us-east-1")
s3_client.create_bucket(Bucket="example-repo")
file = File("s3://example-repo/potato/redun.ini")
file.write(DEFAULT_REDUN... | 5,331,617 |
def numpy2seq(Z, val=-1):
"""Appends the minimal required amount of zeroes at the end of each
array in the jagged array `M`, such that `M` looses its jagedness."""
seq = []
for z in t2n(Z).astype(int):
i = np.where(z==val)[0]
if i.size == 0:
seq += [z.tolist()]
else... | 5,331,618 |
def winner(board):
"""Detirmine the game's winner."""
WAYS_TO_WIN = ((0, 1, 2),
(3, 4, 5),
(6, 7, 8),
(0, 3, 6),
(1, 4, 7),
(2, 5, 8),
(0, 4, 8),
(2, 4, 6))
for row in WAYS_TO_WIN:
if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
winner = board[row[0]]
return winner
... | 5,331,619 |
def compute_inv_propensity(train_file, A, B):
"""
Compute Inverse propensity values
Values for A/B:
Wikpedia-500K: 0.5/0.4
Amazon-670K, Amazon-3M: 0.6/2.6
Others: 0.55/1.5
"""
train_labels = data_utils.read_sparse_file(train_file)
inv_propen = xc_metri... | 5,331,620 |
def test_ap_wpa2_eap_gpsk(dev, apdev):
"""WPA2-Enterprise connection using EAP-GPSK"""
params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
hostapd.add_ap(apdev[0]['ifname'], params)
id = eap_connect(dev[0], apdev[0], "GPSK", "gpsk user",
password="abcdefghijklmnop0123456789abcdef... | 5,331,621 |
def tanh(x):
"""
Returns the cos of x.
Args:
x (TensorOp): A tensor.
Returns:
TensorOp: The tanh of x.
"""
return TanhOp(x) | 5,331,622 |
def importBodyCSVDataset(testSplit: float, local_import: bool):
"""Import body dataset as numpy arrays from GitHub if available, or local dataset otherwise.
Args:
testSplit (float, optional): Percentage of the dataset reserved for testing. Defaults to 0.15. Must be between 0.0 and 1.0.
"""
asse... | 5,331,623 |
def download_extract(database_name, data_path):
"""
Download and extract database
:param database_name: Database name
"""
DATASET_ML1M = 'ml-1m'
if database_name == DATASET_ML1M:
url = 'http://files.grouplens.org/datasets/movielens/ml-1m.zip'
hash_code = 'c4d9eecfca2ab87c1945afe... | 5,331,624 |
def list_systeminsights_hardware_json():
"""print: get_systeminsights_system_info_json."""
skip = 0
limit = 100
idlist = get_systems_id()
for system_id in idlist:
response = get_systeminsights_system_info_json(system_id, limit, skip)
if len(response) == 0:
response = {'... | 5,331,625 |
def mvstdtprob(a, b, R, df, ieps=1e-5, quadkwds=None, mvstkwds=None):
"""
Probability of rectangular area of standard t distribution
assumes mean is zero and R is correlation matrix
Notes
-----
This function does not calculate the estimate of the combined error
between the underlying multi... | 5,331,626 |
def build_dataloaders(
cfg: CfgNode,
batch_size: Union[int, Iterable[int]],
) -> Dict[str, Callable]:
"""
Get iterators of built-in datasets.
Args:
cfg: CfgNode instance that requests built-in datasets.
batch_size (int or sequence): The number of examples in one mini-bat... | 5,331,627 |
def get_activity(
iterator,
*,
perspective,
garbage_class,
dtype=np.bool,
non_sil_alignment_fn=None,
debug=False,
use_ArrayIntervall=False,
):
"""
perspective:
Example:
'global_worn' -- global perspective for worn ('P')
... | 5,331,628 |
def dropNested(text, openDelim, closeDelim):
"""
A matching function for nested expressions, e.g. namespaces and tables.
"""
openRE = re.compile(openDelim, re.IGNORECASE)
closeRE = re.compile(closeDelim, re.IGNORECASE)
# partition text in separate blocks { } { }
spans = [] #... | 5,331,629 |
def is_rotational(block_device: str) -> bool:
"""
Checks if given block device is "rotational" (spinning rust) or
solid state block device.
:param block_device: Path to block device to check
:return: True if block device is a rotational block device,
false otherwise
"""
base_... | 5,331,630 |
def format_exc(limit=None):
"""Like print_exc() but return a string. Backport for Python 2.3."""
try:
etype, value, tb = sys.exc_info()
return ''.join(traceback.format_exception(etype, value, tb, limit))
finally:
etype = value = tb = None | 5,331,631 |
def make_dpl_from_construct(construct,showlabels=None):
""" This function creats a dictionary suitable for
input into dnaplotlib for plotting constructs.
Inputs:
construct: a DNA_construct object
showlabels: list of part types to show labels for. For example, [AttachmentSite,Terminator]"""
#TODO... | 5,331,632 |
def load_config(path: str, env=None):
"""
Load a YAML config file and replace variables from the environment
Args:
path (str): The resource path in the form of `dir/file` or `package:dir/file`
Returns:
The configuration tree with variable references replaced, or `False` if the
f... | 5,331,633 |
def ls(manager: Manager):
"""List network names, versions, and optionally, descriptions."""
for n in manager.list_networks():
click.echo('{}\t{}\t{}'.format(n.id, n.name, n.version)) | 5,331,634 |
def update_service(
*, db_session: Session = Depends(get_db), service_id: PrimaryKey, service_in: ServiceUpdate
):
"""Update an existing service."""
service = get(db_session=db_session, service_id=service_id)
if not service:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,... | 5,331,635 |
def plotsetup():
### PARAMETERS FOR MATPLOTLIB :
"""
Parameters
----------
TODO
Returns
-------
TODO
"""
mpl.rcParams['font.size'] = 12.
mpl.rcParams['font.family'] = 'sans-serif'
mpl.rcParams['axes.labelsize'] = 12.
mpl.rcParams['xtick.labelsize']... | 5,331,636 |
def import_flow_by_ref(flow_strref):
"""Return flow class by flow string reference."""
app_label, flow_path = flow_strref.split('/')
return import_string('{}.{}'.format(get_app_package(app_label), flow_path)) | 5,331,637 |
def display_cusum(
df: pd.DataFrame,
target: str,
threshold: float,
drift: float,
external_axes: Optional[List[plt.Axes]] = None,
):
"""Cumulative sum algorithm (CUSUM) to detect abrupt changes in data
Parameters
----------
df : pd.DataFrame
Dataframe
target : str
... | 5,331,638 |
def _escape_value(value):
"""Escape a value."""
value = value.replace(b"\\", b"\\\\")
value = value.replace(b"\n", b"\\n")
value = value.replace(b"\t", b"\\t")
value = value.replace(b'"', b'\\"')
return value | 5,331,639 |
def find(*objects: Iterable[object]):
"""Sometimes you know the inputs and outputs for a procedure, but you don't remember the name.
methodfinder.find tries to find the name.
>>> import methodfinder
>>> import itertools
>>> methodfinder.find([1,2,3]) == 6
sum([1, 2, 3])
>>> methodfinder.fin... | 5,331,640 |
def join_returns(cfg, arg_names, function_ast=None):
"""Joins multiple returns in a CFG into a single block
Given a CFG with multiple return statements, this function will replace the
returns by gotos to a common join block.
"""
join_args = [ir.Argument(function_ast, info=n, name=n) for n in arg_na... | 5,331,641 |
def _cmor_reformat(config, obs_list):
"""Run the cmorization routine."""
logger.info("Running the CMORization scripts.")
# master directory
raw_obs = config["rootpath"]["RAWOBS"][0]
# set the reformat scripts dir
reformat_scripts = os.path.dirname(os.path.abspath(__file__))
logger.info("Us... | 5,331,642 |
def write_block_summary_report(course_data):
"""
Generate a CSV file containing a summary of the xBlock usage
Arguments:
course_data (list of dicts): a list of course_data objects
Returns:
Nothing
"""
(block_summary_counts, unique_course_counts) = _get_block_summary_totals(cour... | 5,331,643 |
def save_json(object: Any, path: Union[str, Path]) -> None:
"""Save .json file to given path"""
import json
path = Path(path).resolve()
path.parent.mkdir(parents=True, exist_ok=True)
with open(str(path), 'w') as f:
json.dump(object, f) | 5,331,644 |
def test_command_missing_args(run_line):
"""
Runs get-identities without values, confirms exit_code 2
"""
result = run_line("globus get-identities", assert_exit_code=2)
assert "Missing argument" in result.stderr | 5,331,645 |
def get_all():
"""
Returns list of all tweets from this server.
"""
return jsonify([t.to_dict() for t in tweet.get_all()]) | 5,331,646 |
def proportion_sig_beg_to_start_of_ground(ds):
"""
The total energy from signal beginning to the start of the ground peak,
normalized by total energy of the waveform. Ground peak assumed to be the last peak.
"""
from carbonplan_trace.v1.glas_preprocess import select_valid_area # avoid circular impo... | 5,331,647 |
def post_file(url, file_path, username, password):
"""Post an image file to the classifier."""
kwargs = {}
if username:
kwargs['auth'] = requests.auth.HTTPBasicAuth(username, password)
file = {'file': open(file_path, 'rb')}
response = requests.post(
url,
files=file,
... | 5,331,648 |
def bias_init_with_prob(prior_prob):
""" initialize conv/fc bias value according to giving probablity"""
bias_init = float(-np.log((1 - prior_prob) / prior_prob))
return bias_init | 5,331,649 |
def parse_number(s, start_position):
"""
If an integer or float begins at the specified position in the
given string, then return a tuple C{(val, end_position)}
containing the value of the number and the position where it ends.
Otherwise, raise a L{ParseError}.
"""
m = _PARSE_NUMBER_VALUE.ma... | 5,331,650 |
def training_data_provider(train_s, train_t):
"""
Concatenates two lists containing adata files
# Parameters
train_s: `~anndata.AnnData`
Annotated data matrix.
train_t: `~anndata.AnnData`
Annotated data matrix.
# Returns
Concatenated Annota... | 5,331,651 |
def _build_trees(base_estimator, estimator_params, params, X, y, sample_weight,
tree_state, n_trees, verbose=0, class_weight=None,
bootstrap=False):
""" Fit a single tree in parallel """
tree = _make_estimator(
_get_value(base_estimator), estimator_par... | 5,331,652 |
def _add_to_arguments(arg_dict, argument_name, argument_value):
"""Add a variable to the argument dict that will be requested to the event generation API.
Args:
arg_dict: dictionary with the arguments.
argument_name: name of the variable in the API (key in the dict).
argument_value: val... | 5,331,653 |
def select_privilege():
"""Provide a select Privilege model for testing."""
priv = Privilege(
database_object=DatabaseObject(name="one_table", type=DatabaseObjectType.TABLE),
action=Action.SELECT,
)
return priv | 5,331,654 |
def plot_gaia_sources_on_survey(
tpf,
target_gaiaid,
gaia_sources=None,
fov_rad=None,
depth=0.0,
kmax=1.0,
sap_mask="pipeline",
survey="DSS2 Red",
verbose=True,
ax=None,
outline_color="C6", # pink
figsize=None,
pix_scale=TESS_pix_scale,
**mask_kwargs,
):
"""P... | 5,331,655 |
def getLinkToSong(res):
"""
getLinkToSong(res): link to all songs
:param: res: information about the playlist -> getResponse(pl_id)
:returns: list of links to each song
"""
return res['items'][0]['track']['external_urls']['spotify'] | 5,331,656 |
def entropy_sampling(classifier, X, n_instances=1):
"""Entropy sampling query strategy, uses entropy of all probabilities as score.
This strategy selects the samples with the highest entropy in their prediction
probabilities.
Args:
classifier: The classifier for which the labels are to be ... | 5,331,657 |
def browser(browserWsgiAppS):
"""Fixture for testing with zope.testbrowser."""
assert icemac.addressbook.testing.CURRENT_CONNECTION is not None, \
"The `browser` fixture needs a database fixture like `address_book`."
return icemac.ab.calexport.testing.Browser(wsgi_app=browserWsgiAppS) | 5,331,658 |
def parse_playing_now_message(playback):
"""parse_playing_now_message
:param playback: object
:returns str
"""
track = playback.get("item", {}).get("name", False)
artist = playback.get("item", {}).get("artists", [])
artist = map(lambda a: a.get("name", ""), artist)
artist = ", ".join(l... | 5,331,659 |
def test_in_execution(test_plan_uuid):
"""
Executor->Curator
Test in execution: executor responses with the Test ID that can be used in a future test cancellation
{ "test-id": <test_id> }(?)
:param test_plan_uuid:
:return:
"""
# app.logger.debug(f'Callback received {request.path}, contai... | 5,331,660 |
def reset_state(environ):
"""Reset module and class level runtime state.
To make sure that each test has the same starting conditions, we reset
module or class level datastructures that maintain runtime state.
This resets:
- ``model.Property._FIND_METHODS_CACHE``
- ``model.Model._kind_map``
... | 5,331,661 |
def load_remote_image(image_url):
"""Loads a remotely stored image into memory as an OpenCV/Numpy array
Args:
image_url (str): the URL of the image
Returns:
numpy ndarray: the image in OpenCV format (a [rows, cols, 3] BGR numpy
array)
"""
response = requests.get... | 5,331,662 |
def test_adjacent_vectors_not_found(vector_field, flawed_adjacency):
"""
Adjacency is wrong.
"""
with pytest.raises(KeyError):
for key in vector_field.keys():
adjacent_vectors(vector_field, flawed_adjacency[key]) | 5,331,663 |
def checkNotice(bot):
"""
주기적으로 Notice를 읽어 최신 정보가 있으면, 사용자들에게 전송한다.
:return:
"""
global g_notice_list
global g_chat_id_db
updateNoticeList()
# dict_chat_id = updateListenerList(bot)
l = g_chat_id_db.getAllChatIdDb()
for n_item in g_notice_list:
tmp_msg_1 = makeNoticeS... | 5,331,664 |
def evlt(inp : str) -> int:
""" Evaluates the passed string and returns the value if
successful, otherwise raises an error """
operand = [] # stack for operands
operator = [] # stack for operators + parentheses
i = 0 # loop variable, cannot do range because have to increment dynamically
if i... | 5,331,665 |
def test_push_doesnt_happen_when_fetched_repo_has_zero_commits(instance, monkeypatch):
"""Test if push is not called when repository is correctly fetched and contains zero commits"""
def raise_(*args, **kwargs):
raise Exception()
fake_remote = flexmock(push=raise_)
monkeypatch.setattr(instance... | 5,331,666 |
def is_dir(dirname):
"""Checks if a path is an actual directory"""
if not os.path.isdir(dirname):
msg = "{0} is not a directory".format(dirname)
raise argparse.ArgumentTypeError(msg)
else:
return dirname | 5,331,667 |
def _create_preactivation_hook(activations):
"""
when we add this hook to a model's layer, it is called whenever
it is about to make the forward pass
"""
def _linear_preactivation_hook(module, inputs):
activations.append(inputs[0].cpu())
return _linear_preactivation_hook | 5,331,668 |
def import_by_path(path):
"""
Given a dotted/colon path, like project.module:ClassName.callable,
returns the object at the end of the path.
"""
module_path, object_path = path.split(":", 1)
target = importlib.import_module(module_path)
for bit in object_path.split("."):
target = geta... | 5,331,669 |
def ordered_links(d, k0, k1):
"""
find ordered links starting from the link (k0, k1)
Parameters
==========
d : dict for the graph
k0, k1: adjacents nodes of the graphs
Examples
========
>>> from active_nodes import ordered_links
>>> d = {0:[1,4], 1:[0,2], 2:[1,3], 3:[2,4], 4:... | 5,331,670 |
def _exceeded_threshold(number_of_retries: int, maximum_retries: int) -> bool:
"""Return True if the number of retries has been exceeded.
Args:
number_of_retries: The number of retry attempts made already.
maximum_retries: The maximum number of retry attempts to make.
Returns:
True... | 5,331,671 |
def main(argv):
"""Go main."""
date = datetime.date(int(argv[1]), int(argv[2]), int(argv[3]))
os.chdir("/i/0/cli")
for zone in glob.glob("*"):
os.chdir(zone)
for fn in glob.glob("*.cli"):
do(fn, date)
os.chdir("..") | 5,331,672 |
def _get_and_check_response(method, host, url, body=None, headers=None, files=None, data=None, timeout=30):
"""Wait for the HTTPS response and throw an exception if the return
status is not OK. Return either a dict based on the
HTTP response in JSON, or if the response is not in JSON format,
return a tu... | 5,331,673 |
def moveb_m_human(agents, self_state, self_name, c, goal):
"""
This method implements the following block-stacking algorithm:
If there's a block that can be moved to its final position, then
do so and call move_blocks recursively. Otherwise, if there's a
block that needs to be moved and can be moved... | 5,331,674 |
def test_bootstrap_transformers_panel_format(
transformer_class, return_actual, expected_index
):
"""Tests that the final panel has the right index."""
transformer = transformer_class(n_series=2, return_actual=return_actual)
y_hat = transformer.fit_transform(y)
assert expected_index.equals(y_hat.ind... | 5,331,675 |
def send_credential_without_confirmed_password(page_users, new_user) -> None:
"""I send the credential without the confirmed password."""
page_users.set_user(new_user)
# Fill the fields
p_action = FillUserAction(_page=page_users)
p_action.fill_name() \
.fill_password()
del p_action
... | 5,331,676 |
def create_initialized_headless_egl_display():
"""Creates an initialized EGL display directly on a device."""
devices = EGL.eglQueryDevicesEXT()
if os.environ.get("EGL_DEVICE_ID", None) is not None:
devices = [devices[int(os.environ["EGL_DEVICE_ID"])]]
for device in devices:
display = EGL.eglGetPlatform... | 5,331,677 |
def BooleanVar(default, callback=None):
"""
Return a new (initialized) `tkinter.BooleanVar`.
@param default the variable initial value
@param callback function to invoke whenever the variable changes its value
@return the created variable
"""
return _var(tkinter.BooleanVar, default, callbac... | 5,331,678 |
def parse_header(source):
"""Copied from textgrid.parse_header"""
header = source.readline() # header junk
m = re.match('File type = "([\w ]+)"', header)
if m is None or not m.groups()[0].startswith('ooTextFile'):
raise ValueError('The file could not be parsed as a Praat text file as '
... | 5,331,679 |
async def setup_private_registry_async(
loop: asyncio.BaseEventLoop,
table_client: azure.storage.table.TableService,
ipaddress: str, container: str, registry_archive: str,
registry_image_id: str) -> None:
"""Set up a docker private registry if a ticket exists
:param asyncio.BaseE... | 5,331,680 |
def create_amsterdam(*args):
"""
Creates a new droplet with sensible defaults
Usage:
[name]
Arguments:
name: (optional) name to give the droplet; if missing, current timestamp
"""
name = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H-%M-%S.%f")
try:
name = args[0]
... | 5,331,681 |
def convert_inp(float_inp):
"""
Convert inp from decimal value (0.000, 0.333, 0.667, etc) to (0.0, 0.1, 0.2) for cleaner display.
:param float float_inp: inning pitching float value
:return:
"""
# Split inp into integer and decimal parts
i_inp, d_inp = divmod(float_inp, 1)
d_inp = d_in... | 5,331,682 |
def plot(pulse: PulseTemplate,
parameters: Dict[str, Parameter]=None,
sample_rate: Real=10,
axes: Any=None,
show: bool=True,
plot_channels: Optional[Set[ChannelID]]=None,
plot_measurements: Optional[Set[str]]=None,
stepped: bool=True,
maximum_point... | 5,331,683 |
def is_ipv4(line):
"""检查是否是IPv4"""
if line.find("ipv4") < 6: return False
return True | 5,331,684 |
def format_ica_lat(ff_lat):
"""
conversão de uma latitude em graus para o formato GGMM.mmmH
@param ff_lat: latitude em graus
@return string no formato GGMM.mmmH
"""
# logger
# M_LOG.info(">> format_ica_lat")
# converte os graus para D/M/S
lf_deg, lf_min, lf_seg = deg2dms(ff_lat)
... | 5,331,685 |
def fixture_git_dir():
"""Create tmpdir and return its file name."""
tmpdir = tempfile.mkdtemp()
yield tmpdir
# Cleanup
try:
os.rmdir(tmpdir)
except FileNotFoundError:
pass | 5,331,686 |
def loadData (x_file="ass1_data/linearX.csv", y_file="ass1_data/linearY.csv"):
"""
Loads the X, Y matrices.
Splits into training, validation and test sets
"""
X = np.genfromtxt(x_file)
Y = np.genfromtxt(y_file)
Z = [X, Y]
Z = np.c_[X.reshape(len(X), -1), Y.reshape(len(Y), -1)]
np.ra... | 5,331,687 |
async def retrieve_users():
"""
Retrieve all users in collection
"""
users = []
async for user in user_collection.find():
users.append(user_parser(user))
return users | 5,331,688 |
def config():
"""
Commands for the configuration.
Default config file: ~/.padre.cfg
""" | 5,331,689 |
def get_file_hash(path):
"""파일 해쉬 구하기."""
hash = None
md5 = hashlib.md5()
with open(path, 'rb') as f:
data = f.read()
md5.update(data)
hash = md5.hexdigest()
info("get_file_hash from {}: {}".format(path, hash))
return hash | 5,331,690 |
def apply_repro_analysis(dataset, thresholds=[3.0], method = 'crfx'):
"""
perform the reproducibility analysis according to the
"""
from nipy.labs.spatial_models.discrete_domain import \
grid_domain_from_binary_array
n_subj, dimx, dimy = dataset.shape
func = np.reshape(dataset,(n... | 5,331,691 |
def api_root(request):
"""
Logging root
"""
rtn = dict(
message="Hello, {}. You're at the logs api index.".format(request.user.username),
)
return Response(rtn) | 5,331,692 |
def test_weekly__Weekly____call____3(DateTime, interval_start, interval_end):
"""It returns an empty iterable if the recurrence should start after ...
... `interval_end`.
"""
assert ([] == list(Weekly(
DateTime(2014, 5, 1, 21, 45))(interval_start, interval_end))) | 5,331,693 |
def load_data(filename: str):
"""
Load house prices dataset and preprocess data.
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector (prices) - either as a single
DataFrame or a Tuple[DataFrame, Series]
"""
... | 5,331,694 |
def parse_esim_inst(line):
"""Parse a single line of an e-sim trace.
Keep the original line for debugging purposes.
>>> i0 = parse_esim_inst('0x000000 b.l 0x0000000000000058 - pc <- 0x58 - nbit <- 0x0')
>>> ex0 = {'pc': 0, 'AN': False, 'instruction': 'b.l', 'line': '0x000000 ... | 5,331,695 |
def getcollength(a):
"""
Get the length of a matrix view object
"""
t=getType(a)
f={'mview_f':vsip_mgetcollength_f,
'mview_d':vsip_mgetcollength_d,
'mview_i':vsip_mgetcollength_i,
'mview_si':vsip_mgetcollength_si,
'mview_uc':vsip_mgetcollength_uc,
'cmview_... | 5,331,696 |
def process_files( optD, fileL, fileG, **kwargs ):
"""
Apply -g and -d options to the 'fileL' list, in place. The order
of 'fileL' is retained, but each glob list is sorted by ascending file
date stamp. If 'fileG' is not None, it will be filled with the files
glob'ed using the -G option, if presen... | 5,331,697 |
def test_list_date_white_space_nistxml_sv_iv_list_date_white_space_1_3(mode, save_output, output_format):
"""
Type list/date is restricted by facet whiteSpace with value collapse.
"""
assert_bindings(
schema="nistData/list/date/Schema+Instance/NISTSchema-SV-IV-list-date-whiteSpace-1.xsd",
... | 5,331,698 |
def test_plotcals():
"""calibration param inspector routine with sensible default values"""
mydat = mkh5.mkh5(TEST_H5)
mydat.reset_all() # start fresh
mydat.create_mkdata(S01["gid"], S01["eeg_f"], S01["log_f"], S01["yhdr_f"])
# This is a pre-calibration inspector ... viewer only like garv
myd... | 5,331,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.