content
stringlengths
22
815k
id
int64
0
4.91M
def _estimate_gaussian_covariances_spherical(resp, X, nk, means, reg_covar): """Estimate the spherical variance values. Parameters ---------- responsibilities : array-like of shape (n_samples, n_components) X : array-like of shape (n_samples, n_features) nk : array-like of shape (n_c...
6,200
def parsed_codebook_importer(codebook): """ Import the parsed CPS codebook Parameters: codebook (str): the filename of the parsed codebook Returns: dataframe """ path_finder('codebooks') skip = row_skipper(codebook) codebook = pd.read_csv(codebook, sep='\t', skiprows=sk...
6,201
def put_job_failure(job, message): """Notify CodePipeline of a failed job Args: job: The CodePipeline job ID message: A message to be logged relating to the job status Raises: Exception: Any exception thrown by .put_job_failure_result() """ print...
6,202
def get_html(url): """Returns html content of the url. Retries until successful without overloading the server.""" while True: # Retry until succesful try: sleep(2) debug('Crawling %s' % url) html = urllib2.urlopen(url).read() return html e...
6,203
def clear_cache(): """Clears featurization cache.""" global SMILES_TO_GRAPH SMILES_TO_GRAPH = {}
6,204
def map_min(process): """ """ param_dict = {'ignore_nodata': 'bool'} return map_default(process, 'min', 'reduce', param_dict)
6,205
def geoname_exhaustive_search(request, searchstring): """ List all children of a geoname filtered by a list of featurecodes """ if request.query_params.get('fcode'): fcodes = [ s.upper() for s in request.query_params.get('fcode').split(',')] else: fcodes = [] limit = request.qu...
6,206
def guess_temperature_sensor(): """ Try guessing the location of the installed temperature sensor """ devices = listdir(DEVICE_FOLDER) devices = [device for device in devices if device.startswith('28-')] if devices: # print "Found", len(devices), "devices which maybe temperature sensors....
6,207
def help_systempowerlimit(self, commands): """ Show: limit: Shows the power limit for a server ======================================================= Usage: show system power limit -i {serverid} -i -- serverid, the target server number. Typically 1-48 ...
6,208
def count_reads(regions_list, params): """ Count reads from bam within regions (counts position of cutsite to prevent double-counting) """ bam_f = params.bam read_shift = params.read_shift bam_obj = pysam.AlignmentFile(bam_f, "rb") log_q = params.log_q logger = TobiasLogger("", params.verbosity, log_q) #sending...
6,209
def rgbImage2grayVector(img): """ Turns a row and column rgb image into a 1D grayscale vector """ gray = [] for row_index in range(0, len(img)): for pixel_index, pixel in enumerate(img[row_index]): gray.append(rgbPixel2grayscaleValue(pixel)) return gray
6,210
def compute_MSE(predicted, observed): """ predicted is scalar and observed as array""" if len(observed) == 0: return 0 err = 0 for o in observed: err += (predicted - o)**2/predicted return err/len(observed)
6,211
def log_sum(log_u): """Compute `log(sum(exp(log_u)))`""" if len(log_u) == 0: return NEG_INF maxi = np.argmax(log_u) max = log_u[maxi] if max == NEG_INF: return max else: exp = log_u - max np.exp(exp, out = exp) return np.log1p(np.sum(exp[:maxi]) + np.sum(...
6,212
def rand_2d(rand, width: int, height: int): """ Infinite stream of coordinates on a 2D plane from the random source provided. Assumes indexing [(0, width - 1), (0, height - 1)]. :param rand: Random source with method <i>randint(min, max)</i> with [min, max]. :param width: Width, first dimension...
6,213
def gather_basic_file_info(filename: str): """ Build out the basic file metadata that can be gathered from any file on the file system. Parameters ---------- filename full file path to a file Returns ------- dict basic file attributes as dict """ if not os.path...
6,214
def special_value_sub(lhs, rhs): """ Subtraction between special values or between special values and numbers """ if is_nan(lhs): return FP_QNaN(lhs.precision) elif is_nan(rhs): return FP_QNaN(rhs.precision) elif (is_plus_infty(lhs) and is_plus_infty(rhs)) or \ (is_minus...
6,215
def parse_git_repo(git_repo): """Parse a git repository URL. git-clone(1) lists these as examples of supported URLs: - ssh://[user@]host.xz[:port]/path/to/repo.git/ - git://host.xz[:port]/path/to/repo.git/ - http[s]://host.xz[:port]/path/to/repo.git/ - ftp[s]://host.xz[:port]/path/to/repo.git/...
6,216
def make_wavefunction_list(circuit, include_initial_wavefunction=True): """ simulate the circuit, keeping track of the state vectors at ench step""" wavefunctions = [] simulator = cirq.Simulator() for i, step in enumerate(simulator.simulate_moment_steps(circuit)): wavefunction_scrambled = step....
6,217
def if_else(cond, a, b): """Work around Python 2.4 """ if cond: return a else: return b
6,218
def _update_machine_metadata(esh_driver, esh_machine, data={}): """ NOTE: This will NOT WORK for TAGS until openstack allows JSONArrays as values for metadata! """ if not hasattr(esh_driver._connection, 'ex_set_image_metadata'): logger.info( "EshDriver %s does not have function '...
6,219
def timedelta_to_time(data: pd.Series) -> pd.Series: """Convert ``datetime.timedelta`` data in a series ``datetime.time`` data. Parameters ---------- data : :class:`~pandas.Series` series with data as :class:`datetime.timedelta` Returns ------- :class:`~pandas.Series` seri...
6,220
def bzr_wc_target_exists_version(): """ Test updating a working copy when a target already exists. """ test = 'bzr_wc_target_exists_version' wt = '%s-test-%s' % (DIR, test) puts(magenta('Executing test: %s' % test)) from fabric.api import run from fabtools.files import is_dir from...
6,221
def nms(boxes, scores, iou_thresh, max_output_size): """ Input: boxes: (N,4,2) [x,y] scores: (N) Return: nms_mask: (N) """ box_num = len(boxes) output_size = min(max_output_size, box_num) sorted_indices = sorted(range(len(scores)), key=lambda k: -scores[k]) select...
6,222
def get_db(): """Connect to the application's configured database. The connection is unique for each request and will be reused if this is called again """ if 'db' not in g: g.db = pymysql.connect( host='localhost', port=3306, user='root', password='', database='qm', charset='utf8' ) return...
6,223
def read_stb(library, session): """Reads a status byte of the service request. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :return: Service request status byte. """ status = ViUInt16() library.viReadSTB(session, byref(status)) ...
6,224
def will_expire(certificate, days): """ Returns a dict containing details of a certificate and whether the certificate will expire in the specified number of days. Input can be a PEM string or file path. .. versionadded:: 2016.11.0 certificate: The certificate to be read. Can be a path...
6,225
def write_reset_reg(rst_reg_addr, rst_reg_space_id, rst_reg_val, config): """Write reset register info :param rst_reg_addr: reset register address :param rst_reg_space_id: reset register space id :param rst_reg_val: reset register value :param config: file pointer that opened for writing board confi...
6,226
def one_particle_quasilocal(sp, chli, chlo, Es=None): """ Calculate the one-particle irreducible T-matrix T(1). Parameters ---------- s : Setup Setup object describing the setup chi : int Input schannel cho : int Output channel Es : ndarray List of partic...
6,227
def _CreateIssueForFlake(issue_generator, target_flake, create_or_update_bug): """Creates a monorail bug for a single flake. This function is used to create bugs for detected flakes and flake analysis results. Args: create_or_update_bug (bool): True to create or update monorail bug, otherwise False....
6,228
def get_spilled_samples(spills: List, train_dataset: Dataset): """ Returns the actual data that was spilled. Notice that it returns everything that the __getitem__ returns ie. data and labels and potentially other stuff. This is done to be more general, not just work with datasets that return: (data...
6,229
def reshard( inputs: List[Path], output: Path, tmp: Path = None, free_original: bool = False, rm_original: bool = False, ) -> Path: """Read the given files and concatenate them to the output file. Can remove original files on completion, or just write dummy content into them to free disk. ...
6,230
def on_intent(intent_request, session): """ Called when the user specifies an intent for this skill """ print("on_intent requestId=" + intent_request['requestId'] + ", sessionId=" + session['sessionId']) intent = intent_request['intent'] intent_name = intent_request['intent']['name'] # Dispatch t...
6,231
def load_twitter(path, shuffle=True, rnd=1): """ load text files from twitter data :param path: path of the root directory of the data :param subset: what data will be loaded, train or test or all :param shuffle: :param rnd: random seed value :param vct: vectorizer :return: :raise ValueE...
6,232
def parse_vtables(f): """ Parse a given file f and constructs or extend the vtable function dicts of the module specified in f. :param f: file containing a description of the vtables in a module (*_vtables.txt file) :return: the object representing the module specified in f """ marx_module = Mod...
6,233
def getCifar10Dataset(root, isTrain=True): """Cifar-10 Dataset""" normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) if isTrain: trans = transforms.Compose([ transforms.RandomHorizontalFlip(), transforms.RandomCrop...
6,234
def histogram(layer, num_bins : int = 256, minimum = None, maximum = None, use_cle=True): """ This function determines a histogram for a layer and caches it within the metadata of the layer. If the same histogram is requested, it will be taken from the cache. :return: """ if "bc_histogram_num_bi...
6,235
def get_tbl_type(num_tbl, num_cols, len_tr, content_tbl): """ obtain table type based on table features """ count_very_common = len([i for i, x in enumerate(content_tbl) if re.match(r'^very common',x) ]) count_common = len([i for i, x in enumerate(content_tbl) if re.match(r'^common',x) ]) count_uncommon = ...
6,236
def decode_EAN13(codes): """ คืนสตริงของเลขที่ได้จากการถอดรหัสจากสตริง 0/1 ที่เก็บใน codes แบบ EAN-13 ถ้าเกิดกรณีต่อไปนี้ ให้คืนสตริงว่าง (สาเหตุเหล่านี้มักมาจากเครื่องอ่านบาร์โค้ดอ่านรหัส 0 และ 1 มาผิด) codes เก็บจำนวนบิต หรือรูปแบบไม่ตรงข้อกำหนด รหัสบางส่วนแปลงเป็นตัวเลขไม่ได้ เลขหลักที่ 13...
6,237
def GiveNewT2C(Hc, T2C): """ The main routine, which computes T2C that diagonalized Hc, and is close to the previous T2C transformation, if possible, and it makes the new orbitals Y_i = \sum_m T2C[i,m] Y_{lm} real, if possible. """ ee = linalg.eigh(Hc) Es = ee[0] Us0= ee[1] Us = matrix(e...
6,238
def normalize(form, text): """Return the normal form form for the Unicode string unistr. Valid values for form are 'NFC', 'NFKC', 'NFD', and 'NFKD'. """ return unicodedata.normalize(form, text)
6,239
def handle_internal_validation_error(error): """ Error handler to use when a InternalValidationError is raised. Alert message can be modified here as needed. :param error: The error that is handled. :return: an error view """ alert_message = format_alert_message(error.__class__.__name__...
6,240
def bbox_encode(bboxes, targets): """ :param bboxes: bboxes :param targets: target ground truth boxes :return: deltas """ bw = bboxes[:, 2] - bboxes[:, 0] + 1.0 bh = bboxes[:, 3] - bboxes[:, 1] + 1.0 bx = bboxes[:, 0] + 0.5 * bw by = bboxes[:, 1] + 0.5 * bh tw = targets[:, 2] -...
6,241
def cipher(text: str, key: str, charset: str = DEFAULT_CHARSET) -> str: """ Cipher given text using Vigenere method. Be aware that different languages use different charsets. Default charset is for english language, if you are using any other you should use a proper dataset. For instance, if you are ci...
6,242
def product_delete(product_id): """ Delete product from database """ product_name = product_get_name(product_id) res = False # Delete product from database if product_name: mongo.db.products.delete_one({"_id": (ObjectId(product_id))}) flash( product_name + ...
6,243
def alpha_072(enddate, index='all'): """ Inputs: enddate: 必选参数,计算哪一天的因子 index: 默认参数,股票指数,默认为所有股票'all' Outputs: Series:index 为成分股代码,values为对应的因子值 公式: (rank(decay_linear(correlation(((high + low) / 2), adv40, 8.93345), 10.1519)) / rank(decay_linear(correlation(Ts_Rank(vw...
6,244
def update_input(): """ update all / reads the input and stores it to be returned by read_input() """ global UP, DOWN, LEFT, RIGHT, NEXT, BACK, pygame_events global up_state, down_state, left_state, right_state, next_state, back_state global up_state_prev, down_state_prev, left_state_prev, right_state_prev, next_s...
6,245
def getBoxFolderPathName(annotationDict, newWidth, newHeight): """ getBoxFolderPathName returns the folder name which contains the resized image files for an original image file. Given image 'n02085620_7', you can find the resized images at: 'F:/dogs/images/n02085620-Chihuahua/boxes_64_64/' ...
6,246
def _download_artifact_from_uri(artifact_uri, output_path=None): """ :param artifact_uri: The *absolute* URI of the artifact to download. :param output_path: The local filesystem path to which to download the artifact. If unspecified, a local output path will be created. """ ...
6,247
def api_get_project_members(request, key=None, hproPk=True): """Return the list of project members""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden if settings.PIAPI_STANDALONE: if not settings.PIAPI_REALUSERS: users = [generate_user(pk="-1"), generat...
6,248
def sic_or_lm_silhoutte(image, sensor): """ :param sensor: string with the sensor to be used, options: - mw_sic - lm """ print "Preparing silhoutte for {0} using {1}".format(image, sensor) if sensor == 'mw_sic': img = SIC(image) if sensor...
6,249
def backtest_chart3(Results, title='Portfolio Backtests', figsize=(15, 9), save=False, show=True, colormap='jet'): """ Plots the performance for all efficient frontier portfolios. :param Results: (object) Results object from bt.backtest.Result(*backtests). Refer to the following documentation ...
6,250
def random(n, mind): """Does not guarantee that it's connected (TODO)!""" return bidirectional({i: sample(range(n), mind) for i in range(n)})
6,251
def process_tare_drag(nrun, plot=False): """Processes a single tare drag run.""" print("Processing tare drag run", nrun) times = {0.2: (15, 120), 0.3: (10, 77), 0.4: (10, 56), 0.5: (8, 47), 0.6: (10, 40), 0.7: (8, 33), 0.8: (5, 31...
6,252
def _alpha_blend_numexpr1(rgb1, alpha1, rgb2, alpha2): """ Alternative. Not well optimized """ import numexpr alpha1_ = alpha1[..., None] # NOQA alpha2_ = alpha2[..., None] # NOQA alpha3 = numexpr.evaluate('alpha1 + alpha2 * (1.0 - alpha1)') alpha3_ = alpha3[..., None] # NOQA rgb3 = numex...
6,253
def chunks(arr: list, n: int) -> Generator: """ Yield successive n-sized chunks from arr. :param arr :param n :return generator """ for i in range(0, len(arr), n): yield arr[i:i + n]
6,254
def test_serialize_unknown_type(): """Check that RuleSerializeError is raised on attempt to serialize rule of unknown type. 1. Create rule factory. 2. Register new rule type. 3. Try to serialize a rule with unregistered type. 4. Check that RuleSerializeError is raised. 5. Check the message of t...
6,255
def clean_weight(v): """Clean the weight variable Args: v (pd.Series): Series containing all weight values Returns: v (pd.Series): Series containing all cleaned weight values """ # Filter out erroneous non-float values indices = v.astype(str).apply( lambda x: not re...
6,256
def step_matcher(name): """ DEPRECATED, use :func:`use_step_matcher()` instead. """ # -- BACKWARD-COMPATIBLE NAME: Mark as deprecated. warnings.warn("deprecated: Use 'use_step_matcher()' instead", DeprecationWarning, stacklevel=2) use_step_matcher(name)
6,257
def get_yield(category): """ Get the primitive yield node of a syntactic category. """ if isinstance(category, PrimitiveCategory): return category elif isinstance(category, FunctionalCategory): return get_yield(category.res()) else: raise ValueError("unknown category type with instance %r" % cat...
6,258
def box(type_): """Create a non-iterable box type for an object. Parameters ---------- type_ : type The type to create a box for. Returns ------- box : type A type to box values of type ``type_``. """ class c(object): __slots__ = 'value', def __init...
6,259
def cmorization(in_dir, out_dir, cfg, _): """Cmorization func call.""" cmorizer = OSICmorizer(in_dir, out_dir, cfg, 'sh') cmorizer.cmorize()
6,260
def test__reac__elimination(): """ test elimination functionality """ rct_smis = ['CCCO[O]'] prd_smis = ['CC=C', 'O[O]'] rxn_objs = automol.reac.rxn_objs_from_smiles(rct_smis, prd_smis) rxn, geo, _, _ = rxn_objs[0] # reaction object aligned to z-matrix keys # (for getting torsion coord...
6,261
def rssError(yArr, yHatArr): """ Desc: 计算分析预测误差的大小 Args: yArr:真实的目标变量 yHatArr:预测得到的估计值 Returns: 计算真实值和估计值得到的值的平方和作为最后的返回值 """ return ((yArr - yHatArr) ** 2).sum()
6,262
def initialize_vocabulary(vocabulary_file): """ Initialize vocabulary from file. :param vocabulary_file: file containing vocabulary. :return: vocabulary and reversed vocabulary """ if gfile.Exists(vocabulary_file): rev_vocab = [] with gfile.GFile(vocabulary_file, mode="rb") as f:...
6,263
def mock_create_draft(mocker): """Mock the createDraft OpenAPI. Arguments: mocker: The mocker fixture. Returns: The patched mocker and response data. """ response_data = {"draftNumber": 1} return ( mocker.patch( f"{gas.__name__}.Client.open_api_do", return_...
6,264
def test_vi_xbuild(): """ iv = ['7', '19', '23'] opts = {'--build': True} rv = ['7', '19', '23', '1'] """ pytest.dbgfunc() inp, exp = '7.19.23', '7.19.23.1' assert exp.split('.') == gitr.version_increment(inp.split('.'), {'--build': Tru...
6,265
def to_csv(data_path="data"): """Transform data and save as CSV. Args: data_path (str, optional): Path to dir holding JSON dumps. Defaults to "data". save_path (str, optional): Path to save transformed CSV. Defaults to "data_transformed.csv". """ elements = [] for data in tqdm(list...
6,266
def do_on_subscribe(source: Observable, on_subscribe): """Invokes an action on subscription. This can be helpful for debugging, logging, and other side effects on the start of an operation. Args: on_subscribe: Action to invoke on subscription """ def subscribe(observer, scheduler=None)...
6,267
def get_language_file_path(language): """ :param language: string :return: string: path to where the language file lies """ return "{lang}/localization_{lang}.json".format(lang=language)
6,268
def json_loader(path: str = None) -> Union[Dict, list]: """ Loads json or jsonl data Args: path (str, optional): path to file Returns: objs : Union[Dict, list]: Returns a list or dict of json data json_format : format of file (json or jsonl) """ check_extension = os.pat...
6,269
def handle_response(request_object): """Parses the response from a request object. On an a resolvable error, raises a DataRequestException with a default error message. Parameters ---------- request_object: requests.Response The response object from an executed request. Returns ...
6,270
def _get_zoom_list_recordings_list() -> List[str]: """Get the list of all the recordings.""" # The local path for zoom recording is ~/Documents/Zoom # Get the home directory file_list = os.listdir(ZOOM_DIR) files = [] for f in file_list: files.append(f) files.append(Separator()) ...
6,271
def evaluate(expn): """ Evaluate a simple mathematical expression. @rtype: C{Decimal} """ try: result, err = CalcGrammar(expn).apply('expn') return result except ParseError: raise SyntaxError(u'Could not evaluate the provided mathematical expression')
6,272
def is_device_removable(device): """ This function returns whether a given device is removable or not by looking at the corresponding /sys/block/<device>/removable file @param device: The filesystem path to the device, e.g. /dev/sda1 """ # Shortcut the case where the device an SD card. The kern...
6,273
def get_user(is_external: Optional[bool] = None, name: Optional[str] = None, username: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetUserResult: """ Use this data source to retrieve information about a Rancher v2 user ## Example Usa...
6,274
def randbytes(size) -> bytes: """Custom implementation of random.randbytes, since that's a Python 3.9 feature """ return bytes(random.sample(list(range(0, 255)), size))
6,275
def path_to_model(path): """Return model name from path.""" epoch = str(path).split("phase")[-1] model = str(path).split("_dir/")[0].split("/")[-1] return f"{model}_epoch{epoch}"
6,276
def _cpp_het_stat(amplitude_distribution, t_stop, rates, t_start=0.*pq.ms): """ Generate a Compound Poisson Process (CPP) with amplitude distribution A and heterogeneous firing rates r=r[0], r[1], ..., r[-1]. Parameters ---------- amplitude_distribution : np.ndarray CPP's amplitude dist...
6,277
def validate_uncles(state, block): """Validate the uncles of this block.""" # Make sure hash matches up if utils.sha3(rlp.encode(block.uncles)) != block.header.uncles_hash: raise VerificationFailed("Uncle hash mismatch") # Enforce maximum number of uncles if len(block.uncles) > state.config[...
6,278
def quote_index(q_t,tr_t): """Get start and end index of quote times in `q_t` with the same timestamp as trade times in `tr_t`.""" left, right = get_ind(q_t,tr_t) right[left<right] -=1 # last quote cannot be traded on, so shift index left -=1 # consider last quote from before the timestamp of the...
6,279
def calculate_learning_curves_train_test(K, y, train_indices, test_indices, sampled_order_train, tau, stop_t=None): """Calculate learning curves (train, test) from running herding algorithm Using the sampled order from the sampled_order indexing array calculate the ...
6,280
def json2vcf(jsonfile, outputfile): """Function to grab variant(s) from JSON file and spit out VCF in outputdir. Currently this function assumes that there is a chromosome field that has the chromosome number encoded in 'code'. Hopefully this generalizes.""" # Make the vcf file w/ header vcf_filenam...
6,281
def _CheckRequirements(requirements_file_path): """Checks that all package requirements specified in a file are met. Args: requirements_file_path: string. Path to a pip requirements file. """ try: with open(requirements_file_path, 'rb') as fp: for line in fp: pkg_resources.require(line) ...
6,282
def create_account(param: CreateAccountParams) -> Transaction: """Generate a Transaction that creates a new account.""" raise NotImplementedError("create_account not implemented")
6,283
def check(datapath, config, output): """Cli for apps/morph_check.""" morph_check.main(datapath, config, output)
6,284
def removeString2(string, removeLen): """骚操作 直接使用字符串替换""" alphaNums = [] for c in string: if c not in alphaNums: alphaNums.append(c) while True: preLength = len(string) for c in alphaNums: replaceStr = c * removeLen string = string.replace(rep...
6,285
def process_filing(client, file_path: str, filing_buffer: Union[str, bytes] = None, store_raw: bool = False, store_text: bool = False): """ Process a filing from a path or filing buffer. :param file_path: path to process; if filing_buffer is none, retrieved from here :param filing_buf...
6,286
def metadata_file(): """ Return the path to the first (as per a descending alphabetic sort) .csv file found at the expected location (<ffmeta_package_dir>/data/*.csv) This is assumed to be the latest metadata csv file. :return: The absolute path of the latest metadata csv file. """ dirna...
6,287
def determineDicom(importedFile): """ Determines whether the Dicom file is PET, CT or invalid""" dicom_info = pydicom.dcmread(importedFile) # Different file types passes to one of two functions. if dicom_info.Modality == 'CT': textArea.insert(END, 'CT Dicom file:\n') CTdicom(importedFi...
6,288
def _get_anchor_negative_triplet_mask(labels): """Return a 2D mask where mask[a, n] is True iff a and n have distinct labels. Args: labels: tf.int32 `Tensor` with shape [batch_size] Returns: mask: tf.bool `Tensor` with shape [batch_size, batch_size] """ # Check if labels[i] != labels...
6,289
def add_tax_data(file_location): """Adds tax data""" data = read_csv_file(file_location) session = setup_session() list_size = len(data) list_counter = 0 for entry in data: if (entry[0] == "QLD"): list_counter += 1 tax = Tax( postcode = entry[1], ...
6,290
async def test_wait_form_displayed_after_checking(hass, smartthings_mock): """Test error is shown when the user has not installed the app.""" flow = SmartThingsFlowHandler() flow.hass = hass flow.access_token = str(uuid4()) result = await flow.async_step_wait_install({}) assert result['type'] ...
6,291
def test_H(): """Tests the Hamiltonian. """ from pydft.schrodinger import _H from numpy.matlib import randn s = [6,6,4] R = np.array([[6,0,0],[0,6,0],[0,0,6]]) a = np.array(randn(np.prod(s), 1) + 1j*randn(np.prod(s), 1)) b = np.array(randn(np.prod(s), 1) + 1j*randn(np.prod(s), 1)) ...
6,292
def random_k_edge_connected_graph(size, k, p=.1, rng=None): """ Super hacky way of getting a random k-connected graph Example: >>> from graphid import util >>> size, k, p = 25, 3, .1 >>> rng = util.ensure_rng(0) >>> gs = [] >>> for x in range(4): >>> G = ...
6,293
def finish_round(): """Clean up the folders at the end of the round. After round N, the cur-round folder is renamed to round-N. """ last_round = get_last_round_num() cur_round = last_round + 1 round_dir = os.path.join("rounds", f"round-{cur_round}") os.rename(CUR_ROUND_DIR, round_dir) ...
6,294
def _SendGerritJsonRequest( host: str, path: str, reqtype: str = 'GET', headers: Optional[Dict[str, str]] = None, body: Any = None, accept_statuses: FrozenSet[int] = frozenset([200]), ) -> Optional[Any]: """Send a request to Gerrit, expecting a JSON response.""" result = _SendGerritHttpReque...
6,295
def contains_sequence(dna_sequence, subsequence): """ Checks if a defined subsequence exists in a sequence of dna. :param dna_sequence: The dna sequence to check in for a subsequence. ex: ['a', 't', 'g', ...] :param subsequence: The subsequence of the dna to check for. :return: True if...
6,296
def test_sep_digits(): """Must separate digits on 1000s.""" func = utils.sep_digits assert func('12345678') == '12345678' assert func(12345678) == '12 345 678' assert func(1234.5678) == '1 234.57' assert func(1234.5678, precision=4) == '1 234.5678' assert func(1234.0, precision=4) == '1 234....
6,297
def readTableRules(p4info_helper, sw, table): """ Reads the table entries from all tables on the switch. :param p4info_helper: the P4Info helper :param sw: the switch connection """ print '\n----- Reading tables rules for %s -----' % sw.name ReadTableEntries1 = {'table_entries': []} Read...
6,298
def alpha_043(code, end_date=None, fq="pre"): """ 公式: SUM((CLOSE>DELAY(CLOSE,1)?VOLUME:(CLOSE<DELAY(CLOSE,1)?-VOLUME:0)),6) Inputs: code: 股票池 end_date: 查询日期 Outputs: 因子的值 """ end_date = to_date_str(end_date) func_name = sys._getframe().f_code.co_name retur...
6,299