content
stringlengths
22
815k
id
int64
0
4.91M
def threaded_main(): """ Run non-blocking task. Use daemon because we must finish writing image even after UI quits. :return: """ thread = threading.Thread(target=main, args=([sys.argv[0], '-c'],), daemon=True) thread.start()
5,355,600
def delete_user(): """ Deletes the current user's account. """ DB.session.delete(current_user) DB.session.commit() flash("Account deleted", 'success') return redirect('/login')
5,355,601
def setup_code_gen(no_of_accessories): """ Generate setup code """ try: invalid_setup_codes = ['00000000','11111111','22222222','33333333','44444444','55555555',\ '66666666','77777777','88888888','99999999','12345678','87654321'] setup_code_created = [] ...
5,355,602
def letter_difference(letter_1: str, letter_2: str) -> int: """ Return the difference in value between letter_1 and letter_2 """ assert len(letter_1) == 1 assert len(letter_2) == 1 diff = letter_to_value[letter_2] - letter_to_value[letter_1] if diff > 13: diff -= 27 return diff
5,355,603
def refresh_access_token(request): """Updates `accessToken` in request cookies (not in browser cookies) using `refreshToken`. """ try: refresh_token = request.COOKIES['refreshToken'] url = urljoin(settings.TIT_API_HOST, '/api/auth/token/refresh/') response = requests.post(url, {'refres...
5,355,604
def ngrams(string, n=3, punctuation=PUNCTUATION, **kwargs): """ Returns a list of n-grams (tuples of n successive words) from the given string. Punctuation marks are stripped from words. """ s = string s = s.replace(".", " .") s = s.replace("?", " ?") s = s.replace("!", " !") s = [w....
5,355,605
def binstringToBitList(binstring): """Converts a string of '0's and '1's to a list of 0's and 1's""" bitList = [] for bit in binstring: bitList.append(int(bit)) return bitList
5,355,606
def test_reconstructed_plane(): """ Test the reconstruction of a fitted plane from orientation of the plane expressed in spherical coordinates """ fit = random_pca() sdr = fit.strike_dip_rake() ang = fit.angular_errors() reconstructed = ReconstructedPlane(*sdr, *ang) # Test that th...
5,355,607
def file_revisions(request, repo_id): """List file revisions in file version history page. """ repo = get_repo(repo_id) if not repo: raise Http404 # perm check if check_folder_permission(request, repo_id, '/') is None: raise Http404 return render_file_revisions(request, rep...
5,355,608
def textctrl_info_t_get_tabsize(*args): """ textctrl_info_t_get_tabsize(self) -> unsigned int """ return _ida_kernwin.textctrl_info_t_get_tabsize(*args)
5,355,609
def node_is_hidden(node_name): """ Returns whether or not given node is hidden :param node_name: str :return: bool """ if python.is_string(node_name): return not maya.cmds.getAttr('{}.visibility'.format(node_name)) return not maya.cmds.getAttr('{}.visibility'.format(node.get_name(n...
5,355,610
def cargo_raze_transitive_deps(): """Loads all dependnecies from repositories required for cargo-raze""" rules_foreign_cc_dependencies() rust_repositories()
5,355,611
def generate_patch_grid_from_normalized_LAF(img: torch.Tensor, LAF: torch.Tensor, PS: int = 32) -> torch.Tensor: """Helper function for affine grid generation. Args: img: image tensor of shape :math:`(B, CH, H, W)`. LAF: laf with shape :math:`(B, N, 2, 3)`. PS: patch size to be extracte...
5,355,612
def _resolve_condition_operands( left_operand: Union[str, pipeline_channel.PipelineChannel], right_operand: Union[str, pipeline_channel.PipelineChannel], ) -> Tuple[str, str]: """Resolves values and PipelineChannels for condition operands. Args: left_operand: The left operand of a condition exp...
5,355,613
def SanityCheck(help_provider, help_name_map): """Helper for checking that a HelpProvider has minimally adequate content.""" # Sanity check the content. assert (len(help_provider.help_spec.help_name) > 1 and len(help_provider.help_spec.help_name) < MAX_HELP_NAME_LEN) for hna in help_provider.help_spec...
5,355,614
def linkQuantFilesForDabs(cfg): """ Create a per-DAB file link to the quant file. This is needed later by Data2DB. """ # link to the new quant file if cfg.configVerified is False: raise ValueError('Please run checkConfig(cfg) prior to calling linkQuantFiles') print("Linking quant files f...
5,355,615
def format_record(test_record): """Create a properly formatted Kinesis, S3, or SNS record. Supports a dictionary or string based data record. Reads in event templates from the test/integration/templates folder. Args: test_record: Test record metadata dict with the following structure: ...
5,355,616
def int_to_bitstr(int_value: int) -> str: """ A function which returns its bit representation as a string. Arguments: int_value (int) - The int value we want to get the bit representation for. Return: str - The string representation of the bits required to form the int. """ ...
5,355,617
def target_reached(effect): """target amount has been reached (100% or more)""" if not effect.instance.target: return False return effect.instance.amount_raised >= effect.instance.target
5,355,618
def resid_mask(ints, wfs_map=read_map(wfs_file), act_map=read_map(act_file), num_aps=236): """ Returns the locations of the valid actuators in the actuator array resids: Nx349 residual wavefront array (microns) ints: Nx304 intensity array (any units) N: Number of timestamps """ # Check input...
5,355,619
def session(): """Sets up a HTTP session with a retry policy.""" s = requests.Session() retries = Retry(total=5, backoff_factor=0.5) s.mount("http://", HTTPAdapter(max_retries=retries)) return s
5,355,620
def fit(df, methodtype='hc', scoretype='bic', black_list=None, white_list=None, bw_list_method='enforce', max_indegree=None, epsilon=1e-4, max_iter=1e6, verbose=3): """Structure learning fit model. Description ----------- Search strategies for structure learning The search space of DAGs is super-ex...
5,355,621
def handle_index(): """ Kezeli az index oldalat, elokesziti es visszakulti a html-t a kliensnek. :return: """ return render_template("index.html")
5,355,622
def save_pkl(obj, file_name): """Save an object to the given file name as pickle.""" with open(file_name, "wb") as f: pickle.dump(obj, f)
5,355,623
def get_polynomial_coefficients(degree=5): """ Return a list with coefficient names, [1 x y x^2 xy y^2 x^3 ...] """ names = ["1"] for exp in range(1, degree + 1): # 0, ..., degree for x_exp in range(exp, -1, -1): y_exp = exp - x_exp if x_exp == 0: ...
5,355,624
def cluster_stats(all_cluster_labels, draw = False): """ In this function, we want to derive the mean and variance of cluster as the number of cluster differs :param all_cluster_labels: :return: """ cluster_count = np.zeros(max(all_cluster_labels) + 1) dictionary = dict() dictionary['si...
5,355,625
def _get_configured_credentials() -> Dict[str, bytes]: """ Get the encryupted credentials stored in disk """ path = get_credentials_path() credentials: Dict[str, bytes] with open(path, "rb") as file_handle: credentials = pickle.load(file_handle) if len(credentials) == 0: ...
5,355,626
def open(request: HttpRequest, *args, **kwargs) -> HttpResponse: """ Create a temporary project from a single source. This view allows for all users, including anonymous users, to create a temporary project which they can later save as a permanent project if they wish. It aims to be a quick way to ...
5,355,627
def __Logout(si): """ Disconnect (logout) service instance @param si: Service instance (returned from Connect) """ try: if si: content = si.RetrieveContent() content.sessionManager.Logout() except Exception as e: pass
5,355,628
def kabsch_rotate(P, Q): """ Rotate matrix P unto matrix Q using Kabsch algorithm """ U = kabsch(P, Q) # Rotate P P = np.dot(P, U) return P
5,355,629
def matrix( odoo=ODOO_VERSIONS, pg=PG_VERSIONS, odoo_skip=frozenset(), pg_skip=frozenset() ): """All possible combinations. We compute the variable matrix here instead of in ``.travis.yml`` because this generates faster builds, given the scripts found in ``hooks`` directory are already multi-versio...
5,355,630
def iterate_pagerank(corpus, damping_factor): """ Return PageRank values for each page by iteratively updating PageRank values until convergence. Return a dictionary where keys are page names, and values are their estimated PageRank value (a value between 0 and 1). All PageRank values should su...
5,355,631
def user_enabled(inst, opt): """ Check whether the option is enabled. :param inst: instance from content object init :param url: Option to be checked :return: True if enabled, False if disabled or non present """ return opt in inst.settings and inst.settings[opt]
5,355,632
async def get_buttons_data(client: Client, message: Message): """ Get callback_data and urls of all the inline buttons of the message you replied to. """ reply_message = message.reply_to_message if reply_message and reply_message.reply_markup: if reply_message.reply_markup.inline_keyboard: ...
5,355,633
def send_notification(*, subsystem, recipients, subject, body_html, body_text): """Method to send a notification. A plugin may use only part of the information, but all fields are required. Args: subsystem (`str`): Name of the subsystem originating the notification recipients (`list` of :obj:`N...
5,355,634
def convert_img_k_to_jy(imagename, outfile): """ Calculated from flux density / brightness temp conversion page: https://science.nrao.edu/facilities/vla/proposing/TBconv NOTE the implicit conversion at the top for (beam/omega) into [ster] Image must have units: restfreq -> Hz bmaj...
5,355,635
def update_document( *, db_session: Session = Depends(get_db), document_id: PrimaryKey, document_in: DocumentUpdate ): """Update a document.""" document = get(db_session=db_session, document_id=document_id) if not document: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, ...
5,355,636
def from_jabsorb(request, seems_raw=False): """ Transforms a jabsorb request into a more Python data model (converts maps and lists) :param request: Data coming from Jabsorb :param seems_raw: Set it to True if the given data seems to already have been parsed (no Java class hin...
5,355,637
def write_board_to_svg_file(board, file_name, hex_edge=50, hex_offset=0, board_padding=None, pointy_top=True, trim_board=True, style=None): """ Writes given board to a svg file of given name. :param board: 2 dimensional list of fields, each represented as a number :param fil...
5,355,638
def ensure_conf(app): """ Ensure for the given app the the redbeat_conf attribute is set to an instance of the RedBeatConfig class. """ name = 'redbeat_conf' app = app_or_default(app) try: config = getattr(app, name) except AttributeError: config = RedBeatConfig(app) ...
5,355,639
def check_if_process_present(string_to_find): """Checks if process runs on machine Parameters: string_to_find (string): process we want to find Returns: found (bool): True if found process running """ output = check_output(["ps", "-ax"], universal_newlines=True) if string_to_find in ...
5,355,640
def test_boussole_compile_auto(tests_settings, temp_builds_dir, manifest_name): """ Testing everything: * Sass helpers correctly generate CSS; * Manifest is correctly serialized to expected datas; * Builded CSS is the same than stored one in data fixtures; """ manifest_css = manifest_name +...
5,355,641
def consulta_dicionario(nivel): """ Entrada: Parâmetro do nível selecionado (fácil, médio, difícil) Tarefa: Determinar qual dicionário a ser consultado Saída: Parâmetros do dicionário (texto, lacunas, gabarito) """ nivel_dicionario = nivel if nivel_dicionario == 'facil': texto = dici...
5,355,642
def stats_check( main_table: Table, compare_table: Table, checks: List[OutlierCheck] = [], max_rows_returned: int = 100, ): """ :param main_table: main table :type main_table: table object :param compare_table: table to be compared :type compare_table: table object :param checks:...
5,355,643
async def get_collectible_name(collectible_id: int, db: AsyncSession = Depends(get_db_session)): """Gets the collectible name""" result = await destiny_items.get_collectible(db=db, collectible_id=collectible_id) return NameModel(name=result.name) if result else NameModel(name=None)
5,355,644
def test_pyflann_searches(): """ """ try: num_neighbors = 3 pts = testdata_points(nPts=5743, nDims=2) qpts = testdata_points(nPts=7, nDims=2) import vtool_ibeis as vt # sample a radius radius = vt.L2(pts[0:1], qpts[0:1])[0] * 2 + 1 flann = FLANN_CLS()...
5,355,645
def prime_factors(n): """ Return a list of prime factors of n :param n: int :return: list """ # check if 2 is the largest prime all_factors = set() t = n while t % 2 == 0: t /= 2 all_factors.add(2) # check the divisors greater than 2 d = 3 while d < n ** ...
5,355,646
def calculate_central_age(Ns, Ni, zeta, seZeta, rhod, Nd, sigma=0.15): """Function to calculate central age.""" Ns = np.array(Ns) Ni = np.array(Ni) # We just replace 0 counts with a low value, the age will be rounded to # 2 decimals. That should take care of the zero count issue. Ns = np.wher...
5,355,647
def _get_cross_reference_token(auth_cookie: str) -> str: """Gets a new cross reference token affiliated with the Roblox auth cookie. :param auth_cookie: Your Roblox authentication cookie. :return: A fresh cross reference token. """ session: requests.Session = _get_session(auth_cookie) response...
5,355,648
def erase_not_displayed(client): """Erase all non-displayed models from memory. Args: client (obj): creopyson Client. Returns: None """ return client._creoson_post("file", "erase_not_displayed")
5,355,649
def reset_position_for_friends_image_details_from_voter(voter, twitter_profile_image_url_https, facebook_profile_image_url_https): """ Reset all position image urls in PositionForFriends from we vote image details :param voter: :param twitter_profi...
5,355,650
def get_analysis(panda_data): """ Get Analysis of CSV Data :param panda_data: Panda dataframes :return: panda data frames """ # Create Object for Analysis0 sentiment_object = SentimentConfig.sentiment_object ner_object = SentimentConfig.ner_object # Get list of sentences list =...
5,355,651
def create_coordinate_string_dict(): """31パターンのヒモ。""" w = 120 h = 120 return { 47: (0, 0), 57: (1*-w, 0), 58: (2*-w, 0), 16: (4*-w, 0), 35: (5*-w, 0), 36: (6*-w, 0), 38: (0, 1*-h), 13: (1*-w, 1*-h), 14: (2*-w, 1*-h), 15: (3*...
5,355,652
def election_flink_cluster(cluster_group=None): """ 根据 cluster_group 的取值,选择单个选举或全部选举 当优先级为-1时表示该集群被加入黑名单,不参与选举。选举结果也不更新黑名单的集群 只有手动将集群的优先级从-1更改为0时,集群方可再次参与选举 debug集群不注册到资源系统 @param cluster_group: @return: """ cluster_label = "standard" result_list = get_flink_session_std_cluster(r...
5,355,653
def all_but_ast(check): """Only passes AST to check.""" def _check_wrapper(contents, ast, **kwargs): """Wrap check and passes the AST to it.""" del contents del kwargs return check(ast) return _check_wrapper
5,355,654
def get_history_items(): """ Get all history item """ return [ readline.get_history_item(i) for i in xrange(1, readline.get_current_history_length() + 1) ]
5,355,655
def generate_nucmer_commands( filenames: List[Path], outdir: Path = Path("."), nucmer_exe: Path = pyani_config.NUCMER_DEFAULT, filter_exe: Path = pyani_config.FILTER_DEFAULT, maxmatch: bool = False, ) -> Tuple[List, List]: """Return list of NUCmer command-lines for ANIm. :param filenames: ...
5,355,656
def normalize(*args): """Scale a sequence of occurrences into probabilities that sum up to 1.""" total = sum(args) return [arg / total for arg in args]
5,355,657
def get_CZI_zstack(filename,frame,channel,filepath=None,img_info=None): """ Obtains a single z-stack from a 3D imaging time-series for a specified time and channel. Parameters ---------- filename : str Name of the file from which to retrieve the z-stack. frame : int ...
5,355,658
def test_game(): """ Run through a few games and make sure there's no exceptions. """ for i in range(10): for n in range(2, 5): g = Game(n) while not g.winner(): g.act(random.choice(g.options()))
5,355,659
def _make_request( resource: str, from_currency_code: str, to_currency_code: str, timestamp: int, access_token: str, exchange_code: str, num_records: int, api_version: str ) -> requests.Response: """ API documentation for cryptocompare can be f...
5,355,660
def dependencies_order_of_build(target_contract, dependencies_map): """ Return an ordered list of contracts that is sufficient to sucessfully deploys the target contract. Note: This function assumes that the `dependencies_map` is an acyclic graph. """ if len(dependencies_map) == 0: ...
5,355,661
def projective_error_function(params, args): """ :param params: :param args: :return: """ # fx fy cx cy k0 k1 project_params = params[0:5] f, cx, cy, k0, k1 = project_params K = eye(3, 3) K[0,0] = f K[1,1] = f K[0, 2] = k0 K[1, 2] = k1 ...
5,355,662
def _transform_masks(y, transform, data_format=None, **kwargs): """Based on the transform key, apply a transform function to the masks. Refer to :mod:`deepcell.utils.transform_utils` for more information about available transforms. Caution for unknown transform keys. Args: y (numpy.array): Lab...
5,355,663
def root_dir(): """ Returns root director for this project """ return os.path.dirname(os.path.realpath(__file__ + '/..'))
5,355,664
def query_subgraph(seeds, genes_top, output_path): # pylint: disable=too-many-locals """ This function queries the data, writes the resulting subgraph and returns a dictionary containing the number of nodes and edges. seeds: list genes_top: dict whose keys are genes and values are their ranks "...
5,355,665
def get_cur_version(): """ Get current apk version string """ pkg_name = cur_activity.getPackageName() return str( cur_activity.getPackageManager().getPackageInfo( pkg_name, 0).versionName)
5,355,666
def get_item(TableName=None, Key=None, AttributesToGet=None, ConsistentRead=None, ReturnConsumedCapacity=None, ProjectionExpression=None, ExpressionAttributeNames=None): """ The GetItem operation returns a set of attributes for the item with the given primary key. If there is no matching item, GetItem does not ...
5,355,667
def main(arguments=None): """Parse args and run """ parser = parse_arguments() args = parser.parse_args(arguments) smif.cli.log.setup_logging(args.verbose) def exception_handler(exception_type, exception, traceback, debug_hook=sys.excepthook): if args.verbose: debug_hook(exc...
5,355,668
def checkpointload(checkpointfile): """Loads an hyperoptimizer checkpoint from file Returns a list of tuples (params, loss) referring to previous hyperoptimization trials """ try: with open(checkpointfile, "rb") as f: return pkl.load(f) except (FileNotFoundError, EOFError): ...
5,355,669
def encrypt_password(password, key): """ Encrypts the password using the given key. Args: password (str): password to be encrypted key (str): key to be used to encrypt the password """ from time import time from array import array import hmac import base64 h_hash =...
5,355,670
def prepare_test_data(datapath): """ Wrapper function to load the test dataset """ print("Loading and encoding the test dataset") depth_test = np.array(pd.read_csv(os.path.join(datapath,'test_depth.txt'),sep="\t", header = None)) depth_test = depth_test.reshape(depth_test.shape[0],depth_test.shape[1], ...
5,355,671
def get_case_color_marker(case): """Get color and marker based on case.""" black_o = ("#000000", "o") teal_D = ("#469990", "D") orange_s = ("#de9f16", "s") purple_v = ("#802f99", "v") bs = case["batch_size"] sub = case["subsampling"] mc = case["mc_samples"] if sub is None and mc =...
5,355,672
def clean_integer_score(x): """Converts x from potentially a float or string into a clean integer, and replace NA and NP values with one string character""" try: x = str(int(float(x))) except Exception as exc: if isinstance(x, basestring): pass else: raise ...
5,355,673
def do_stuff2(): """This is not right.""" (first, second) = 1, 2, 3 return first + second
5,355,674
def rule_block_distributor(rule_param, src_cortical_area, dst_cortical_area, src_neuron_id, z_offset): """ This rule helps to take a set of unique inputs from one cortical area and develop synaptic projections that can lead to a comprehensive set of unique connections that covers all the combinations of the...
5,355,675
def get_extra(item_container): """ liefert die erste passende image_url """ if item_container.item.extra != '': return get_extra_data(item_container) item_container = item_container.get_parent() while item_container.item.app.name == 'dmsEduFolder': if item_container.item.extra != '': return get_ex...
5,355,676
def abort_if_requests_doesnt_exists(id): """Checks if given id exists in the database""" if not Requests.get_one_by_field('id', value=id): api.abort(404, "Request with id {} doesn't exist or your provided an id that does not belong to you".format(id))
5,355,677
def pt_accuracy(output, target, topk=(1,)): """Compute the accuracy over the k top predictions for the specified values of k.""" with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.e...
5,355,678
def compute_phasing_counts(variant_to_read_names_dict): """ Parameters ---------- variants_to_read_names : dict Dictionary mapping varcode.Variant to set of read names Returns ------- Dictionary from variant to Counter(Variant) """ read_names_to_variants = defaultdict(set) ...
5,355,679
def run_bar( bar, sort_by=["sample_num"], dryrun=0, rev=[False], delete_as_complete=True, retract_when_done=False, save_as_complete="", ): """ run all sample dictionaries stored in the list bar @param bar: a list of sample dictionaries @param sort_by: list of strings determin...
5,355,680
def test_domain_command_failure(client, mocker): """ When there is a invalid response then ValueError should be raised with valid message """ from GoogleChronicleBackstory import domain_command dummy_response = "{ \"error\": { \"code\": 400, \"message\": \"Invalid JSON payload received. Unknown nam...
5,355,681
def _inputs_and_vae(hparams): """Constructs a VAE.""" obs_encoder = codec.MLPObsEncoder(hparams) obs_decoder = codec.MLPObsDecoder( hparams, codec.BernoulliDecoder(squeeze_input=True), param_size=1) inputs = context_mod.EncodeObserved(obs_encoder) vae = vae_mod.make(hparams, ...
5,355,682
def main(): """Starts the bot.""" # TODO: Handle network errors, see: # https://github.com/python-telegram-bot/python-telegram-bot/wiki/Handling-network-errors # TODO: Multithreading can be implemented for performance. See: # https://github.com/python-telegram-bot/python-telegram-bot/wiki/Pe...
5,355,683
def read_grid_hdf5(filepath, name): """Read a grid from HDF5 file. Parameters ---------- filepath : string or pathlib.Path object Path of the HDF5 file. name : string Name of the grid. Returns ------- x : numpy.ndarray The x-coordinates along a gridline in the x...
5,355,684
def string_to_version(verstring): """ Return a tuple of (epoch, version, release) from a version string This function replaces rpmUtils.miscutils.stringToVersion, see https://bugzilla.redhat.com/1364504 """ # is there an epoch? components = verstring.split(':') if len(components) > 1: ...
5,355,685
def cff2provn(filename): """Parse cml xml file and return a prov bundle object""" #filename = "/Users/fariba/Desktop/UCI/freesurfer/scripts/meta-MC-SCA-023_tp1.cml" tree = xml.dom.minidom.parse(filename) collections = tree.documentElement g = prov.ProvBundle() g.add_namespace(xsd) g.add_nam...
5,355,686
def optional(idx, *args): """A converter for functions having optional arguments. The index to the last non-optional parameter is specified and a list of types for optional arguments follows. """ return lambda ctx, typespecs: _optional_imp(ctx, typespecs[idx], args)
5,355,687
def analysis(): """Work out numbers of patients done this year and whether on target""" def report_number_this_week(): try: with open('d:\\JOHN TILLET\\episode_data\\' 'jtdata\\weekly_data.py', 'rb') as pf: weekly = pickle.load(pf) ...
5,355,688
def calc_plot_ROC(y1, y2): """ Take two distributions and plot the ROC curve if you used the difference in those distributions as a binary classifier. :param y1: :param y2: :return: """ y_score = np.concatenate([y1, y2]) y_true = np.concatenate([np.zeros(len(y1)), np.ones(len(y2))])...
5,355,689
def custom_leastsq(obj_fn, jac_fn, x0, f_norm2_tol=1e-6, jac_norm_tol=1e-6, rel_ftol=1e-6, rel_xtol=1e-6, max_iter=100, num_fd_iters=0, max_dx_scale=1.0, damping_mode="identity", damping_basis="diagonal_values", damping_clip=None, use_acceleration=False, uphill_s...
5,355,690
def degrees(x): """Converts angle x from radians to degrees. :type x: numbers.Real :rtype: float """ return 0.0
5,355,691
def account_credit(account=None, asset=None, date=None, tp=None, order_by=['tp', 'account', 'asset'], hide_empty=False): """ Get credit operations for the account Args: account: filter by account code ...
5,355,692
def get_logger(log_file=None): """ Initialize logger configuration. Returns: logger. """ formatter = logging.Formatter( '%(asctime)s %(name)s.%(funcName)s +%(lineno)s: ' '%(levelname)-8s [%(process)d] %(message)s' ) logger = logging.getLogger(__name__) logger.set...
5,355,693
def verify(model): """ 测试数据模型检验 :param model: 网络模型以及其参数 :return res: 返回对应的列表 """ device = 'cuda' if torch.cuda.is_available() else 'cpu' model = model.to(device) if device == 'cuda': model = torch.nn.DataParallel(model) cudnn.benchmark = True res = [] for idx, da...
5,355,694
def parse_solution_file(solution_file): """Parse a solution file.""" ids = [] classes = [] with open(solution_file) as file_handle: solution_reader = csv.reader(file_handle) header = next(solution_reader, None) if header != HEADER: raise ValueError( 'I...
5,355,695
def fibonacci_modulo(number, modulo): """ Calculating (n-th Fibonacci number) mod m Args: number: fibonacci number modulo: modulo Returns: (n-th Fibonacci number) mod m Examples: >>> fibonacci_modulo(11527523930876953, 26673) 10552 """ period = _pi...
5,355,696
def _str_unusual_grades(df: pd.DataFrame) -> Union[str, None]: """Print the number of unusual grades.""" grades = np.arange(0, 10.5, 0.5).astype(float) catch_grades = [] for item in df["grade"]: try: if float(item) not in grades: catch_grades.append(item) exce...
5,355,697
def _adjust_estimator_options(estimator: Any, est_options: Dict[str, Any], **kwargs) -> Dict[str, Any]: """ Adds specific required classifier options to the `clf_options` dictionary. Parameters ---------- classifier : Any The classifier object for which the options have to be added clf_...
5,355,698
def run(args): """ Create all registered downloads (locally). """ if args.domain: args.env['request'].environ['HTTP_HOST'] = args.domain for name, download in args.env['registry'].getUtilitiesFor(IDownload): args.log.info('creating download %s' % name) if not args.list: ...
5,355,699