content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _check_axis_valid(axes, ndim):
"""
Checks axes are valid given ndim, and returns axes that can be passed
to the built-in operator (non-negative, int or tuple)
"""
if axes is None:
axes = F.make_range(ndim)
return axes
if isinstance(axes, (tuple, list)):
axes = tuple(m... | 53,100 |
def wait_for_running( max_timeout=60 ):
""" wait for htcondor to be running
Args:
max_timeout: max time to wait
Returns:
boolean, true for success
Raises:
RuntimeError if the daemon is not up before the timeout
"""
logger.info("waiting for the condor daemon ...")
... | 53,101 |
def before_request():
"""
Called at the beginning of every request to set the global application context.
"""
# Reset the user information that is saved in the global context. If the session
# already contains user information, use that to populate the global context, otherwise
# leave it unset.... | 53,102 |
def _create_cigale_in(photom_cat:Table, zmin:float = 0.01, zmax:float=0.35, n_z:int = 35, cigale_input:str = "cigin_minz_zfrb.fits")->Table:
"""
Take the photometry table and
create a new table with redshifts.
For each galaxy, create multiple entries
with different redshifts from 0 to 2.
These r... | 53,103 |
def get_corrections(time_from=None, time_to=None, source=None):
"""
:return:
"""
corrections = session.query(Correction).filter(Correction.rolled_back == False)
if time_from is not None:
corrections.filter(Correction.date > time_from)
if time_to is not None:
corrections.filter(C... | 53,104 |
def writeback() -> None:
"""Save the modified config. This will erase comments."""
with open(config_file, "w", encoding="utf") as f:
config.write(f) | 53,105 |
def regression_loss(predicty, ylabel, weight_map=None):
"""
Distance regression loss
:param predicty: prediction results
:param ylabel: ground truth
:return: regression loss
"""
loss = l2_loss(predicty, ylabel, weight_map)
return loss | 53,106 |
def get_required_distance(W, sigma_det, wav):
"""
Calculate the propagation distance required to satisfy sampling conditions.
:param W: approximate feature size [m]
:param sigma_det: propagated plane (detector) pixel size [m]
:param wav: source wavelength [m]
:returns zreq: required distance ... | 53,107 |
def get_token():
""" Get an OAuth token for Spotify """
global TOKEN
try:
data = st.start_session(USER,PW)
TOKEN = data[0]
EXPIRATION_DATE = data[1]
except:
quit('Unable to get OAuth Token :-( -- Check you have set your Spotify username and password correctly.') | 53,108 |
def add_user_to_license(
requesting_user: User, license_object: License, user: User
) -> LicenseUser:
"""
Adds a user to the provided license.
:param requesting_user: The user on whose behalf the user is added to the license.
:param license_object: The license that the user must be added to.
:p... | 53,109 |
async def main(records: Union[str, List[str]], access_token: str, ttl: int = 3600):
"""
Dynamic DNS tool for Digital Ocean
"""
os.environ['DIGITALOCEAN_ACCESS_TOKEN'] = access_token
parsed_records = []
if isinstance(records, tuple):
for raw in records:
parsed_records += [r fo... | 53,110 |
def subfolders_in(whole_path):
"""
Returns all subfolders in a path, in order
>>> subfolders_in('/')
['/']
>>> subfolders_in('/this/is/a/path')
['/this', '/this/is', '/this/is/a', '/this/is/a/path']
>>> subfolders_in('this/is/a/path')
['this', 'this/is', 'this/is/a', 'this/is/a/path']... | 53,111 |
def test_out_of_order_end_states(settings):
"""
Test with missing PENDING and/or end states
"""
# Remove last state, a required dead end state
settings.RETIREMENT_STATES = copy.deepcopy(settings.RETIREMENT_STATES)
del settings.RETIREMENT_STATES[-1]
settings.RETIREMENT_STATES.insert(-2, 'COMP... | 53,112 |
def getall(current_user):
""" endpoint to fetch all meetups """
all_meetups = MEETUPS.getall_meetups()
if all_meetups:
return make_response(jsonify({
"message": "Success",
"meetups": all_meetups
}), 200)
return make_response(jsonify({'message': 'Meetup not found'... | 53,113 |
def setRoi(event, x, y, flags, params):
"""Mouse callback to set ROI
event - mouse event
x: int - x coordinate
x: int - y coordinate
flags - additional flags
params - extra parameters
"""
global drawingRect, roiRect, initVideo
if event == cv2.EVENT_LBUTTONDOWN:
drawingRect = [(x, y), (x, y)]
# print(... | 53,114 |
def generate_certificates(base_dir, broker_bool, client_bool, client_file):
"""Generate client and/or broker Curve certificates"""
keys_dir = os.path.join(base_dir, "tmp_certificates")
if broker_bool:
broker_keys_dir = os.path.join(keys_dir, "broker_keys")
if client_bool:
client_keys_di... | 53,115 |
def read_attribute_value(stream, compiler):
"""
Reads an attribute's value which may be a string, a number or None
"""
ch = stream.text[stream.ptr]
if ch in STRING_LITERALS:
value = read_quoted_string(stream)
if compiler.options.escape_attrs:
# TODO handle escape_attrs=... | 53,116 |
def user_session_token(primary_auth, headers):
"""Get session_token.
param headers: Headers of the request
param primary_auth: Primary authentication
return session_token: Session Token from JSON response
"""
try:
status = primary_auth.get("errorCode", primary_auth["status"])
except... | 53,117 |
def initSetGenotype(possible_values: list):
"""
Function to initialise the genotype of individuals represented as a Set from a list of possible
values.
Parameters
----------
possible_values: list
List of possible values to insert into the individual.
Returns
-------
:list
... | 53,118 |
def logout(request):
"""
Logout request
:param request:
:return:
"""
auth.logout(request)
return render_to_response("logout.html") | 53,119 |
def subprocess_check_output(*popenargs, **kwargs):
"""
Function to call a subprocess and gather the output.
"""
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
if 'stderr' in kwargs:
raise ValueError('stderr argument not allowed, it will be over... | 53,120 |
def _mirtop(out_files, hairpin, gff3, species, out):
"""
Convert miraligner to mirtop format
"""
args = argparse.Namespace()
args.hairpin = hairpin
args.sps = species
args.gtf = gff3
args.add_extra = True
args.files = out_files
args.format = "seqbuster"
args.out_format = "gff... | 53,121 |
def get_actual(db: Connection) -> Mapping[str, Event]:
"""
Get actual channel values.
"""
return {key: Event(**value) for key, value in db[ACTUAL_KEY].items()} | 53,122 |
def teardown_deployer_container(config_path):
"""Teardown the Cluster Genesis container on the deployer.
This function is idempotent.
"""
log = logger.getlogger()
try:
cfg = Config(config_path)
except UserException:
log.error('Unable to open Cluster Genesis config.yml file')
... | 53,123 |
def get_filter_set_field_tuples(filter_set):
"""Return a list of tuples of filter set filter names and values.
This is used together with above `join_filter_set_field_values` to create
a table of filters used in an analysis view.
NOTE:
- This function and `join_filter_set_field_values` are kept se... | 53,124 |
def getInnerText(node):
"""
Get all the inner text of a DOM node (recursively).
"""
# inspired by http://mail.python.org/pipermail/xml-sig/2005-March/011022.html
inner_text = []
for child in node.childNodes:
if child.nodeType == child.TEXT_NODE or child.nodeType == child.CDATA_SECTION_NO... | 53,125 |
def pull_tweets(
query,
from_date,
to_date,
save_path,
credentials_path,
yaml_key,
file_name=None,
results_per_call=500,
max_results=3000,
verbose=False,
**kwargs
):
"""
Pulls data (i.e., tweets and user info) from Twitter u... | 53,126 |
def solve(s, minint=-20, maxint=20, threads=8, options=()):
"""
Return the (optimal) models/assignments of the program in the given string.
"""
solver = Solver(minint, maxint, threads, options)
ret = _solve(solver, s)
has_minimize = solver.prp.has_minimize
for conf in CONF_GLOBAL:
... | 53,127 |
def package_root(module: types.ModuleType):
"""获取module的目录"""
root, _ = os.path.split(os.path.abspath(module.__file__))
return root | 53,128 |
def do_it(session, island, iterations):
"""
Parameters
----------
session : ikabot.web.session.Session
island : dict
iterations : int
"""
for i in range(iterations):
wait_for_miracle(session, island)
response = activateMiracleHttpCall(session, island)
if response[1][1][0] == 'error':
msg = _('The mi... | 53,129 |
def process_directory(jvm_args, study_directory, update_generic_assay_entity = None):
"""
Import an entire study directory based on meta files found.
1. Determine meta files in study directory.
2. Read all meta files and determine file types.
3. Import data files in specific order by file type.
... | 53,130 |
def create_report(result: DefaultDict) -> str:
"""
Creates the report
:param result: results instance
:param output: output string
:return:
"""
fpoint = 10
report = f"""
Analyse-Report Version 0.1
\n{"-" * 60}\n"""
if "combined" in result.keys():
subheader = f"""
... | 53,131 |
def interactiveNIFSInput():
"""
Get NIFS configuration interactively. This is based on Sphinx's interactive input session.
"""
logging.info("\nWelcome to Nifty! The current mode is NIFS data reduction.\n\nPress enter to accept default data reduction options.")
fullReduction = getParam(
... | 53,132 |
def test_exchange_info():
"""Tests the API endpoint to get exchange info"""
api = Client()
response = api.exchange_info()
response.should.equal(mock_item) | 53,133 |
def np_masked_softmax(logits, legal_actions_mask):
"""Returns the softmax over the valid actions defined by `legal_actions_mask`.
Args:
logits: A tensor [..., num_actions] (e.g. [num_actions] or [B, num_actions])
representing the logits to mask.
legal_actions_mask: The legal action mask, same shape a... | 53,134 |
def get_example1_pandas():
"""First example with no missing values, A and D are declared categoricals,
while B is also categorical but not declared as such, one which is
obviously categorical and two continuous
"""
df = pd.DataFrame(
{
"A": [0, 1, 1, 1, 0, 0, 0, 0, 1],
... | 53,135 |
def wpet_unit(out):
"""wpe * tの単位変換器を生成する.
以下のコードを実行することで、データのt軸をwpe*tで規格化できる.
>>> Emout.name2unit['t'] = wpet_unit
Parameters
----------
out : Emout
Emoutオブジェクト
Returns
-------
UnitTranslator
wpe * tの単位変換器
"""
return UnitTranslator(
out.inp.wp[0] ... | 53,136 |
async def test_erros(hass, config, error, exc):
"""Test that exceptions show the correct error."""
with patch(
"homeassistant.components.notion.config_flow.async_get_client", side_effect=exc
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_... | 53,137 |
def buttons_click(dx, dy, key):
"""Проверяет, какая клавиша была нажата.
При нажатии опредленных клавиш меняются скорость, а также ращрешение, какую кнопку нажать
dx, dy -- изменение координат змейки
key -- параметр запускающий метод pygame для читания нажатых клавиш
return: измененные в со... | 53,138 |
def key_func(length=10) -> str:
"""
generate random key
"""
String = 'abcdefghijklmnopqrstuvwxyz' # string for creating auth Keys
String += String.upper()+'1234567890ß´^°!"§$%&/()=?`+*#.:,;µ@€<>|'
password_provided = ''.join(random.sample(String, length)) # This i... | 53,139 |
def download(p):
"""Format: download -p descarga """
if p == p:
dl.activate()
else:
click.echo('parametro no valido') | 53,140 |
def listing(output_lines):
"""Return list of dicts with basic item info parsed from cli output."""
items = []
table_ = multi_line_row_table(output_lines)
for row in table_['values']:
item = {}
for col_idx, col_key in enumerate(table_['headers']):
item[col_key] = row[col_idx]... | 53,141 |
def extract_network_from_shapefile(edge_shapefile_df, node_shapefile_df):
"""
Extracts network data into DataFrames for pipes and nodes in the network
:param edge_shapefile_df: DataFrame containing all data imported from the edge shapefile
:param node_shapefile_df: DataFrame containing all data importe... | 53,142 |
def MPC_SetupFindFieldStrength(expected_voltage: float) \
-> Dict[str, Union[float, int]]:
"""Reaches Vov by adjusting RF field strength
Parameters
----------
expected_voltage : float
Vdc value to reach in V
Returns
-------
dict
'voltage_reached' (float): Reached Vd... | 53,143 |
def calculate_regrid_matrix(fname_griddesc, fname_matrix, fname_mattxt,
in_grid, out_grid,
col_refinement=1000, row_refinement=1000):
"""run mtxcalc (from the Models-3 I/O API) to calculate a regrid
matrix for a specified grid-to-grid transformation. Mode... | 53,144 |
def classifier_sklearn(X_train, X_test, y, classifier_name, params):
"""
:param X_train:
:param X_test:
:param y:
:param classifier_name: class must be imported at top of the file, for config use class name only
:param params:
:return:
"""
n_classes = np.unique(y).shape[0]
class... | 53,145 |
def load(filepath : str) -> Iterable[Maze]:
"""Load a sequence of Mazes from a message file."""
yield from mazes_from_messages(load_messages(filepath)) | 53,146 |
def check_test_cwd(request):
"""Check particular test restore CWD."""
if request.cls:
yield
return
os.chdir(ROOT_DIR)
old_cwd = os.getcwd()
yield
if old_cwd != os.getcwd():
os.chdir(ROOT_DIR)
raise CwdException() | 53,147 |
def string_generator(size=6, chars=string.ascii_letters):
"""Generator string based on the parameters passed.
@param size: Size limit of string. Default: 6
@param chars: string.ascii_letters Default: 200 - Use the constant string class
"""
return ''.join(random.choice(chars) for x in range(size)) | 53,148 |
def write_json(data: Dict[str, Annotations], file: str):
"""
Dumps generated signatures to disk for comparision with other binaries
:param data: dictionary mapping hashes to dictionary mapping basic block index to tag data
:param file: full path to json file to be dumped
"""
if not os.path.exis... | 53,149 |
def compileFinalNgramCounts(final_ngrams,compiled_final_station_ngrams,station_ngrams):
"""Join the final_ngrams in station_ngrams to compiled_final_station_ngrams"""
for (station, ngrams) in station_ngrams.viewitems():
thisstation_finalngrams = \
compiled_final_station_ngrams.get(statio... | 53,150 |
def inference(model, X):
""" Run model inferences and return the predictions.
Inputs
------
model : catboost.CatBoostClassifier
Trained machine learning model.
X : np.array
Data used for prediction.
Returns
-------
preds : np.array
Predictions from the model.
... | 53,151 |
def validate_args(parser: ArgumentParser, args: dict) -> dict:
"""
Validates the parsed arguments and either returns the validated arguments or aborts the execution of the program,
issuing an help message.
Args:
parser: An ArgumentParser instance initialized with command line definitions. Only us... | 53,152 |
def readPars(fileName, var_Ze="Ze", var_time="time", var_vmean="vmean", var_dmean="dmean", var_rr="rr", **kwargs):
""" This function reads the parsivel netCDF files and
extracts the desired variables.
Arguments
---------
fileName of the .nc parsivel data file
var_Ze: va... | 53,153 |
def fib_iter(n):
"""[summary]
Works iterative approximate O(n)
Arguments:
n {[int]} -- [description]
Returns:
[int] -- [description]
"""
# precondition
assert n >= 0, 'n must be positive integer'
fib_1 = 0
fib_2 = 1
res = 0
if n <= 1:
return n
... | 53,154 |
def split(values: Sequence[TItem], split_count: int) -> Tuple[Any, ...]:
"""
Returns the split ``values`` in ``split_count`` pieces in protocol.
Spec: https://github.com/ethereum/eth2.0-specs/blob/70cef14a08de70e7bd0455d75cf380eb69694bfb/specs/core/0_beacon-chain.md#helper-functions # noqa: E501
"""
... | 53,155 |
def test_filter_point_cloud_to_polygon_2d_triangle_and_3d_pointcloud():
"""
Test points that fall within a triangle symbol centered at
the origin. The shape resembles:
(0,1)
/\
/ \
(-1,0)--.--(1,0)
By shapely convention, points on the boundary are not
consid... | 53,156 |
def BalanceOf(account):
"""
Method to return the current balance of an address
:param account: the account address to retrieve the balance for
:type account: bytearray
:return: the current balance of an address
:rtype: int
"""
context = GetContext()
balance = Get(context, account)... | 53,157 |
def start(task_id: int, note: str = None):
"""Starts a task"""
create_timelog(graph, task_id, note=note)
save(graph) | 53,158 |
def all_downloadable_sfs_files(session):
"""
Gets all files managed in Snapchat FS for a specific user; returns
them as a list of Snap objects, whose IDs can be used to download
all or some of the files from Snapchat's DB.
@session An SfsSession object that has been logged in.
@return List ... | 53,159 |
def overlaps_graph(boxes1, boxes2):
"""Computes IoU overlaps between two sets of boxes.
boxes1, boxes2: [N, (y1, x1, y2, x2)].
"""
# 1. Tile boxes2 and repeat boxes1. This allows us to compare
# every boxes1 against every boxes2 without loops.
# TF doesn't have an equivalent to np.repeat() so si... | 53,160 |
def com_google_fonts_check_description_max_length(description):
"""DESCRIPTION.en_us.html must have less than 2000 bytes."""
if len(description) >= 2000:
yield FAIL,\
Message("too-long",
"DESCRIPTION.en_us.html must"
" have size smaller than 2000... | 53,161 |
def friendly_number(num):
""" Convert a base 10 number to a base X string.
Charcters from VALID_CHARS are chosen, to convert the number
to eg base 24, if there are 24 characters to choose from.
Use valid chars to choose characters that are friendly, avoiding
ones that could be confu... | 53,162 |
def check_sbd_device(options, device_path):
"""checks that a given sbd device exists and is initialized
Key arguments:
options -- options dictionary
device_path -- device path to check
Return Codes:
1 / DEVICE_INIT if the device exists and is initialized
-1 / PATH_NOT_EXISTS if the path do... | 53,163 |
def run_training_loop(
base_dir: str,
env: balloon_env.BalloonEnv,
agent: base_agent.Agent,
num_episodes: int,
max_episode_length: int,
collector_constructors: Sequence[
collector_dispatcher.CollectorConstructorType],
*,
render_period: int = 10,
checkpoint_period: int = 1,
... | 53,164 |
def create_c2_opt(optimizer_config, eval_func_path):
"""
Create a C2 Calibration object. Can be used to simulate the calibration process, if
the eval_func_path contains a ''real'' experiment.
Parameters
----------
optimizer_config : str
File path to a hjson configuration file.
eval_... | 53,165 |
def pick_model(data):
"""Picks the models depending on the provided configuration flags."""
# Create model classification.
if FLAGS.model_cls == 'mlp':
hidden_classif = (parse_layers_string(FLAGS.hidden_cls)
if FLAGS.hidden_cls is not None else [])
model_cls = MLP(
output_dim... | 53,166 |
def test_format_nested_fields() -> None:
"""Nested fields in formatting.
Uses width and precision formatting.
"""
value: Decimal = Decimal("12.34567")
width: int = 10
precision: int = 5
assert "result: {0:{1}.{2}}".format(value, width, precision) == "result: 12.346" | 53,167 |
def pytest_funcarg__tracker_config(request):
"""
The tracker configuration as ``TrackerConfig`` object, or ``None``, if
there is no tracker configuration.
Tracker configuration is taken from the class this test is defined in. If
there is a ``testname`` for this test, the tracker config is taken fr... | 53,168 |
def send_verify_code(phone_num):
"""发送验证码逻辑
:params phone_num: 手机号码
:return:
"""
code = utils.gen_rendom_code(6)
#生成验证码
sms.send_verify_code(phone_num, code)
#发送验证码
return True | 53,169 |
def api_index():
"""List available endpoints
"""
url_rules = [r.rule for r in current_app.url_map.iter_rules()]
return ApiResponse({'endpoints': sorted(list(set(url_rules)))}) | 53,170 |
def get_available_formats():
"""List the formats you can use in self.getFormat in a comma separated list (string)"""
ret = ""
for formats in IRC_FORMATTING_DICT:
ret += formats + ", "
return ret[:-2] | 53,171 |
def min_os_level(release):
"""
Usage::
class Tests (unittest.TestCase):
@min_os_level('10.6')
def testSnowLeopardCode(self):
pass
"""
return onlyIf(
os_level_key(os_release()) >= os_level_key(release),
f"Requires OSX {release} or later",
... | 53,172 |
def UNet(dim=512, num_classes=12):
"""
Standard U-Net architecture for segmentation
"""
from keras.models import Model
from keras.layers import Input
from keras.layers import Conv2D, SpatialDropout2D, MaxPool2D
from keras.layers import UpSampling2D, Reshape, concatenate
from keras.regul... | 53,173 |
def _PreprocessExactUsers(
cnxn, cond, user_service, id_fields, is_member):
"""Preprocess a foo=emails cond into foo_id=IDs, if exact user match.
This preprocesing step converts string conditions to int ID conditions.
E.g., [owner=email] to [owner_id=ID]. It only does it in cases
where (a) the email was "... | 53,174 |
def eval_asmk_multistep(net, inference, multistep, globals, *, datasets, codebook_training, asmk):
"""Evaluate local descriptors with ASMK"""
valid_steps = ["train_codebook", "aggregate_database", "build_ivf", "query_ivf", "aggregate_build_query"]
assert multistep['step'] in valid_steps, multistep['step']
... | 53,175 |
def UploadForecastFromExcel():
"""Interface Package Description"""
interface = {
"FileName" : str,
"SheetName" : str,
"ForecastName" : str,
"ForecastYear" : str,
"GFO" : bool,
"InterpolationMethod" : ['MonthlyVolumes', 'MonthlyRates', 'None'],
"Phase" : ['Gas', 'Oil'],
... | 53,176 |
def random_matrix(width: int, height: int, a: int, b: int) -> Matrix:
"""
returns a random matrix WxH with integer components
between 'a' and 'b'
"""
random.seed(None)
matrix: list[list[float]] = [
[random.randint(a, b) for _ in range(width)] for _ in range(height)
]
return Matri... | 53,177 |
def show_quick_pick(items: list, options: QuickPickOptions = None) -> QuickPickItem:
"""
Shows a selection list allowing multiple selections.
Returns either the selected items or undefined.
"""
data = []
for item in items:
if isinstance(item, QuickPickItem):
data.ap... | 53,178 |
def test_getattr(get_calcjob_node):
"""Test that the manager supports the getattr operator."""
node, dictionary = get_calcjob_node
manager = CalcJobResultManager(node)
for key, value in dictionary.items():
assert getattr(manager, key) == value
with pytest.raises(AttributeError):
as... | 53,179 |
def merge(nums1, m: int, nums2, n) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
if len(nums1) >= m + n:
for num in nums2:
nums1[m] = num
m += 1
nums1.sort()
return nums1 | 53,180 |
def create_sample_user(**params):
"""Creates sample user"""
return get_user_model().objects.create_user(**params) | 53,181 |
def subset_model(
model: Model,
objective_weights: Tensor,
outcome_constraints: Optional[Tuple[Tensor, Tensor]] = None,
objective_thresholds: Optional[Tensor] = None,
) -> SubsetModelData:
"""Subset a botorch model to the outputs used in the optimization.
Args:
model: A BoTorch Model. I... | 53,182 |
def relu_derivative(dA, Z):
"""
Implement the backward propagation for a single RELU unit.
Arguments:
dA -- post-activation gradient, of any shape
cache -- 'Z' where we store for computing backward propagation efficiently
Returns:
dZ -- Gradient of the cost with respect to Z
"""
... | 53,183 |
def compute_coupled_cell(f1,f2) :
"""
Computes the full-sky angular power spectra of two masked fields (f1 and f2) without aiming to deconvolve the mode-coupling matrix. Effectively, this is equivalent to calling the usual HEALPix anafast routine on the masked and contaminant-cleaned maps.
:param NmtField ... | 53,184 |
def processArgs(options, args):
""" By default (no args) run the daemon. Otherwise we could be making an XML RPC call, or
calling a PostProcessor on the specified dir then exiting """
if not len(args) and not options.postProcessDir:
Hellanzb.IS_DOWNLOADER = True
if getattr(options, ... | 53,185 |
def get_dates(time):
"""Obtain pandas datetime objects from date objects.
Sometimes there are problems with 360 days calendars and cftime
units in pandas. This function uses `dates_from_360cal` to
circumvent this problem when pandas can't be used directly to
generate a DatetimeIndex.
Param... | 53,186 |
def build_1tdm_costly(no,bra_space,ket_space,basis,spin_case):
"""
Copy of ca_ss
Compute a(v1,v2,j) = <v1|a_j|v2>
Input:
no = n_orbs
bra_space = (n_alpha,n_beta) for bra
ket_space = (n_alpha,n_beta) for ket
spin_case: 'a' or 'b'
basis = dict of basis vectors
... | 53,187 |
def read_words_pos(parse):
"""
Read the given parse string and return a list of tuples
(token, pos_tag) in lower case.
"""
parse = parse.lower()
tree = nltk.Tree.fromstring(parse)
word_pos = [(word, map_wn_pos(pos)) for word, pos in tree.pos()]
return word_pos | 53,188 |
def die_with_usage():
""" HELP MENU """
print 'USAGE: python previewDownloader.py [path to MSD data]'
sys.exit(0) | 53,189 |
def broadcast(socketio, drink, message):
"""Broadcast orders through SocketIO connection"""
socketio.emit(
'incomming',
{
'drink': drink,
'message': message
},
broadcast=True
) | 53,190 |
def get_state_02y1_pure_state_vector() -> np.ndarray:
"""returns the pure state vector of :math:`\\frac{1}{\\sqrt{2}} (|0\\rangle - j|2\\rangle)`.
Returns
-------
np.ndarray
the pure state vector.
"""
vec = np.array([1, 0, -1j], dtype=np.complex128) / np.sqrt(2)
return vec | 53,191 |
def check_input_allowed(object):
"""
This is a generic function called with the object being commented.
It's defined as the default in 'COMMENTS_INK_APP_MODEL_OPTIONS'.
If you want to disallow comments input to your 'app.model' instances under
a given conditions, rewrite this function in your code ... | 53,192 |
def eval_dev(dev_file, batch_size, epoch, shuffle, cuda, top_k,
sender, receiver, desc_dict, map_labels, file_name,
callback=None):
"""
Function computing development accuracy
"""
desc = desc_dict["desc"]
desc_set = desc_dict.get("desc_set", None)
desc_set_lens = desc_... | 53,193 |
def create_temp_dir(tmpdir=None):
"""Create a new unique directory at a given temporary directory"""
if tmpdir is None:
tmpdir = tempfile.gettempdir()
elif not os.path.isdir(tmpdir):
os.makedirs(tmpdir)
# running into a rare issue with MAPDL on Windows with "\n" being
# treated lite... | 53,194 |
def is_dataclass_instance(obj: Any) -> bool:
"""Return True if the given object is a dataclass object, False otherwise.
In py36, this function returns False if the "dataclasses" backport is not available.
Taken from https://docs.python.org/3/library/dataclasses.html#dataclasses.is_dataclass.
"""
r... | 53,195 |
def add_path(path, node):
"""
Takes in list of synsets and add it into the overall hierarchy.
@param path: List of strings, where each string is a synset.
- The list is in the form of [child, parent, grandparent, ...]
@param node: Dictionary, contains the overall hierarchy we are building
"""... | 53,196 |
def dedup_model2_norm_by_layer_dedup_together(method):
"""Here, we perform the deduplication to rcv1_2k_xml model, while we normalize the block magnitude
by layer then order them together
Please use the correct commented out code to evaluate different approaches.
"""
model_path = 'models'
# De... | 53,197 |
def project_raster_ds(input_ds, output_raster, resampling_type,
output_osr=None, output_cs=None, output_extent=None,
input_nodata=None):
"""Project raster dataset to new spatial reference and/or cellsize
Args:
input_raster:
output_raster:
resa... | 53,198 |
def isChr(s, c):
"""
:param s: String
:param c: Chromosome, number or X or Y
:return: Whether s matches c
"""
if 'X' == c:
return 'X' in c
if 'Y' == c:
return 'Y' in c
return str(c) in re.findall("[1-9][0-9]*", s) | 53,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.