content
stringlengths
22
815k
id
int64
0
4.91M
def setForceFieldVersion(version): """ Set the forcefield parameters using a version number (string) and return a handle to the object holding them current version are: '4.2': emulating AutoDock4.2 'default': future AutoDock5 Parameters <- setForceFieldVersion(version) """ _par...
24,200
async def test_not_callable_modifier(): """ Test that an non-callable ``conn_modifier`` raises a specific ``TypeError``. """ with pytest.raises(TypeError) as err: await Dispatcher().dispatch("otus", "update", {"test": True}, conn_modifier="abc") assert "conn_modifier must be callable" in s...
24,201
def run(args): """ Runs the simulator """ for i in range(args.numtrack): run_time = 0 init_x, init_y, init_z, velx, vely, velz, accx, accy, accz = initialize_track_creation() sim = Simulator(init_x, init_y, init_z, x_vel=velx, y_vel=vely, z_vel=velz, x_acc=...
24,202
def filter_words(data: TD_Data_Dictionary): """This function removes all instances of Key.ctrl from the list of keys and any repeats because of Press and Realese events""" # NOTE: We may just want to remove all instances of Key.ctrl from the list and anything that follows that keys = data.get_letters() ...
24,203
def check_url_secure( docker_ip: str, public_port: int, *, auth_header: Dict[str, str], ssl_context: SSLContext, ) -> bool: """ Secure form of lovey/pytest/docker/compose.py::check_url() that checks when the secure docker registry service is operational. Args: docker_ip: IP ...
24,204
def ResNet101(pretrained=False, use_ssld=False, **kwargs): """ ResNet101 Args: pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise. If str, means the path of the pretrained model. use_ssld: bool=False. Whether using distillation pretrain...
24,205
def LineTextInCurrentBuffer( line_number ): """ Returns the text on the 1-indexed line (NOT 0-indexed) """ return vim.current.buffer[ line_number - 1 ]
24,206
def imported_instrumentor(library): """ Convert a library name to that of the correlated auto-instrumentor in the libraries package. """ instrumentor_lib = "signalfx_tracing.libraries.{}_".format(library) return get_module(instrumentor_lib)
24,207
def parse_cache_entry_into_seconds(isoTime): """ Returns the number of seconds from the UNIX epoch. See :py:attribute:`synapseclient.utils.ISO_FORMAT` for the parameter's expected format. """ # Note: The `strptime() method is not thread-safe (http://bugs.python.org/issue7980) strptimeLock.a...
24,208
def parse_runtime(log_file): """ Parse the job run-time from a log-file """ with open(log_file, 'r') as f: for line in f: l0 = line.rstrip("\n") break l1 = tail(log_file, 1)[0].rstrip("\n") l0 = l0.split()[:2] l1 = l1.split()[:2] try: y0, m0, d0 = li...
24,209
def load_answerer(): """Loads the answerer model.""" global _answerer if _model is None: load_model() _answerer = _model
24,210
def calculateEMA(coin_pair, period, unit): """ Returns the Exponential Moving Average for a coin pair """ closing_prices = getClosingPrices(coin_pair, period, unit) previous_EMA = calculateSMA(coin_pair, period, unit) constant = (2 / (period + 1)) current_EMA = (closing_prices[-1] * (2 / (1...
24,211
def euler_method(r0, N): """ euler_method function description: This method computes the vector r(t)'s using Euler's method. Args: r0 - the initial r-value N - the number of steps in each period """ delta_t = (2*np.pi)/N # delta t r = np.zeros((5*N, 2)) # 5Nx...
24,212
def main_menu(found_exists): """prints main menu and asks for user input returns task that is chosen by user input""" show_main_menu(found_exists) inp = input(">> ") if inp == "1": return "update" elif inp == "2": return "show_all" elif inp == "3": return "s...
24,213
def fromPsl(psl, qCdsRange=None, inclUnaln=False, projectCds=False, contained=False): """generate a PairAlign from a PSL. cdsRange is None or a tuple. In inclUnaln is True, then include Block objects for unaligned regions""" qCds = _getCds(qCdsRange, psl.qStrand, psl.qSize) qSeq = _mkPslSeq(psl.qName, p...
24,214
def drawMatrix(ax, mat, **kwargs): """Draw a view to a matrix into the axe." TODO ---- * pg.core.BlockMatrix Parameters ---------- ax : mpl axis instance, optional Axis instance where the matrix will be plotted. mat: obj obj can be so far: * pg.core.*Matrix...
24,215
def test_template_observation(workbench, template_sequence, app_dir, caplog): """Test that new templates are properly detected. """ import logging caplog.set_level(logging.WARNING) plugin = workbench.get_plugin('exopy.pulses') assert template_sequence in plugin.se...
24,216
def get_graph(identifier: str, *, rows: Optional[int] = None) -> pybel.BELGraph: """Get the graph surrounding a given GO term and its descendants.""" graph = pybel.BELGraph() enrich_graph(graph, identifier, rows=rows) return graph
24,217
def parse_custom_variant(self, cfg): """Parse custom variant definition from a users input returning a variant dict an example of user defined variant configuration 1) integrated: cpu=2 ram=4 max_nics=6 chassis=sr-1 slot=A card=cpm-1 slot=1 mda/1=me6-100gb-qsfp28 2) distributed: cp: cpu=2 ram=4 chassis...
24,218
def test_update_w_up_to_date(version, supplied_version, latest_version, mocker): """Tests footing.update.update when the template is already up to date""" mocker.patch('footing.check.not_has_branch', autospec=True) mocker.patch('footing.check.in_git_repo', autospec=True) mocker.patch('footing.check.in_c...
24,219
def cube_recenter_via_speckles(cube_sci, cube_ref=None, alignment_iter=5, gammaval=1, min_spat_freq=0.5, max_spat_freq=3, fwhm=4, debug=False, recenter_median=False, fit_type='gaus', negative=True, crop=True, ...
24,220
def root_histogram_shape(root_hist, use_matrix_indexing=True): """ Return a tuple corresponding to the shape of the histogram. If use_matrix_indexing is true, the tuple is in 'reversed' zyx order. Matrix-order is the layout used in the internal buffer of the root histogram - keep True if reshaping t...
24,221
def json_file_to_dict(fname): """ Read a JSON file and return its Python representation, transforming all the strings from Unicode to ASCII. The order of keys in the JSON file is preserved. Positional arguments: fname - the name of the file to parse """ try: with io.open(fname, enco...
24,222
def get_weather_sensor_by( weather_sensor_type_name: str, latitude: float = 0, longitude: float = 0 ) -> Union[WeatherSensor, ResponseTuple]: """ Search a weather sensor by type and location. Can create a weather sensor if needed (depends on API mode) and then inform the requesting user which one to...
24,223
def _npy_loads(data): """ Deserializes npy-formatted bytes into a numpy array """ logger.info("Inside _npy_loads fn") stream = six.BytesIO(data) return np.load(stream,allow_pickle=True)
24,224
def parse_string(string): """Parse the string to a datetime object. :param str string: The string to parse :rtype: `datetime.datetime` :raises: :exc:`InvalidDateFormat` when date format is invalid """ try: # Try to parse string as a date value = dateutil.parser.parse(string) ...
24,225
def get_elfs_oriented(atoms, density, basis, mode, view = serial_view()): """ Outdated, use get_elfs() with "mode='elf'/'nn'" instead. Like get_elfs, but returns real, oriented elfs mode = {'elf': Use the ElF algorithm to orient fingerprint, 'nn': Use nearest neighbor algorithm} """ ...
24,226
def test_medicinalproduct_1(base_settings): """No. 1 tests collection for MedicinalProduct. Test File: medicinalproduct-example.json """ filename = base_settings["unittest_data_dir"] / "medicinalproduct-example.json" inst = medicinalproduct.MedicinalProduct.parse_file( filename, content_type...
24,227
def on_new_thread_with_config(match, state, logger): """It happens when a new DB GC thread is created.""" kind = match[0] name = match[1] if match[1][:4] != "rDsp" else "rDsp" priority = int(match[2]) stack_size = int(match[3], 16) if "threads" not in state: state['threads'] = {} st...
24,228
def get_alliances_alliance_id_contacts(*, alliance_id, token, if_none_match=None, page='1'): """ :param alliance_id: An EVE alliance ID :param if_none_m...
24,229
def _get_corpora_json_contents(corpora_file): """ Get the contents of corpora.json, or an empty dict """ exists = os.path.isfile(corpora_file) if not exists: print("Corpora file not found at {}!".format(corpora_file)) return dict() with open(corpora_file, "r") as fo: retu...
24,230
def error_logger(param=None): """ Function to get an error logger, object of Logger class. @param param : Custom parameter that can be passed to the logger. @return: custom logger """ logger = Logger('ERROR_LOGGER', param) return logger.get_logger()
24,231
def _run_make_examples(pipeline_args): """Runs the make_examples job.""" def get_region_paths(regions): return filter(_is_valid_gcs_path, regions or []) def get_region_literals(regions): return [ region for region in regions or [] if not _is_valid_gcs_path(region) ] def get_extra_args(): ...
24,232
def get_iou(mask, label): """ :param mask: predicted mask with 0 for background and 1 for object :param label: label :return: iou """ # mask = mask.numpy() # label = labels.numpy() size = mask.shape mask = mask.flatten() label = label.flatten() m = mask + label i = len(np...
24,233
async def test_route_events( mock_socket: MagicMock, mock_subscriber: AsyncGenerator, topic_event ) -> None: """Test that an event is read from subscriber and sent to websocket.""" with patch.object(handle_subscriber, "send") as mock_send: await handle_subscriber.route_events(mock_socket, mock_subsc...
24,234
def mean_jaccard_distance(sets: List[Set[Any]]) -> float: """ Compute the mean Jaccard distance for sets A_1, \dots A_n: d = \frac{1}{n} \sum_{i=1}^{n-1} \sum_{j=i+1}^n (1 - J(A_i, A_j)) where J(A, B) is the Jaccard index between sets A and B and 1-J(A, B) is the Jaccard distance. """ n ...
24,235
def nx_find_connected(graph, start_set, end_set, cutoff=np.inf): """Return the nodes in end_set connected to start_set.""" reachable = [] for end in end_set: if nx_is_reachable(graph, end, start_set): reachable.append(end) if len(reachable) >= cutoff: break ...
24,236
def svn_client_proplist(*args): """ svn_client_proplist(char target, svn_opt_revision_t revision, svn_boolean_t recurse, svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t """ return _client.svn_client_proplist(*args)
24,237
def dev_transform(signal, input_path='../data/', is_denoised=True): """ normalization function that transforms each fature based on the scaling of the trainning set. This transformation should be done on test set(developmental set), or any new input for a trained neural network. Due to existence of ...
24,238
def moveTo(self, parent): """Move this element to new parent, as last child""" self.getParent().removeChild(self) parent.addChild(self) return self
24,239
def csv2timeseries_graphs(directories_dic={}, output_dir='', base_name=None, plot_numbers='', quantities=['stage'], extra_plot_name='', assess_all_csv_files=True, ...
24,240
def coerce_to_end_of_day_datetime(value): """ gets the end of day datetime equivalent of given date object. if the value is not a date, it returns the same input. :param date value: value to be coerced. :rtype: datetime | object """ if not isinstance(value, datetime) and isinstance(value...
24,241
def GenerateOutput(target_list, target_dicts, data, params): """Called by gyp as the final stage. Outputs results.""" config = Config() try: config.Init(params) if not config.files: raise Exception('Must specify files to analyze via config_path generator ' 'flag') topleve...
24,242
def greybody(nu, temperature, beta, A=1.0, logscale=0.0, units='cgs', frequency_units='Hz', kappa0=4.0, nu0=3000e9, normalize=max): """ Same as modified blackbody... not sure why I have it at all, though the normalization constants are different. """ h,k,c = unitdict[units]...
24,243
def GCLarsen_v0(WF, WS, WD, TI, pars=[0.435449861, 0.797853685, -0.124807893, 0.136821858, 15.6298, 1.0]): """Computes the WindFarm flow and Power using GCLarsen [Larsen, 2009, A simple Stationary...] Inputs ---------- WF: WindFarm Windfarm instance WS: list Rotor averaged U...
24,244
def log(message, exception=None): """Log a message (with optional exception) to a file.""" if exception: message = message[0:-1] + ': ' + str(exception) time = datetime.now() print "Log", time, ":", message logdir = autoplatform.personaldir() if not os.path.exists(logdir): mkdir(logdir) l...
24,245
def guess_table_address(*args): """ guess_table_address(insn) -> ea_t Guess the jump table address (ibm pc specific) @param insn (C++: const insn_t &) """ return _ida_ua.guess_table_address(*args)
24,246
def xmind_to_excel_file(xmind_file): """Convert XMind file to a excel csv file""" xmind_file = get_absolute_path(xmind_file) logging.info('Start converting XMind file(%s) to excel file...', xmind_file) testcases = get_xmind_testcase_list(xmind_file) fileheader = ["所属模块", "用例标题", "前置条件", "步骤", "预期",...
24,247
def reverse_file(filename): """reverse txt file contents with index""" with open(filename, "r", encoding="utf-8") as f: lines = f.readlines() lines.reverse() index = 0 with open(filename, "w", encoding="utf-8") as f: for line in lines: index += 1 ...
24,248
def test_6_1_9_etc_gshadow_dash_user(host): """ CIS Ubuntu 20.04 v1.1.0 - Rule # 6.1.9 Tests if /etc/gshadow- is owned by user root """ assert host.file(ETC_GSHADOW_DASH).user == 'root'
24,249
def get_elbs(account, region): """ Get elastic load balancers """ elb_data = [] aws_accounts = AwsAccounts() if not account: session = boto3.session.Session(region_name=region) for account_rec in aws_accounts.all(): elb_data.extend( query_elbs_for_account(acc...
24,250
def handle_commit_from_git_author(repository, commit, signed, missing): """ Helper method to triage commits between signed and not-signed user signatures. This method deals with non-GitLab users found in the commit information. :param repository: The repository this commit belongs to. :type reposi...
24,251
def make_call_context(sender_address: Address, gas: int=None, value: int=None, gas_price: int=None, data: bytes=None) -> Generator[Tuple[str, Any], None, None]: """ Makes the context for message call. """ if not is_a...
24,252
def nyul_normalize(img_dir, mask_dir=None, output_dir=None, standard_hist=None, write_to_disk=True): """ Use Nyul and Udupa method ([1,2]) to normalize the intensities of a set of MR images Args: img_dir (str): directory containing MR images mask_dir (str): directory containing masks for MR...
24,253
def likelihood_params(ll_mode, mode, behav_tuple, num_induc, inner_dims, inv_link, tbin, jitter, J, cutoff, neurons, mapping_net, C): """ Create the likelihood object. """ if mode is not None: kernel_tuples_, ind_list = kernel_used(mode, behav_tuple, num_induc, inner_dims)...
24,254
def is_num_idx(k): """This key corresponds to """ return k.endswith("_x") and (k.startswith("tap_x") or k.startswith("sig"))
24,255
def convert_to_boolarr(int_arr, cluster_id): """ :param int_arr: array of integers which relate to no, one or multiple clusters cluster_id: 0=Pleiades, 1=Meingast 1, 2=Hyades, 3=Alpha Per, 4=Coma Ber """ return np.array((np.floor(int_arr/2**cluster_id) % 2), dtype=bool)
24,256
def serialize(root): # """Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Des...
24,257
def test_sort(): """Test sort container by specific index""" a = (10, 3, 3) b = (5, 1, -1) c = (1, -3, 4) list0 = (a, b, c) # Test sort on 1st entry list1 = floodsystem.utils.sorted_by_key(list0, 0) assert list1[0] == c assert list1[1] == b assert list1[2] == a # Test s...
24,258
def ensure_daemon(f): """A decorator for running an integration test with and without the daemon enabled.""" def wrapper(self, *args, **kwargs): for enable_daemon in [False, True]: enable_daemon_str = str(enable_daemon) env = { "HERMETIC_ENV": "PANTS_PANTSD,PANTS...
24,259
def create_auth_token(sender, instance=None, created=False, **kwargs): """ Tokens for users would be created as soon as they register through signals """ if created: Token.objects.create(user=instance)
24,260
def reproject_dataset(dataset, out_srs, in_srs=None): """Standalone function to reproject a given dataset with the option of forcing an input reference system :param out_srs: The desired output format in WKT. :type out_srs: str :param in_srs: The input format in WKT from which to conver...
24,261
def conditional(condition, decorator): """ Decorator for a conditionally applied decorator. Example: @conditional(get_config('use_cache'), ormcache) def fn(): pass """ if condition: return decorator else: return lambda fn: fn
24,262
def variance(data, mu=None): """Compute variance over a list.""" if mu is None: mu = statistics.mean(data) return sum([(x - mu) ** 2 for x in data]) / len(data)
24,263
def make_note(outfile, headers, paragraphs, **kw): """Builds a pdf file named outfile based on headers and paragraphs, formatted according to parameters in kw. :param outfile: outfile name :param headers: <OrderedDict> of headers :param paragraphs: <OrderedDict> of paragraphs :param kw: keyword...
24,264
def output_file_exists(filename): """Check if a file exists and its size is > 0""" if not file_exists(filename): return False st = stat(filename) if st[stat_module.ST_SIZE] == 0: return False return True
24,265
def IMF_N(m,a=.241367,b=.241367,c=.497056): """ returns number of stars with mass m """ # a,b,c = (.241367,.241367,.497056) # a=b=c=1/3.6631098624 if .1 <= m <= .3: res = c*( m**(-1.2) ) elif .3 < m <= 1.: res = b*( m**(-1.8) ) elif 1. < m <= 100.: # res = a*( m*...
24,266
def features_disable(partial_name, partial_name_field, force, **kwargs): """Disable a feature""" mode = "disable" params = {"mode": "force"} if force else None feature = _okta_get("features", partial_name, selector=_selector_field_find(partial_name_field, partial_name)) featu...
24,267
def _get_images(): """Get the official AWS public AMIs created by Flambe that have tag 'Creator: flambe@asapp.com' ATTENTION: why not just search the tags? We need to make sure the AMIs we pick were created by the Flambe team. Because of tags values not being unique, anyone can create a public AMI ...
24,268
def ar_coefficient(x, param): """ This feature calculator fits the unconditional maximum likelihood of an autoregressive AR(k) process. The k parameter is the maximum lag of the process .. math:: X_{t}=\\varphi_0 +\\sum _{{i=1}}^{k}\\varphi_{i}X_{{t-i}}+\\varepsilon_{t} For the config...
24,269
def measure_ir( sweep_length=1.0, sweep_type="exponential", fs=48000, f_lo=0.0, f_hi=None, volume=0.9, pre_delay=0.0, post_delay=0.1, fade_in_out=0.0, dev_in=None, dev_out=None, channels_input_mapping=None, channels_output_mapping=None, ascending=False, deconv...
24,270
def address_factory(sqla): """Create a fake address.""" fake = Faker() # Use a generic one; others may not have all methods. addresslines = fake.address().splitlines() areas = sqla.query(Area).all() if not areas: create_multiple_areas(sqla, random.randint(3, 6)) areas = sqla.query(A...
24,271
def generate_test_bench(file_path): """ Main function to generate a testbench from a VHDL source file. The script takes the input path of the file and generates a new file in that directory with a prefix defined by testbench_prefix. :param file_path: path to the .vhd file :return: nothing """ ...
24,272
def discover_performance_dfg(log: Union[EventLog, pd.DataFrame], business_hours: bool = False, worktiming: List[int] = [7, 17], weekends: List[int] = [6, 7]) -> Tuple[dict, dict, dict]: """ Discovers a performance directly-follows graph from an event log Parameters --------------- log Event...
24,273
def mifs(data, target_variable, prev_variables_index, candidate_variable_index, **kwargs): """ This estimator computes the Mutual Information Feature Selection criterion. Parameters ---------- data : np.array matrix Matrix of data set. Columns are variables, rows are observations. targe...
24,274
async def cmd_denybnc(text: str, message, bnc_queue, conn: 'Conn'): """<user> - Deny [user]'s BNC request""" nick = text.split()[0] if nick not in bnc_queue: message(f"{nick} is not in the BNC queue.") return conn.rem_queue(nick) message( f"SEND {nick} Your BNC auth could not...
24,275
def main(args): """Main function""" args_check(args) mkdir(TMP) mkdir(RESULT) # set_cpu_mode or set_gpu_mode decides whether using # CPU/GPU to do weights calibration, but activation calibration is # controled by caffe APIs: caffe.set_mode_cpu() or set_mode_gpu(). # Need to set amct mod...
24,276
def input_thing(): """输入物品信息""" name_str, price_str, weight_str = input('请输入物品信息(名称 价格 重量):').split() return name_str, int(price_str), int(weight_str)
24,277
def extract_features_mask(img, mask): """Computes law texture features for masked area of image.""" preprocessed_img = laws_texture.preprocess_image(img, size=15) law_images = laws_texture.filter_image(preprocessed_img, LAW_MASKS) law_energy = laws_texture.compute_energy(law_images, 10) energy_feat...
24,278
def construct_grid_with_k_connectivity(n1,n2,k,figu = False): """Constructs directed grid graph with side lengths n1 and n2 and neighborhood connectivity k""" """For plotting the adjacency matrix give fig = true""" def feuclidhorz(u , v): return np.sqrt((u[0] - (v[0]-n2))**2+(u[1...
24,279
def test_remove_duplicate_events(): """Test the remove_duplicate_events function by ensuring that duplicate events are removed.""" one = EventRecord(received_at=datetime(2018, 2, 19, 0, 0, 11), source_type="datastoretest", owner="a", data={}) one.fingerprint = "f1" two = EventRecord(received_at=datetime...
24,280
def get_tar_file(tar_url, dump_dir=os.getcwd()): """ Downloads and unpacks compressed folder Parameters ---------- tar_url : string url of world wide web location dump_dir : string path to place the content Returns ------- tar_names : list list of strings of fil...
24,281
def check_auth(*args, **kwargs): """A tool that looks in config for 'auth.require'. If found and it is not None, a login is required and the entry is evaluated as a list of conditions that the user must fulfill""" conditions = cherrypy.request.config.get('auth.require', None) if conditions is not No...
24,282
def _optimal_shift(pos, r_pad, log): """ Find the shift for the periodic unit cube that would minimise the padding. """ npts, ndim = pos.shape # +1 whenever a region starts, -1 when it finishes start_end = empty(npts*2, dtype=np.int32) start_end[:npts] = 1 start_end[npts:] = -1 ...
24,283
def test_i(kind): """Test I methods. :param str kind: Type of string to test. """ instance = get_instance(kind, 'tantamount') assert instance.index('t') == 0 assert instance.index('t', 0) == 0 assert instance.index('t', 0, 1) == 0 assert instance.index('t', 1) == 3 assert instance.i...
24,284
def ShowActStack(cmd_args=None): """ Routine to print out the stack of a specific thread. usage: showactstack <activation> """ if cmd_args == None or len(cmd_args) < 1: print "No arguments passed" print ShowAct.__doc__.strip() return False threadval = kern.GetValueFromA...
24,285
def upload(dbx, fullname, dbx_folder, subfolder, name, overwrite=False): """Upload a file. Return the request response, or None in case of error. """ path = '/%s/%s/%s' % (dbx_folder, subfolder.replace(os.path.sep, '/'), name) while '//' in path: path = path.replace('//', '/') mode = (dr...
24,286
def load_request(possible_keys): """Given list of possible keys, return any matching post data""" pdata = request.json if pdata is None: pdata = json.loads(request.body.getvalue().decode('utf-8')) for k in possible_keys: if k not in pdata: pdata[k] = None # print('pkeys: ...
24,287
def get_random_tcp_start_pos(): """ reachability area: x = [-0.2; 0.4] y = [-0.28; -0.1] """ z_up = 0.6 tcp_x = round(random.uniform(-0.2, 0.4), 4) tcp_y = round(random.uniform(-0.28, -0.1), 4) start_tcp_pos = (tcp_x, tcp_y, z_up) # start_tcp_pos = (-0.2, -0.28, z_up) return...
24,288
def CalculateChiv3p(mol): """ ################################################################# Calculation of valence molecular connectivity chi index for path order 3 ---->Chiv3 Usage: result=CalculateChiv3p(mol) Input: mol is a molecule object...
24,289
def coerce(version: str) -> Tuple[Version, Optional[str]]: """ Convert an incomplete version string into a semver-compatible Version object * Tries to detect a "basic" version string (``major.minor.patch``). * If not enough components can be found, missing components are set to zero to obtai...
24,290
def choose_wyckoff(wyckoffs, number): """ choose the wyckoff sites based on the current number of atoms rules 1, the newly added sites is equal/less than the required number. 2, prefer the sites with large multiplicity """ for wyckoff in wyckoffs: if len(wyckoff[0]) <= number: ...
24,291
def _to_system(abbreviation): """Converts an abbreviation to a system identifier. Args: abbreviation: a `pronto.Term.id` Returns: a system identifier """ try: return { 'HP': 'http://www.human-phenotype-ontology.org/' }[abbreviation] except KeyError: ...
24,292
def apply_gate(circ: QuantumCircuit, qreg: QuantumRegister, gate: GateObj, parameterise: bool = False, param: Union[Parameter, tuple] = None): """Applies a gate to a quantum circuit. More complicated gates such as RXX gates should be decomposed into single qubit gates and CNOTs prior to call...
24,293
def write_MOM6_solo_mosaic_file(mom6_grid): """Write the "solo mosaic" file, which describes to the FMS infrastructure where to find the grid file(s). Based on tools in version 5 of MOM (http://www.mom-ocean.org/).""" # NOTE: This function is very basic, since we're skipping the # finding ...
24,294
def preprocess_datasets(data: str, seed: int = 0) -> Tuple: """Load and preprocess raw datasets (Yahoo! R3 or Coat).""" if data == 'yahoo': with codecs.open(f'../data/{data}/train.txt', 'r', 'utf-8', errors='ignore') as f: data_train = pd.read_csv(f, delimiter='\t', header=None) ...
24,295
def loadSentimentVector(file_name): """ Load sentiment vector [Surprise, Sorrow, Love, Joy, Hate, Expect, Anxiety, Anger] """ contents = [ line.strip('\n').split() for line in open(file_name, 'r').readlines() ] sentiment_dict = { line[0].decode('utf-8'): [float(w) for w in li...
24,296
def unique_boxes(boxes, scale=1.0): """Return indices of unique boxes.""" v = np.array([1, 1e3, 1e6, 1e9]) hashes = np.round(boxes * scale).dot(v) _, index = np.unique(hashes, return_index=True) return np.sort(index)
24,297
def compscan_key(compscan): """List of strings that identifies compound scan.""" # Name of data set that contains compound scan path = compscan.scans[0].path filename_end = path.find('.h5') dataset_name = os.path.basename(path[:filename_end]) if filename_end > 0 else os.path.basename(path) # Tim...
24,298
def HEX2DEC(*args) -> Function: """ Converts a signed hexadecimal number to decimal format. Learn more: https//support.google.com/docs/answer/3093192 """ return Function("HEX2DEC", args)
24,299