content
stringlengths
22
815k
id
int64
0
4.91M
def encode(*args, **kwargs): """ A helper function to encode an element. @param args: The python data to be encoded. @kwarg encoding: AMF encoding type. One of L{ENCODING_TYPES}. @return: A L{util.BufferedByteStream} object that contains the data. """ encoding = kwargs.pop('encoding', DEFAU...
46,000
def fenergy_symmetric_bar( work_ab: ArrayLike, work_bc: ArrayLike, uncertainty_method: str = "BAR", ) -> Tuple[float, float]: """BAR for symmetric periodic protocols. Args: work_ab: Measurements of work from first half of protocol. work_bc: Measurements of work from mirror image sec...
46,001
def format_resolution(resolution): """For debugging, convert resolution dict from resolve_citations() to just the matched_text() of each cite, like {'1 U.S. 1': ['1 U.S. 1', '1 U.S., at 2']}. """ return { k.citation.matched_text(): [i.matched_text() for i in v] for k, v in resolu...
46,002
def mod_arr_fit(ktp_dct, mess_path, fit_type='single', fit_method='dsarrfit', t_ref=1.0, a_conv_factor=1.0, inp_param_dct=None): """ Routine for a single reaction: (1) Grab high-pressure and pressure-dependent rate constants from a MESS output file (2)...
46,003
def _choose_image_ids(selected: Union[None, int, Sequence[int]], available: List[int]) -> List[int]: """Choose which image ids to load from disk.""" # Load all. if selected is None: return available # Load a random selection. if isinstance(selected, int): if selected > len(avai...
46,004
def test_7_custom_docker_lines_train(): """Check that setup.py dockerlines works as expected for training""" # Build the distribution without building the image code = baklava.train(example('7-custom-docker-lines'), ['--nobuild']) assert code == 0 test_7_build_and_check()
46,005
def _post_process_fd(numdata: FDNumericalData) -> None: """Compute dependent numerical arrays from the numerical data after running solver. All updated numerical arrays are stored in the numdata parameter. """ nd = numdata nd.lengths = normrow(nd.C.dot(nd.xyz)) numdata.forces = nd.q * nd.lengths
46,006
def _open_file(name, mode): """ Opens a file in the specified mode. If the mite or M2kinter module is available the path given is not absolute, the writepath or datapath (depending on the specified mode) is searched first. """ if not name: raise OpalFileException('File name cannot be emp...
46,007
def searchsploitout(): """ Convoluted name for the display. takes the global search terms and prints out a display iterating through every database available and printing out the results of the search. """ # ## Used in searchsploitout/nmap's XML # xx validating terms validTerm(terms) if parseAr...
46,008
def canonical_message_builder(content, fmt): """Builds the canonical message to be verified. Sorts the fields as a requirement from AWS Args: content (dict): Parsed body of the response fmt (list): List of the fields that need to go into the message Returns (str): canonical mes...
46,009
def get_random_image(shape): """ Expects something like shape=(480,640,3) :param shape: tuple of shape for numpy array, for example from my_array.shape :type shape: tuple of ints :return random_image: :rtype: np.ndarray """ if random.random() < 0.5: rand_image = get_...
46,010
def evaluate(model, val_loader, device): """ model: CNN networks val_loader: a Dataloader object with validation data device: evaluate on cpu or gpu device return classification accuracy of the model on val dataset """ # evaluate the model model.eval() # context-manager that disabled...
46,011
def estimateInharmonicity(inputFile = '../../sounds/piano.wav', t1=0.1, t2=0.5, window='hamming', M=2048, N=2048, H=128, f0et=5.0, t=-90, minf0=130, maxf0=180, nH = 10): """ Function to estimate the extent of inharmonicity present in a sound Input: inputFile (string): wa...
46,012
def download_wordlist_http(filedown): """ do the HTTP download of a wordlist """ mkdir_if_not_exists("dictionaries") # List of files to download: arguments = { 1: ( "Moby", ( "mhyph.tar.gz", "mlang.tar.gz", "moby.tar.gz", ...
46,013
def _get_default_secret(var, default): """ Get default or raise MissingSecretError. """ if isinstance(default, attr.Factory): return attr.NOTHING elif isinstance(default, Raise): raise MissingSecretError(var) return default
46,014
def draw_region(region, ax): """Draw a QuadTreeRegion in a plot Parameters ---------- region: `QuadTreeRegion` The region to draw ax: `matplotlib.Axis` The axis on which to draw the box """ box = region.bbox draw_box(box, ax, "r") if region.sub_regions is not None: ...
46,015
def make_df_pred_ARIMA(df_prices, steps): """ This function creates the DataFrame which has the tickers, closing prices and predicted values based on ARIMA model for a selected number of steps ahead.""" # Sort values from the oldest values to the newest ones in order to fit # the model. df_true...
46,016
def merge_similar_bounds(json_data: dict, file_names: list, bounds_list: list) -> dict: """Finds keys in a dictionary where there bounds are similar and merges them. Parameters ---------- json_data : dict Dictionary data from which the data informations were extracted from. file_names : lis...
46,017
def is_base64(s): """Return True if input string is base64, false otherwise.""" s = s.strip("'\"") try: if isinstance(s, str): sb_bytes = bytes(s, 'ascii') elif isinstance(s, bytes): sb_bytes = s else: raise ValueError("Argument must be string or b...
46,018
async def change_status() -> None: """ Changes the bot's status """ await client.change_presence( activity=discord.Activity( type=discord.ActivityType.listening, name=f'appeals on /appeal.') )
46,019
def get_coco(opt, coco_path): """Get coco dataset.""" train_dataset = CenterMultiPoseDataset(opt, split = 'train') # custom dataset val_dataset = CenterMultiPoseDataset(opt, split = 'val') # custom dataset opt.val_interval = 10 return train_dataset, val_dataset
46,020
def load_preceding_experiment_data(exp: Experiment, load_path): """ Enriches the experiment with already known results from the given csv containing experiment data. """ loaded_data_df: DataFrame = pd.read_csv(load_path) loaded_data: Data = Data(loaded_data_df) exp.attach_data(loaded_data) ...
46,021
def _get_output_columns(nodes, context): """Get the output columns for a list of SqlNodes. Args: nodes: List[SqlNode], the nodes to get output columns from. context: CompilationContext, global compilation state and metadata. Returns: List[Column], list of SqlAlchemy Columns to outp...
46,022
def main(): """The Imperial March Sounds""" args = get_args() random.seed(args.seed) sequence_number = 0 pool = create_pool(args.pctgc, args.maxlen, args.seqtype) for _ in range(args.numseqs): sequence_number += 1 seq_len = random.randint(args.minlen, args.maxlen) seq =...
46,023
def notif(message): """ docstring """ #message= mess.text #print(message) #print(type(message)) query= str(message).split(',') #print(query) if(len(query)==2): #print(eval(query[1])) list_str= final.ajio_care.find_stock(eval(query[0]),eval(query[1])) #return l...
46,024
def parse_args(): """ Parses command line arguments """ parser = optparse.OptionParser( version=nodeenv_version, usage="%prog [OPTIONS] ENV_DIR") parser.add_option('-n', '--node', dest='node', metavar='NODE_VER', default=get_last_stable_node_version(), help='The nod...
46,025
def float32(x): """Returns a 32-bit floating point representation of the input. Only defined for basic scalar types.""" return np.float32(x)
46,026
def assert_bool_op_api( opname, bool_frame_with_na, float_string_frame, has_bool_only=False ): """ Check that API for boolean operator opname works as advertised on frame Parameters ---------- opname : str Name of the operator to test on frame float_frame : DataFrame DataFra...
46,027
def collect_test_names(): """ " Finds all test names in `TEST_DATA_DIR` which have are valid, i.e. which have both a C file and associated gcc AST json """ test_data_dir_path = Path(TEST_DATA_DIR) c_files = test_data_dir_path.glob("*.c") ast_files = test_data_dir_path.glob("*_gcc_ast.json") ...
46,028
def read_from_file(filename): """Read from a file located at `filename` and return the corresponding graph object.""" file = open(filename, "r") lines = file.readlines() file.close() # Check if it is a graph or digraph graph_or_digraph_str = lines[0].strip() if len(lines) > 0 else None if ...
46,029
def inner_product(t, abar, b, axis=None, apply_conjugate=False): """Perform a time-domain complex inner product between two waveforms <a, b>. This is implemented using spline interpolation, calling quaternion.calculus.spline_definite_integral Parameters ---------- t : array_like Time s...
46,030
def build_datamodel(good_pbks: List[str], is_supply: bool) -> DataModel: """ Build a data model for supply and demand (i.e. for offered or requested goods). :param good_pbks: the list of good public keys :param is_supply: Boolean indicating whether it is a supply or demand data model :return: the ...
46,031
def set_subject_status(client_id: str, email: str, status: Status) -> None: """Set a subject's status""" with connection() as conn: with conn: conn.execute(""" UPDATE subjects SET status = ? WHERE client_...
46,032
def tryReduceOr(sig, val): """ Return sig and val reduced by | operator or None if it is not possible to statically reduce expression """ m = sig._dtype.all_mask() if not val.vldMask: return val if val._isFullVld(): v = val.val if v == m: return val ...
46,033
def _load_data(batch, targets): """Load data into sliced arrays""" _load_general(batch.data, targets)
46,034
def get_mod_from_id(mod_id, mod_list): """ Returns the mod for given mod or None if it isn't found. Parameters ---------- mod_id : str The mod identifier to look for mod_list : list[DatRecord] List of mods to search in (or dat file) Returns ------- DatRecord or Non...
46,035
def resize(image): """ Resize the image to the input shape used by the network model """ return cv2.resize(image, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA)
46,036
def exp_f(name): """"Similar to E but trains to full 3001 epochs""" print("e82 but with seq length 2000 and 5 appliances and learning rate 0.01 and train and validation on all 5 houses") source = RealApplianceSource( filename='/data/dk3810/ukdale.h5', appliances=[ ['fridge freeze...
46,037
def indices_2_one_hot(indices, n): """ Converts a list of indices into one hot codification :param indices: list of indices :param n: integer. Size of the vocabulary :return: numpy array with shape (len(indices), n) """ one_hot = np.zeros((len(indices), n), dtype=np.int8) for i in range...
46,038
def extract_tables(query: str) -> Set[Table]: """ Helper function to extract tables referenced in a query. """ return ParsedQuery(query).tables
46,039
def clear_flow_monitor(device, name, option=''): """ clear flow monitor data Args: device (`obj`): Device object name ('str'): Name of the flow (eg: created[ipv4_input] or user defined[monitor_ipv4_out]) option ('str', optional): Which data to clear....
46,040
def master_operation(matrix): """ Split the initial matrix into tasks and distribute them among slave operations """ workers = MPI.COMM_WORLD.Get_size() accumulator = [] task_queue = [] if not matrix[0][0]: task_queue.append([(0, 0)]) while True: sent_workers = [] ...
46,041
def _weight_mean_color(graph, src, dst, n): """Callback to handle merging nodes by recomputing mean color. The method expects that the mean color of `dst` is already computed. Parameters ---------- graph : RAG The graph under consideration. src, dst : int The vertices in `graph...
46,042
def predict(model, pTestSet, pModelParams, pNoConvertBack): """ Function to predict test set Attributes: model -- model to use testSet -- testSet to be predicted conversion -- conversion function used when training the model """ #copy the test set, before invalidated rows and...
46,043
def poisson_log_likelihood(x, log_rate): """Compute the log likelihood under Poisson distribution. log poisson(k, r) = log(r^k * e^(-r) / k!) = k log(r) - r - log k! log poisson(k, r=exp(l)) = k * l - exp(l) - lgamma(k + 1) Args: x: binned spike count data. log_rate: The (log...
46,044
def test_obs_load_and_write(): """ test041 load and write of MODFLOW-2005 OBS example problem """ pth = os.path.join('..', 'examples', 'data', 'mf2005_obs') opth = os.path.join(cpth, 'tc1-true', 'orig') # delete the directory if it exists if os.path.isdir(opth): shutil.rmtree(opth) ...
46,045
def plat_gen(platforms, sprites, screen_width, screen_height): """Generate the platform obstacles for the game.""" # generate 4 platforms for i in range(4): platform = Platform(screen_width, screen_height) # add platforms to lists platforms.add(platform) sprites.add(platfor...
46,046
def distance(point1, point2): """ Return the distance between two points.""" dx = point1[0] - point2[0] dy = point1[1] - point2[1] return math.sqrt(dx * dx + dy * dy)
46,047
def get_filesystem_perf_results(result_dir, pred_type='classification'): """ Retrieve model metadata and performance metrics stored in the filesystem from a hyperparameter search run. """ model_uuid_list = [] model_type_list = [] max_epochs_list = [] learning_rate_list = [] dropouts_list...
46,048
def order_of_magnitude(value): """ Returns the order of magnitude of the most significant digit of the specified number. A value of zero signifies the ones digit, as would be the case in [Number]*10^[Order]. :param value: :return: """ x = abs(float(value)) offset = 0 if x >= 1.0 el...
46,049
def compute_discounted_R(R, discount_rate=1): """Returns discounted rewards Args: R (1-D array): a list of `reward` at each time step discount_rate (float): Will discount the future value by this rate Returns: discounted_r (1-D array): same shape as input `R` but the valu...
46,050
def setup_dom_for_char(character, create_dompc=True, create_assets=True, region=None, srank=None, family=None, liege_domain=None, create_domain=True, create_liege=True, create_vassals=True, num_vassals=2): """ Creates both a PlayerOrNpc i...
46,051
def verify_memtune_xml(params, env): """ Check the memtune in the guest xml """ params.doc_logger.info(STEPS + "# virsh dumpxml %s" % (params.guest_name)) params.doc_logger.info(RESULT) if params.memtune.hardlimit: params.doc_logger.info(""" <hard_limit unit='KiB'>%d</hard_limit> ...
46,052
def cumulative_sum(t): """ Return a new list where the ith element is the sum of all elements up to that position in the list. Ex: [1, 2, 3] returns [1, 3, 6] """ res = [t[0]] for i in range(1, len(t)): res.append(res[-1] + t[i]) return res
46,053
def update_raw_data_unifytlogc_state(raw_data_id, action): """ 为data_id 创建或清除相关tag """ if action == ENABLE: tags.create_tags(settings.TARGET_TYPE_ACCESS_RAW_DATA, raw_data_id, [USE_V2_UNIFYTLOGC_TAG]) elif action == DISABLE: tags.delete_tags(settings.TARGET_TYPE_ACCESS_RAW_DATA, raw_...
46,054
def WIS(x, q, x_q, norm=False, log=False, smooth=False): """ Parameters ---------- : TODO : TODO Returns ------- : TODO """ # todo sort q and x_q based on q K = len(q) // 2 alps = np.array([1 - q[-i - 1] + q[i] for i in range(K)]) Fs = np.arra...
46,055
def update_documents_in_collection(resource) -> Tuple[Response, int]: """Endpoint for updating multiple documents.""" try: collection_name = services.check_resource_name(resource) request_args = request.args.copy() filters = ["_projection", "_sort", "_limit", "_skip"] for item...
46,056
def generate_prior_data(Pi, a_prior, b_prior): """Return column data sources needed to generate prior distribution.""" # Prior probability distribution n = 1000 x = np.linspace(0, 1, n) dist = beta(a_prior, b_prior) p = dist.pdf(x) # Arrays for the area under the curve patch xs = np.hs...
46,057
def InteractionFingerprintAtomic(ligand, protein, strict=True): """Interaction fingerprint accomplished by converting the molecular interaction of ligand-protein into bit array according to the residue of choice and the interaction. For every residue (One row = one residue) there are eight bits which re...
46,058
def add_subject_conditions( data: pd.DataFrame, condition_list: Union[SubjectConditionDict, SubjectConditionDataFrame] ) -> pd.DataFrame: """Add subject conditions to dataframe. This function expects a dataframe with data from multiple subjects and information on which subject belongs to which conditio...
46,059
def chinese_remainder(n1: int, r1: int, n2: int, r2: int) -> int: """ >>> chinese_remainder(5,1,7,3) 31 penjelasan : 31 adalah nomor yang paling kecil ketika dibagi dengan 5 kita dapat hasil bagi 1 ketika dibagi dengan 7 kita dapat hasil bagi 3 """ (x, y) = extended_euclid(n1, n2) m...
46,060
def likelihood(angle, displacement, ln_variance, z, s, debug=False): """ Returns theano function from the angle, displacement, ln_variance2 theano.scalars """ variance = tt.exp(ln_variance) # gradient = tt.tan(angle) v = tt.stacklists([[-np.sin(angle)], [np.cos(angle)]]) delta = tt.dot(v.T,...
46,061
def query_factorize_industry_df(factorize_arr, market=None): """ 使用match_industries_factorize可以查询到行业所对应的factorize序列, 使用factorize序列即组成需要查询的行业组合,返回行业组合pd.DataFrame对象 eg: 从美股所有行业中找到中国企业的行业 input:ABuIndustries.match_industries_factorize('中国', market=EMarketTargetType.E_MARKET_TARGET_US) outp...
46,062
def rbac_assign_roles(email, roles, tenant=None): """assign a list of roles to email""" tstr = " -tenant=%s " % (tenant) if tenant else "" roles = ",".join(roles) rc = run_command("%s user-role -op assign -user-email %s -roles %s %s" % ( g_araalictl_path, email, roles, tstr), ...
46,063
def haversine_np(lon1, lat1, lon2, lat2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) Reference: https://stackoverflow.com/a/29546836/7657658 https://gist.github.com/mazzma12/6dbcc71ab3b579c08d66a968ff509901 """ lon1, la...
46,064
def test_nhc_archives(): """Test that storm dictionaries from before current year are being sifted correctly.""" # Perform test on Hurricane Anna from 1976 nhc = NHCD() models = nhc.get_tracks(1976, ' al061976') nhc.model_selection_latlon(models) # Asserting characteristics of first forecast fo...
46,065
def basename_wo_ext( path: typing.Union[str, bytes], *, ext: str = None ) -> str: """File basename without file extension. Args: path: file or directory name ext: explicit extension to be removed Returns: basename of directory or file without extension ...
46,066
def test_decr_unix_socket(): """TCPStatsClient.decr works.""" cl = _unix_socket_client() _test_decr(cl, 'unix')
46,067
def extract_current_step(current_status_string): """ Attempts to extract the current step numeric identifier from the given status string. Returns the step number or None if none. """ # Older format: `Step 12 :` # Newer format: `Step 4/13 :` step_increment = re.search(r"Step ([0-9]+)/([0-9]+) :"...
46,068
def unique1d(ar1, return_index=False, return_inverse=False): """ Find the unique elements of an array. Parameters ---------- ar1 : array_like This array will be flattened if it is not already 1-D. return_index : bool, optional If True, also return the indices against `ar1` that ...
46,069
def login_required(func): """ Decorator check required login and active user :param func: :return: """ @wraps(func) def decorated_view(*args, **kwargs): if current_app.login_manager._login_disabled: return func(*args, **kwargs) elif not current_user.is...
46,070
def prepare_statement(template, values): """Correctly escape things and keep as unicode. pyscopg2 has a default encoding of `latin-1`: https://github.com/psycopg/psycopg2/issues/331""" new_values = [] for value in values: adapted = adapt(value) adapted.encoding = 'utf-8' new_val...
46,071
def addgroup(request): """Add group form.""" return render( request, 'addgroup.htm', context={}, )
46,072
def cached_function_method_signature(ctx: MethodSigContext) -> CallableType: """Fixes the `_CachedFunction.__call__` signature to be correct. It already has *almost* the correct signature, except: 1. the `self` argument needs to be marked as "bound"; 2. any `cache_context` argument should be r...
46,073
def load_valid_data_full(): """ load validation data from disk """ hdf5_file_valid = h5py.File(HDF5_PATH_VALID, "r") data_num_valid = hdf5_file_valid["valid_img"].shape[0] images_valid = np.array(hdf5_file_valid["valid_img"][:]) # your test set features labels_valid = np.array(hdf5_file_val...
46,074
def import_slab_structures(filename): """Read 2D water structures from file and return a dictionary of it. Parameters ---------- filename : str Filename of the file containing the bulk structures Returns ------- filedict : dict Dictionary of the structures """ file...
46,075
def test_conserved_n(seir_data): """Checks if S + E + I + R is conserved for SEIR """ x, pars = seir_data n_total = 0 for key in SEIRModel.compartments: n_total += pars[f"initial_{key}"] seir_model = SEIRModel() predictions = seir_model.propagate_uncertainties(x, pars) n_compu...
46,076
def main_Music(): """Main music""" pygame.mixer.music.load(sounds + 'main.mp3') pygame.mixer.music.play(-1)
46,077
def handle_email(text): """Summary Args: text (TYPE): Description Returns: TYPE: Description """ return re.sub(r'(\w+@\w+)', Replacement.EMAIL.value, text)
46,078
def LowerCustomDatatypes(): """Lower custom datatypes. See tvm::datatypes::Registry for more information on adding custom datatypes. Returns ------- fpass : tvm.ir.transform.Pass The result pass """ return _ffi_api.LowerCustomDatatypes()
46,079
def apply_if_or_value( maybe_value: typing.Optional[typing.Any], operation: typing.Callable[[typing.Any], typing.Any], fallback_value: typing.Any, ) -> typing.Any: """Attempt to apply operation to maybe_value, returning fallback_value if maybe_value is None. Almost a convenience composition of ...
46,080
def process_arxiv_feeds( section_codes: Union[List[str], Tuple[str]], output_dir: str ) -> None: """Download, clean, and re-export one or more arXiv RSS feeds. Args: section_codes (list[str]): arXiv section identifiers output_dir (str): where to write the updated XML files """ feeds...
46,081
def write(target_path: str, tag: _typing.AnyStr) -> None: """ For writing to .tk files """ ## Data ## fn = _getFN.get_filename(target_path) file_ext = _getFN.get_file_ext(fn) ## Data ## ## Checks ## assert _os.path...
46,082
def make_pyg_dataset_from_dataframe( df: pd.DataFrame, list_n: list, list_e: list, paired=False, mode: str = "all" ) -> list: """Take a Dataframe, a list of strings of node features, a list of strings of edge features and return a List of PyG Data objects. Parameters ---------- df DataF...
46,083
def ucfirst(string: str): """Return the string with the first character in upper case.""" return _change_first_case(string, upper=True)
46,084
def gumbel_softmax(log_pi, tau=0.1, axis=1): """Gumbel-Softmax sampling function. This function draws samples :math:`y_i` from Gumbel-Softmax distribution, .. math:: y_i = {\\exp((g_i + \\log\\pi_i)/\\tau) \\over \\sum_{j}\\exp((g_j + \\log\\pi_j)/\\tau)}, where :math:`\\tau` is a tem...
46,085
def has_active_lease(storage_server, storage_index, now): """ :param allmydata.storage.server.StorageServer storage_server: A storage server to use to look up lease information. :param bytes storage_index: A storage index to use to look up lease information. :param float now: The curre...
46,086
def _enumerate_files(path: str, parts: List[str], repl_list1: List[str], repl_list2: List[str] = None) -> str: """ Enumerate all possible file names """ if len(parts) <= 2: for token in repl_list1: parts[-1] = token candidate = os.path.join(path, ''.join(parts)) if os...
46,087
def MXfunc(A, At, d1, p1): """ Compute P^{-1}X (PCG) y = P^{-1}*x """ def matvec(x): return p1 * x N = p1.shape[0] return LinearOperator((N, N), matvec=matvec)
46,088
def filter(predicate: Predicate[_T]) -> Callable[[Observable[_T]], Observable[_T]]: """Filters the elements of an observable sequence based on a predicate. .. marble:: :alt: filter ----1---2---3---4---| [ filter(i: i>2) ] ------------3---4---| Example: >>> o...
46,089
def SimpleCycle(Ref,Te,Tc,DTsh,DTsc,eta_a,Ts_Ph='Ph',**kwargs): """ This function plots a simple four-component cycle, on the current axis, or that given by the optional parameter *axis* Required parameters: * Ref : A string for the refrigerant * Te : Evap Temperature in K * Tc : Condensing Te...
46,090
def scb_to_unit(scb): """Convert codes used by Statistics Sweden to units used by the NAD GIS files.""" scbform = 'SE/' + '{:0<9}'.format(scb) if scbform in g_units.index: return g_units.loc[scbform, 'G_unit'] else: return 0
46,091
async def async_setup_platform(hass, config, async_add_devices, discovery_info=None): """Old way of setting up Hue lights. Can only be called when a user accidentally mentions hue platform in their config. But even in that case it would have been ignored. """ pass
46,092
def revision_pattern_from_build_bucket_path(bucket_path): """Get the revision pattern from a build bucket path.""" return '.*?' + os.path.basename(bucket_path)
46,093
def img_to_square(im_pic): """ 把图片处理成正方形 :param im_pic: :return: """ w, h = im_pic.size if w >= h: w_start = (w - h) * 0.618 box = (w_start, 0, w_start + h, h) region = im_pic.crop(box) else: h_start = (h - w) * 0.618 box = (0, h_start, w, h_start + w)...
46,094
def load_sentence( filename: str, with_symbol: bool=True ) -> List[str]: """コーパスをロードする。""" if with_symbol: tokens = [ list(sent.split()) + [config.END_SYMBOL] for sent in (_.strip() for _ in open(filename)) ] else: tokens = [ list(sent.spli...
46,095
def main(): """ Main game code Contains pygame setup and the main game loop """ alternative_pointer = True # Use precise mouse pointer ants_underground_display = ant_class.ants_underground pygame.init() # Initialise pygame logger.log("Init done", important=True) # Set window titl...
46,096
def to_str(bytes_or_str): """ The first function takes a bytes or str instance and always returns a str. """ if isinstance(bytes_or_str, bytes): value = bytes_or_str.decode('utf-8') else: value = bytes_or_str return value
46,097
def configure_ampliseq(request): """View for ampliseq.com importing stuff""" ctx = get_ctx_ampliseq(request) return render_to_response( "rundb/configure/ampliseq.html", ctx, context_instance=RequestContext(request) )
46,098
def _copy(s): """Creates a new set from another set. Args: s: A set, as returned by `sets.make()`. Returns: A new set containing the same elements as `s`. """ return struct(_values = dict(s._values))
46,099