content
stringlengths
22
815k
id
int64
0
4.91M
def fancy_vector(v): """ Returns a given 3-vector or array in a cute way on the shell, if you use 'print' on the return value. """ return "\n / %5.2F \\\n" % (v[0]) + \ " | %5.2F |\n" % (v[1]) + \ " \\ %5.2F /\n" % (v[2])
20,200
def findpath_split(seq, ss1, ss2, md, th = 5, w = None): """ Calculate findpath barriers for smaller components. Args: seq: RNA sequence. ss1: Structure 1. ss2: Structure 2. md: ViennaRNA model details. th: Threshold of how many basepairs must change for an independent f...
20,201
def get_root_relative_url(url_path): """Remove the root page slug from the URL path""" return _clean_rel_url('/'.join(url_path.split('/')[2:]))
20,202
def test_policy_om_random_mdp(): """Test that optimal policy occupancy measure ("om") for a random MDP is sane.""" mdp = gym.make("imitation/Random-v0") V, Q, pi = mce_partition_fh(mdp) assert np.all(np.isfinite(V)) assert np.all(np.isfinite(Q)) assert np.all(np.isfinite(pi)) # Check it is a...
20,203
def run_command(command, split=False, include_errors=False, cwd=None, shell=False, env=None): """Run command in subprocess and return exit code and output""" sub_env = os.environ.copy() if env is not None: sub_env.update(env) if include_errors: error_pipe = subprocess.STDOUT else: ...
20,204
def exclusion_windows_matching(match_peaks): """ Discard the occurrences of matching and non-matchign ions when they are found in the window (+-losses_window_removal) around M-xx or free bases ions """ output_dic = match_peaks for key in match_peaks: if match_peaks[key]: fo...
20,205
def any_of(elements): """ Check to see if the argument is contained in a list of possible elements. :param elements: The elements to check the argument against in the predicate. :return: A predicate to check if the argument is a constituent element. """ def predicate(argument): return a...
20,206
def find_year(films_lst: list, year: int): """ Filter list of films by given year """ filtered_films_lst = [line for line in films_lst if line[1] == str(year)] return filtered_films_lst
20,207
def func_BarPS(HA_Open, HA_Close, HA_PS_Lookback, PS_pct_level=[0.35, 0.5, 0.95, 0.97], combine=False): """ 0. This function is for calculating price trend number of HA bar, by looking back HA_PS_Lookback HA bars, according to the previous bars' distribution, find the range (i.e. -4,-3,-2,-1,0,1,2,3,4) o...
20,208
def filter_whitespace(stream: List[Part]) -> List[Part]: """Remove whitespace tokens""" return flu(stream).filter(lambda x: x.token != Token.WHITESPACE).collect()
20,209
def iterellipse(x: int, y: int, b: int, a: int): """Yields (int, int) 2D vertices along a path defined by major and minor axes b and a as it traces an ellipse with origin set at (x, y) Args: b, a: major and minor axes Yields: ...
20,210
def merge_partial_dicts(interfaces_dict, partials_dict): """Merges partial interface into non-partial interface. Args: interfaces_dict: A dict of the non-partial interfaces. partial_dict: A dict of partial interfaces. Returns: A merged dictionary of |interface_dict| with |partial_dict|. ...
20,211
def gen_code_def_part(metadata): """生成代码中定义类的部分。 """ class_def_dict = validate(metadata) class_def_list = list(class_def_dict.values()) code = templates.t_def_all_class.render(class_def_list=class_def_list) return code
20,212
def clang_plusplus_frontend(input_file, args): """Generate LLVM IR from C++ language source(s).""" compile_command = default_clang_compile_command(args) compile_command[0] = llvm_exact_bin('clang++') return compile_to_bc(input_file, compile_command, args)
20,213
def create_forward_many_to_many_manager(superclass, rel, reverse): """ Create a manager for the either side of a many-to-many relation. This manager subclasses another manager, generally the default manager of the related model, and adds behaviors specific to many-to-many relations. """ class ...
20,214
def grp_render_dashboard_module(context, module, index=None, subindex=None): """ Template tag that renders a given dashboard module, it takes a ``DashboardModule`` instance as first parameter and an integer ``index`` as second parameter, that is the index of the module in the dashboard. """ ...
20,215
def serialize_routing(value, explicit_type=None): """Custom logic to find matching serialize implementation and returns it's unique registration string key :param value: instance to serialize :param explicit_type: explicit serialization type for value :return: str key to find proper serialize im...
20,216
def get_projection_matricies(az, el, distance_ratio, roll = 0, focal_length=35, img_w=137, img_h=137): """ Calculate 4x3 3D to 2D projection matrix given viewpoint parameters. Code from "https://github.com/Xharlie/DISN" """ F_MM = focal_length # Focal length SENSOR_SIZE_MM = 32. PIXEL_ASPE...
20,217
def test_apply_3d(): """test that apply correctly applies a simple function across 3d volumes of a Stack""" stack = synthetic_stack() assert np.all(stack.xarray == 1) stack.apply(divide, in_place=True, value=4, group_by={Axes.ROUND, Axes.CH}) assert (stack.xarray == 0.25).all()
20,218
def pix_to_coord(edges, pix, interp="lin"): """Convert pixel coordinates to grid coordinates using the chosen interpolation scheme.""" scale = interpolation_scale(interp) interp_fn = interp1d( np.arange(len(edges), dtype=float), scale(edges), fill_value="extrapolate" ) return scale.inv...
20,219
def create_action_urls(actions, model=None, **url_args): """ Creates a list of URLs for the given actions. """ urls = {} if len(actions) > 0: # Resolve the url_args values as attributes from the model values = {} for arg in url_args: values[arg] = getattr(model, u...
20,220
def check_vfvx(x0, fx, fx_args, dfx, dfx_args=None, delta=1e-5): """ Check derivatives of a (vectorized) vector or scalar function of a vector variable. """ if x0.ndim != 2: raise ValueError('The variable must have two dimensions!') if dfx_args is None: dfx_args = fx_args d...
20,221
def process( save_data_path: Path, annotations_df: pd.DataFrame, vat_image_directory: Path ) -> None: """ bbox format is [xmin, ymin, xmax, ymax] """ image_path = save_data_path / "imgs" annotations_path = save_data_path / "annotations" create_directory(save_data_path, overwrite=True) cr...
20,222
def test_feature_list_pattern_features(mk_creoson_post_dict, mk_getactivefile): """Test list_group_features.""" c = creopyson.Client() result = c.feature_list_pattern_features( "pattern_name", file_="file", type_="type", ) assert isinstance(result, (list)) result = c.feat...
20,223
def add_hovertool(p1, cr_traj, traj_src, sat_src, traj_df): """Adds a hovertool to the top panel of the data visualization tool plot.""" # Create the JS callback for vertical line on radar plots. callback_htool = CustomJS(args={'traj_src':traj_src,'sat_src':sat_src}, code=""" const indices = cb_d...
20,224
def backpage_url_to_sitekey(url): """http://longisland.backpage.com/FemaleEscorts/s-mny-oo-chics-but-oo-nn-lik-oo-me-19/40317377""" (scheme, netloc, path, params, query, fragment) = urlparse(url) sitekey = netloc.split('.')[0] return sitekey
20,225
def batch_eye_like(X: torch.Tensor): """Return batch of identity matrices like given batch of matrices `X`.""" return torch.eye(*X.shape[1:], out=torch.empty_like(X))[None, :, :].repeat(X.size(0), 1, 1)
20,226
def cal_occurence(correspoding_text_number_list): """ calcualte each occurence of a number in a list """ di = dict() for i in correspoding_text_number_list: i = str(i) s = di.get(i, 0) if s == 0: di[i] = 1 else: di[i] = di[i] + 1 return di
20,227
def subtract(v: Vector, w: Vector) -> Vector: """simple vector subtraction""" assert len(v) == len(w), 'Vectors need to have the same length' return [vi - wi for vi, wi in zip(v, w)]
20,228
def upgradeExplicitOid(store): """ Upgrade a store to use explicit oid columns. This allows VACUUMing the database without corrupting it. This requires copying all of axiom_objects and axiom_types, as well as all item tables that have not yet been upgraded. Consider VACUUMing the database...
20,229
def test_int_init_from_boxfile(): """Test mech init from .box file.""" test_dir = "tests/int/init_from_boxfile" utils.cleanup_dir_and_vms_from_dir(test_dir) ubuntu = "ubuntu-18.04" box_file = "/tmp/{}.box".format(ubuntu) # download the file if we don't have it already # that way we "cache...
20,230
def f1(): """ Filtering 1D. """ # Get center of the filter c = int((size - 1) / 2) # Pad the flatten (1D array) image with wrapping If = np.pad(I.flatten(), (c), 'wrap') # Initialize the resulting image Ir = np.zeros(If.shape) # Apply 1D convulation in the image for x in range(c, Ir.shape[0] - c):...
20,231
def _unify_data_and_user_kwargs( data: 'LayerData', kwargs: Optional[dict] = None, layer_type: Optional[str] = None, fallback_name: str = None, ) -> 'FullLayerData': """Merge data returned from plugins with options specified by user. If ``data == (_data, _meta, _type)``. Then: - ``kwargs`...
20,232
def get_sentence_embeddings(data): """ data -> list: list of text """ features = temb.batch_tokenize(data, tokenizer) dataset = temb.prepare_dataset(features) embeddings = temb.compute_embeddings(dataset, model) return embeddings
20,233
def sample_user(phone="+989123456789", full_name="testname"): """ Create a sample user """ return get_user_model().objects.create_user(phone=phone, full_name=full_name)
20,234
async def metoo(hahayes): """ Haha yes """ if not hahayes.text[0].isalpha() and hahayes.text[0] not in ("/", "#", "@", "!"): await hahayes.edit(random.choice(RENDISTR))
20,235
async def test_import_duplicate_yaml(hass: HomeAssistant) -> None: """Test that the yaml import works.""" MockConfigEntry( domain=DOMAIN, data={"host": "192.168.1.123"}, source=config_entries.SOURCE_IMPORT, unique_id="uuid", ).add_to_hass(hass) with patch( "pyoct...
20,236
def get_word_counts(filepath: str) -> Dict[str, int]: """ Return a dictionary of key-value pairs where keys are words from the given file and values are their counts. If there is no such file, return an empty dictionary. :param filepath: path to the file :return: a dictionary of word counts ...
20,237
def getVanHoveDistances(positions, displacements, L): """ Compte van Hove distances between particles of a system of size `L', with `positions' and `displacements'. Parameters ---------- positions : (*, 2) float array-like Positions of the particles. displacements : (*, 2) float arr...
20,238
def plot_local_coordinate_system_matplotlib( lcs, axes: plt.Axes.axes = None, color: Any = None, label: str = None, time: Union[pd.DatetimeIndex, pd.TimedeltaIndex, List[pd.Timestamp]] = None, time_ref: pd.Timestamp = None, time_index: int = None, show_origin: bool = True, show_trace...
20,239
def saved_searches_list(request): """ Renders the saved_searches_list html """ args = get_saved_searches_list(request.user) return render('saved_searches_list.html', args, request)
20,240
def _blob(x, y, area, colour, val, textcolor="black"): """ Draws a square-shaped blob with the given area (< 1) at the given coordinates. """ hs = np.sqrt(area) / 2 xcorners = np.array([x - hs, x + hs, x + hs, x - hs]) ycorners = np.array([y - hs, y - hs, y + hs, y + hs]) plt.fil...
20,241
def upload(): """Upload files. This endpoint is used to upload "trusted" files; E.i. files created by CERT-EU E.g. CITAR, CIMBL, IDS signatures, etc. **Example request**: .. sourcecode:: http POST /api/1.0/upload HTTP/1.1 Host: do.cert.europa.eu Accept: application/json ...
20,242
def get_active_loan_by_item_pid(item_pid): """Return any active loans for the given item.""" return search_by_pid( item_pid=item_pid, filter_states=current_app.config.get( "CIRCULATION_STATES_LOAN_ACTIVE", [] ), )
20,243
def _get_szymkiewicz_simpson_coefficient(a: Set[X], b: Set[X]) -> float: """Calculate the Szymkiewicz–Simpson coefficient. .. seealso:: https://en.wikipedia.org/wiki/Overlap_coefficient """ if a and b: return len(a.intersection(b)) / min(len(a), len(b)) return 0.0
20,244
def data_splitter( input: pd.DataFrame, ) -> Output(train=pd.DataFrame, test=pd.DataFrame,): """Splits the input dataset into train and test slices.""" train, test = train_test_split(input, test_size=0.1, random_state=13) return train, test
20,245
def reload(module, exclude=('sys', 'os.path', 'builtins', '__main__', 'numpy', 'numpy._globals')): """Recursively reload all modules used in the given module. Optionally takes a list of modules to exclude from reloading. The default exclude list contains sys, __main__, and __bu...
20,246
def get_words_for_board(words, board_size, packing_constant=1.1): """Pick a cutoff which is just beyond limit of the board size.""" # Order the words by length. It's easier to pack shorter words, so prioritize them. # This is SUPER hacky, should have a Word class that handles these representational differe...
20,247
async def test_device_setup_broadlink_exception(hass): """Test we handle a Broadlink exception.""" device = get_device("Office") mock_api = device.get_mock_api() mock_api.auth.side_effect = blke.BroadlinkException() with patch.object( hass.config_entries, "async_forward_entry_setup" ) a...
20,248
def write_cells_from_component( component: Component, dirpath: Optional[PathType] = None ) -> None: """Writes all Component cells. Args: component: dirpath: directory path to write GDS (defaults to CWD) """ dirpath = dirpath or pathlib.Path.cwd() if component.references: ...
20,249
def booleans(key, val): """returns ucsc formatted boolean""" if val in (1, True, "on", "On", "ON"): val = "on" else: val = "off" return val
20,250
def feature_kstest_histograms(dat, covars, batch_list, filepath): """ Plots kernel density plots and computes KS test p-values separated by batch effect groups for a dataset (intended to assess differences in distribution to all batch effects in batch_list following harmonization with NestedComBat ...
20,251
def run_check_handler_sync( check: Check, handler: CheckHandler, *args, **kwargs ) -> None: """Run a check handler and record the result into a Check object. Args: check: The check to record execution results. handler: A callable handler to perform the check. args: A list of positio...
20,252
def merge_param_classes(*cls_list, merge_positional_params: bool = True) -> type(Params): """ Merge multiple Params classes into a single merged params class and return the merged class. Note that this will not flatten the nested classes. :param cls_list: A list of Params subcla...
20,253
def make_pin_list(eff_cnt): """Generates a pin list with an effect pin count given by eff_cnt.""" cards = [1] * eff_cnt cards.extend([0] * (131 - len(cards))) random.shuffle(cards) deck = collections.deque(cards) pin_list = [] for letters, _ in KEY_WHEEL_DATA: pins = [c for c in lett...
20,254
def drop(cols, stmt): """ Function: Drops columns from the statement. Input: List of columns to drop. Output: Statement with columns that are not dropped. """ col_dict = column_dict(stmt) col_names = [c for c in col_dict.keys()] colintention = [c.evaluate(stmt).name if isinstance(c, Int...
20,255
def ConvertVolumeSizeString(volume_size_gb): """Converts the volume size defined in the schema to an int.""" volume_sizes = { "500 GB (128 GB PD SSD x 4)": 500, "1000 GB (256 GB PD SSD x 4)": 1000, } return volume_sizes[volume_size_gb]
20,256
def _check_dims(matrix): """Raise a ValueError if the input matrix has more than two square. Parameters ---------- matrix : numpy.ndarray Input array. """ if matrix.ndim != 2: raise ValueError('Expected a square matrix, got array of shape' ' {0}.'.format(...
20,257
def render_template_with_system_context(value): """ Render provided template with a default system context. :param value: Template string. :type value: ``str`` :param context: Template context. :type context: ``dict`` """ context = { SYSTEM_KV_PREFIX: KeyValueLookup(), } ...
20,258
def ToTranslation(tree, placeholders): """Converts the tree back to a translation, substituting the placeholders back in as required. """ text = tree.ToString() assert text.count(PLACEHOLDER_STRING) == len(placeholders) transl = tclib.Translation() for placeholder in placeholders: index = text.find(PL...
20,259
def complex(real, imag): """Return a 'complex' tensor - If `fft` module is present, returns a propert complex tensor - Otherwise, stack the real and imaginary compoenents along the last dimension. Parameters ---------- real : tensor imag : tensor Returns ------- ...
20,260
def _load_images_from_param_file( param_filename: str, delete: bool, ) -> Iterator[Tuple[np.ndarray, np.ndarray, scene_parameters.SceneParameters]]: """Yields tuples of image and scene parameters. Args: param_filename: read images from this jsonl parameter file. delete: delete images af...
20,261
def get_snps(x: str) -> tuple: """Parse a SNP line and return name, chromsome, position.""" snp, loc = x.split(' ') chrom, position = loc.strip('()').split(':') return snp, chrom, int(position)
20,262
def qr_match(event, context, user=None): """ Function used to associate a given QR code with the given email """ user_coll = coll('users') result = user_coll.update_one({'email': event["link_email"]}, {'$push': {'qrcode': event["qr_code"]}}) if result.matched_count == 1: return {"status...
20,263
def plot_smallnorb(path, is_train=False, samples_per_class=5): """Plot examples from the smallNORB dataset. Execute this command in a Jupyter Notebook. Author: Ashley Gritzman 18/04/2019 Args: is_train: True for the training dataset, False for the test dataset samples_per_class: numb...
20,264
def update_has_started(epoch, settings): """ Tells whether update has started or not :param epoch: epoch number :param settings: settings dictionary :return: True if the update has started, False otherwise """ return is_baseline_with_update(settings['baseline']) and epoch >= settings['updat...
20,265
def compute_i_th_moment_batches(input, i): """ compute the i-th moment for every feature map in the batch :param input: tensor :param i: the moment to be computed :return: """ n, c, h, w = input.size() input = input.view(n, c, -1) mean = torch.mean(input, dim=2).view(n, c, 1, 1) ...
20,266
def hs_online_check(onion, put_url): """Online check for hidden service.""" try: print onion return hs_http_checker(onion, put_url) except Exception as error: print "Returned nothing." print error return ""
20,267
def plotfile(fname, cols=(0,), plotfuncs=None, comments='#', skiprows=0, checkrows=5, delimiter=',', names=None, subplots=True, newfig=True, **kwargs): """ Plot the data in a file. *cols* is a sequence of column identifiers to plot. An identifier is either an int or a string....
20,268
def test_integer(): """ """ unary = np.array([[2, 8, 8], [7, 3, 7], [8, 8, 2], [6, 4, 6]]) edges = np.array([[0, 1], [1, 2], [2, 3]]) edge_weight = np.array([3, 10, 1]) smooth = 1 - np.eye(3) labels = pygco.cut_general_graph(edg...
20,269
def parse_options(): """Parses and checks the command-line options. Returns: A tuple containing the options structure. """ usage = 'Usage: ./update_mapping.py [options]' desc = ('Example: ./update_mapping.py -o mapping.json.\n' 'This script generates and stores a file that gives the\n' 'mapping betwe...
20,270
def test_module(proxies): """ This is the call made when pressing the integration test button. """ # a sample microsoft logo png content = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\xd8\x00\x00\x00.\x08\x03\x00\x00\x00}5\'\xdb\x00' \ b'\x00\x01\x11PLTE\x00\x00\x00sssssssssssssss\xf3P...
20,271
def retrieve(object_type, **kwargs): """Get objects from the Metatlas object database. This will automatically select only objects created by the current user unless `username` is provided. Use `username='*'` to search against all users. Parameters ---------- object_type: string The ...
20,272
def read_plot_pars() : """ Parameters are (in this order): Minimum box width, Maximum box width, Box width iterations, Minimum box length, Maximum box length, Box length iterations, Voltage difference """ def extract_parameter_from_string(string): #returns the part ...
20,273
def _configure(yew): """Prompt user for settings necessary for remote operations. Store in user prefs. Skip secret things like tokens and passwords. """ # the preferences need to be in the form: #  location.default.username for pref in settings.USER_PREFERENCES: if "token" in pref ...
20,274
def install_custom_css( destdir, cssfile, resource=PKGNAME ): """ Add the kernel CSS to custom.css """ ensure_dir_exists( destdir ) custom = os.path.join( destdir, 'custom.css' ) prefix = css_frame_prefix(resource) # Check if custom.css already includes it. If so, let's remove it first ...
20,275
def create(subscribe: typing.Subscription) -> Observable: """Creates an observable sequence object from the specified subscription function. .. marble:: :alt: create [ create(a) ] ---1---2---3---4---| Args: subscribe: Subscription function. Returns: ...
20,276
def tocl(d): """Generate TOC, in-page links to the IDs we're going to define below""" anchors = sorted(d.keys(), key=_lower) return TemplateData(t='All The Things', e=[a for a in anchors])
20,277
def assert_pd_equal(left, right, **kwargs): """Assert equality of two pandas objects.""" if left is None: return method = { pd.Series: pd.testing.assert_series_equal, pd.DataFrame: pd.testing.assert_frame_equal, np.ndarray: np.testing.assert_array_equal, }[left.__class__]...
20,278
def usage(): """simple usage statement to prompt user when issue occur""" print('\nKML from CSV Points -- usage:\n') print('This program takes up to three flags (all optional).') print(' -i sets the path to the input CSV file.') print(' -o sets the path to the output KML file.') print(' ...
20,279
def main( filenames: Iterable[PathLike], recursive: bool = False, verbose: int = 0, ): """ Augment Flake8 noqa comments with PyLint comments. """ # stdlib import functools import glob from itertools import chain # 3rd party from domdf_python_tools.paths import PathPlus # this package from flake2li...
20,280
def get_upper_parentwidget(widget, parent_position: int): """This function replaces this: self.parentWidget().parentWidget().parentWidget() with this: get_upper_parentwidget(self, 3) :param widget: QWidget :param parent_position: Which parent :return: Wanted parent widget ...
20,281
def DirectorySizeAsString(directory): """Returns size of directory as a string.""" return SizeAsString(DirectorySize(directory))
20,282
def test_datetime_pendulum_negative_non_dst(): """ datetime.datetime negative UTC non-DST """ assert ( ormsgpack.packb( [ datetime.datetime( 2018, 12, 1, 2, 3, ...
20,283
def patch_is_tty(value): """ Wrapped test function will have peltak.core.shell.is_tty set to *value*. """ def decorator(fn): # pylint: disable=missing-docstring @wraps(fn) def wrapper(*args, **kw): # pylint: disable=missing-docstring is_tty = shell.is_tty shell.is_tty ...
20,284
def zones_analytics(self): """ API core commands for Cloudflare API""" base = self._base branch = self.zones setattr(branch, "analytics", self._add_unused(base, "zones", "analytics")) branch = self.zones.analytics setattr(branch, "colos", self._add_with_auth(base, "zones...
20,285
def make_bed_from_multi_eland_stream( instream, outstream, name, description, chr_prefix='chr', max_reads=255): """ read a multi eland result file from instream and write the bedfile to outstream :Parameters: - `instream`: stream containing the output f...
20,286
def uniform_unit_scaling(tensor: torch.Tensor, nonlinearity: str = "linear"): """ An initaliser which preserves output variance for approximately gaussian distributed inputs. This boils down to initialising layers using a uniform distribution in the range `(-sqrt(3/dim[0]) * scale, sqrt(3 / dim[0]) * sc...
20,287
def save_level1b_fits(outModel, obs_params, save_dir=None, **kwargs): """Save Level1bModel to FITS and update headers""" # Check if save directory specified in obs_params if save_dir is None: save_dir = obs_params.get('save_dir') file_path = outModel.meta.filename if save_dir is not None: ...
20,288
def get_results(elfFile): """Converts and returns collected data.""" staticSizes = parseElf(elfFile) romSize = sum([size for key, size in staticSizes.items() if key.startswith("rom_")]) ramSize = sum([size for key, size in staticSizes.items() if key.startswith("ram_")]) results = { "rom": ...
20,289
def path_element_to_dict(pb): """datastore.entity_pb.Path_Element converter.""" return { 'type': pb.type(), 'id': pb.id(), 'name': pb.name(), }
20,290
def copy_to_tmp(in_file): """Copies a file to a tempfile. The point of this is to copy small files from CNS to tempdirs on the client when using code that's that hasn't been Google-ified yet. Examples of files are the vocab and config files of the Hugging Face tokenizer. Arguments: in_file: Path to th...
20,291
def segment_sylls_from_songs(audio_dirs, song_seg_dirs, syll_seg_dirs, p, \ shoulder=0.05, img_fn='temp.pdf', verbose=True): """ Split song renditions into syllables, write segments. Enter quantiles to determine where to split the song motif. Entering the same quantile twice will remove it. Note ---- * All th...
20,292
def get_orr_tensor(struct): """ Gets orientation of all molecules in the struct """ molecule_list = get_molecules(struct) orr_tensor = np.zeros((len(molecule_list),3,3)) for i,molecule_struct in enumerate(molecule_list): orr_tensor[i,:,:] = get_molecule_orientation(molecule_struct) return or...
20,293
def make_request_for_quotation(supplier_data=None): """ :param supplier_data: List containing supplier data """ supplier_data = supplier_data if supplier_data else get_supplier_data() rfq = frappe.new_doc('Request for Quotation') rfq.transaction_date = nowdate() rfq.status = 'Draft' rfq.company = '_Test Company...
20,294
def testModule(m): """ Test all the docstrings for classes/functions/methods in a module :param m: Module to test :type m: module """ for name,obj in inspect.getmembers(m): if inspect.isclass(obj): testClass(obj) elif inspect.isfunction(obj): testFunction(obj)
20,295
def mlrPredict(W, data): """ mlrObjFunction predicts the label of data given the data and parameter W of Logistic Regression Input: W: the matrix of weight of size (D + 1) x 10. Each column is the weight vector of a Logistic Regression classifier. X: the data matrix of siz...
20,296
def make_vehicle_random_drive(vehicles): """a thread make vehicle random drive 3s and autopilot 10s""" vehicle = vehicles[0] while True: time.sleep(10) logger.info('Start random drive...') vehicle.set_autopilot(False) steer = random.uniform(-0.2,0.2) throttle = random...
20,297
def write_urdb_rate_data(urdb_rate_data, urdb_filepath = './', overwrite_identical=True): """ Takes Pandas DataFrame containing URDB rate data and stores as .csv at urdb_filepath. The 'overwrite_identical' variable indicates whether 'urdb_rate_data' should be compared to previous URDB download and repl...
20,298
def get_batches_from_generator(iterable, n): """ Batch elements of an iterable into fixed-length chunks or blocks. """ it = iter(iterable) x = tuple(islice(it, n)) while x: yield x x = tuple(islice(it, n))
20,299