content
stringlengths
22
815k
id
int64
0
4.91M
def accuracy(output, target): """Computes the precision@k for the specified values of k""" topk = (1,4) maxk = max(topk) batch_size = target.size(0) # 上位何件のデータを参照するかターゲットデータのラベル数を参照 label_count = np.count_nonzero(target == 1, axis = 1) # one-hot配列からクラス番号を取得 class_index_array, class_num...
78,600
def unsubscribe_from_basket_action(newsletter): """Unsubscribe from Basket action.""" def unsubscribe_from_basket(modeladmin, request, queryset): """Unsubscribe from Basket.""" ts = [(mozillians.users.tasks.unsubscribe_from_basket_task .subtask(args=[userprofile.user.email, userp...
78,601
def pgi_params() -> Tuple[Dict[str, str], List[str]]: """ Nvidia PGI compilers pgc++ is not available on Windows at this time """ compilers = {'FC': 'pgfortran', 'CC': 'pgcc'} if os.name == 'nt': cspec = config.get_compiler_spec() if cspec.get('CXX'): ...
78,602
def find_possible_pt2262_device(device_id): """Look for the device which id matches the given device_id parameter.""" for dev_id, device in RFX_DEVICES.items(): if hasattr(device, 'is_lighting4') and len(dev_id) == len(device_id): size = None for i, (char1, char2) in enumerate(zi...
78,603
def gcd(*nums): """ Find the greatest common divisor (GCD) of a list of numbers. Args: *nums (tuple[int]): The input numbers. Returns: gcd_val (int): The value of the greatest common divisor (GCD). Examples: >>> gcd(12, 24, 18) 6 >>> gcd(12, 24, 18, 42, 600...
78,604
def create_app(debug=True, base_url="/api/v1/data"): """Create main Flask app if this module is the entrypoint, e.g. python3 -m data.api""" app = Flask(__name__) app.debug = debug configure_app(app, base_url=base_url) return app
78,605
def exposure_compensation(img, illuminant_lux, # ambient illumination strength in lux luminance_target=300, # will compensate for this luminance, in cd/m2 luminance_display=300, # the luminance of the display cd/m2 ...
78,606
def get_generate_dicom_seg_cmd( resampled_aseg: Union[str, bytes, os.PathLike], aseg_dicom_seg_metadata: Union[str, bytes, os.PathLike], t1_dicom_file: Union[str, bytes, os.PathLike], aseg_dicom_seg_output: Union[str, bytes, os.PathLike], ) -> str: """Generate the command to create a DICOM SEG image...
78,607
def template_and_parser( template_file: Callable[[str, str], Path] ) -> Callable[[str, str], Tuple[Path, Type[AbstractParser]]]: """ Retrieve the parser and test template for a particular supported file type. Args: file_type: The parser type to retrieve i.e. "ini" -> IniParser templ...
78,608
def main(): """ Main function to tune the variable Args: NA Returns: NA """ study = optuna.create_study() study.optimize(objective, n_trials=100) # best param after 10 trainings # auc = 0.6541279233586925 param = { "linear_fit_intercept": True, "line...
78,609
def sum_2(strg): """Sums last 3 digits""" sum = 0 for i in strg[3:]: sum += int(i) if sum == 0: sum = 1 return sum
78,610
def URLs(integration: bool): """ summary: return URLs dict (funName:url) arguments: (integration: bool [test type]) """ URLs = { "get_access_token": "/token", "GetMe": "/users/me/", "ListUsers": "/users", "GetAdmins": "/users/admins", "CreateUser": "/user", ...
78,611
def preprocess_cv(vec_idx_patient, cfg): """ Cross validation mode of the preprocessing function :param vec_idx_patient: list containing start and end indices of the patients :param cfg: object holding all the training parameters :return: """ # Exception detection if not cfg.binary_cla...
78,612
def is_happy(n: int) -> bool: """ is_happy :param n: :return: """ global happy_flag happy_flag = False total, counter = n, 0 while True: num_list, total= list(str(total)), 0 for i in num_list: total += pow(int(i), 2) counter += 1 if total...
78,613
def deploy_fluentd(client, app_name, es_url): """ Logic must handle 3 deployment cases when FLUENTD_DOCKER_IMAGE is unset: localhost:5000/geoint/scale:5.9.2 localhost:5000/geoint/scale geoint/scale:5.9.2 The most problematic is the 2nd case as we previously were improperly identifying the ...
78,614
def rotate_points(points, phase_shift): """ Rotate a point about the origin. Arguments: points: iterable(complex) Points to rotate in the complex plane. phase_shift: Magnitude of rotation in radians. Returns: rotated_points: list(complex) Poi...
78,615
def add_choice(path, choices, default=None, *, var=None, **kwargs): """Add an action for choosing one from a list of choices. :source:`The menubar plugin <porcupine/plugins/menubar.py>` displays these actions as submenus that contain radio button items. If given, *default* should be an element of *cho...
78,616
def get_bprop_max_pool_grad_grad(self): """Grad definition for `MaxPoolGrad` operation.""" maxpool_grad_grad = G.MaxPoolGradGrad( kernel_size=self.kernel_size, strides=self.strides, pad_mode=self.pad_mode) def bprop(x1, x2, grad, out, dout): dx1 = zeros_like(x1) dx2 ...
78,617
def line_style( type=None, line_width=1, line_opacity=1, line_curve=0, line_type="solid", line_color=None, **kwargs ): """ 带线图形的线的风格选项 :param type: 图形类型 :param line_width: 线的宽度,默认为 1 :param line_opacity: 线的透明度,0 为完全透明,1 为完全不透明。默认为 1 :param lin...
78,618
def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" clear() print('Calculating the total and average Trip Duration...') start_time = time.time() # Calc the total and average trip duration total_trip_duration = df['Trip Duration'].sum() mean_trip_d...
78,619
def print_death_age(people_dict): """For each person in the people dictionary, print the person's name and age at death. Parameter people_dict: a dictionary that contains data about people Each item in the dictionary is in this format: person_key: [name, gender, birth_year, ...
78,620
def generate_scale(scale, note, mode=1, r_type="list", octaves=True): # scale, start, type """ Generate a scale scale (string): major, melodic_minor, harmonic_minor, chromatic, major_pentatonic note: start note """ if scale in SCALE_STEPS: steps = _get_mode(SCALE_STEPS[scale], mode) ...
78,621
def _serialize_slot_variables(checkpointable_objects, path_to_root, non_slot_variables, object_graph_proto): """Name slot variables and add them to `object_graph_proto`.""" named_slot_variables = {} for optimizer_checkpoint_id, checkpointable_ref in enumerate( checkpointable_ob...
78,622
def plot_all_attack(model, attack_images_li, attack_success_li, algo_names, x_test, y_test, class_names, save_dir, topk=10): """ 可视化所有对抗算法共同对抗成功的图片 Args: model ([type]): [description] attack_images_li ([type]): [description] attack_success_li ([type]): [description] algo_nam...
78,623
def tupleize(func): """A decorator that tuple-ize the result of a function. This is useful when the evaluation function returns a single value. """ def wrapper(*args, **kargs): return func(*args, **kargs), return wrapper
78,624
def clean_outfile(outfilename, linekey): """Clean an outfile to include only lines containing a string in `linekey`, which should be a list of strings to keep""" with open(outfilename,'r') as f: filedata = f.readlines() newdata = [line for line in filedata if any(k in line for k in linekey)] ...
78,625
def regress_level_on_first_known(y:Y_TYPE, s:dict, k, a:A_TYPE=None, t:T_TYPE =None, e:E_TYPE =None)->([float] , Any , Any): """ Very basic online regression skater, mostly for offlinetesting - Only one known in advance variable is utilized - Last value is ignored, unless a is None in which ca...
78,626
def _gen_capture_chain_fo(nt_names, fname=None): """ Given a list of NT names, generate a function object (function_object_t) that calls corresponding xed3 NT capturing functions. Each such function captures everything that xed2 decode graph would capture for a given pattern with NTs (nt_names) in i...
78,627
def clean_cmd(args): """Command to clean cruft from current directory.""" scriptorium.clean(args.paper)
78,628
def weight2fun(grid_rowcol): """Make a function from a SICD data structure description of a complex image weighting Input: grid_rowcol Either the Grid.Row or Grid.Col SICD field depending on which direction is being processed. Should have either ...
78,629
def public_point(private_key, curve='secp256k1'): """Retrieve the public key as a point object""" try: curve_obj = KNOWN_CURVES[curve.lower()][0] except KeyError: raise ValueError("Unknown curve name {}".format(repr(curve))) return curve_obj.public_point(key)
78,630
def get_five_landmarks_from_net(landmarks): """ Return 5 landmarks needed in face alignment """ num_lmks = landmarks.shape[0] if num_lmks == 5: left_eye = landmarks[0] right_eye = landmarks[1] nose = landmarks[2] mouse_left = landmarks[3] mouse_right = landma...
78,631
def test_RunLogAnalyser_best_epoch_num( populated_log_db: DatabaseAndRunIds, metric: str ): """Black-box test that run log properties work.""" for run_id in populated_log_db.run_ids: run = log_analysis.RunLogAnalyzer(populated_log_db.db, run_id) try: assert run.GetBestEpochNum(metric=metric) exc...
78,632
def det_vectors(h=1.0,v=1.0,nu=0.0,delta=0.0): """ Compute detector apperature vectors in lab frame Parameters: ----------- * h = detector horz width (total slit width in lab-z, or the horizontal scattering plane) * v = detector vert hieght (total slit width in lab-x, or th...
78,633
def TopOpeBRepBuild_Tools_FindStateThroughVertex(*args): """ :param aShape: :type aShape: TopoDS_Shape & :param aShapeClassifier: :type aShapeClassifier: TopOpeBRepTool_ShapeClassifier & :param aMapOfShapeWithState: :type aMapOfShapeWithState: TopOpeBRepDS_IndexedDataMapOfShapeWithState & ...
78,634
def init_test_db(): """ Initiates the db and adds a a car to the database. Tears down the db afterwards. This is run once per module. This means `api` tests has one database, and `models` database has one database. """ downgrade_base() # in case the last test session didn't exit properly u...
78,635
def remove_registered_at(input_list: List[dict]) -> List[dict]: """ Removes the field 'registered_at' frm a list of connection results, for comparing two results without considering the time. """ node_to_remove = 'registered_at' output_list = deepcopy(input_list) for item in output_list: ...
78,636
def extract_melodies(sequence, steps_per_beat=4, min_bars=7, min_unique_pitches=5): """Extracts a list of melodies from the given NoteSequence proto. A time signature of BEATS_PER_BAR is assumed for each sequence. If the sequence has an incompatable time signature, like 3/4, 5/4, etc, then ...
78,637
def vocabulary(word_counts): """ :param word_counts: dictionary of each word count :return: list of vocabulary """ vocabulary = list(map(lambda x: x[0], sorted(word_counts.items(), key=lambda x: -x[1]))) return vocabulary
78,638
def partial_deriv_plot(of, wrt, check_partials_data, title=None, jac_method='J_fwd', tol=1e-10, binary=True): """ Visually examine the computed and finite differenced Jacobians. Parameters ---------- of : string Variable whose derivatives will be computed. wrt : s...
78,639
def new_scaled_crossentropy(index=2, scaling=1.0): """ Returns masked crossentropy with extra scaling: Scales the loss for given stop_index by stop_scaling """ def masked_crossentropy(targets: tf.Tensor, logits: tf.Tensor) -> tf.Tensor: crossentropy = tf.keras.losses.SparseCategoricalCr...
78,640
def version(): """ Report the version of this module """ return __version__
78,641
def rejoin(chunked, initial_shape): """ Rejoins chunked tensor, removing the padding as necessary >>> eq = lambda a, b: torch.all(torch.lt(torch.abs(torch.add(a, -b)), 1e-12)) >>> x = torch.arange(end=4) + 3 >>> y = torch.arange(end=15) + 2 >>> mesh = x.view(-1, 1) @ y.view(1, -1) >>> mesh ...
78,642
def clean(dataframe, column_name, lowercase = True, punctuation = True, special_char = True, stopwords = False, cotum_stopwords = False, stemming = False, lemmatizing = False, tokenizing = False): """ Allows to input both pre-set english stopwords and costum stopword_list Probably ...
78,643
def callback_focus(x): """ Trackbar callback - setting new focus value """ print(f"new focus={x}") vc.set(cv.CAP_PROP_FOCUS, x)
78,644
def single() -> dict: """ 1x1 block """ temp = { 0 : { 0 : Conway(Position(0,0),True) } } return temp
78,645
def h4(content, accesskey:str ="", class_: str ="", contenteditable: str ="", data_key: str="", data_value: str="", dir_: str="", draggable: str="", hidden: str="", id_: str="", lang: str="", spellcheck: str="", style: str="", tabindex: str="", title: str="", translate...
78,646
def svn_wc_delete2(*args): """ svn_wc_delete2(char path, svn_wc_adm_access_t adm_access, svn_cancel_func_t cancel_func, svn_wc_notify_func2_t notify_func, apr_pool_t pool) -> svn_error_t """ return _wc.svn_wc_delete2(*args)
78,647
def tile(address, tile_x, tile_y, tile_z, tilesize=256, **kwargs): """ Create mercator tile from any images. Attributes ---------- address : str file url. tile_x : int Mercator tile X index. tile_y : int Mercator tile Y index. tile_z : int Mercator tile Z...
78,648
def JsonError(error_text): """Constructs a JSON response from an error.""" response = make_response(json.dumps({'error': error_text}, indent=4)) response.headers['Content-Type'] = 'application/json' return response
78,649
def calc_b_stress_xx( x, y = 0, z = 1, Fv = 1, mu = 1, lamb = 1 ): """ Boussonesq solution for stresses acting on x in the x direction, from Liu and Zoback 1992 JGR (equation 68) """ r = get_r( x, y, z) term1 = Fv / (2 * np.pi) term2 = 3 * x **2 * z / r **5 term3 = mu * ( y **2 + z *...
78,650
def update_config_pwd(msg, cfg): """ Updates the profile's auth entry with values set by the user. This will overwrite existing values. Args: :msg: (Message class) an instance of a message class. :cfg: (jsonconfig.Config) config instance. """ msg_type = msg.__class__.__name__.lo...
78,651
def export_coe_TI(f): """ Save FIR filter coefficients in TI coefficient format Coefficient have to be specified by an identifier 'b0 ... b191' followed by the coefficient in normalized fractional format, e.g. b0 .053647 b1 -.27485 b2 .16497 ... """ pass
78,652
def stress_from_momentum_budget(H, dhdx, dSxxdx, dpdx, taub, rhow): """Returns the stress estimate from momentum budget components.""" return rhow * GRAV * H * dhdx + H * dpdx + dSxxdx - taub
78,653
def generate_silence_data( num_known_samples_per_split, splits, data_folder, percentage_silence=26 ): """Generates silence samples. Arguments --------- num_known_samples_per_split: int Total number of samples of known words for each split (i.e. set). splits: str Training, valida...
78,654
def transient_provider(func): """ Decorator to mark a provider as transient """ func.transient = True return func
78,655
def getObsPETs(mat, binSize=5000): """ Get the number of PETs in bins. @param mat: [[x,y]] @param binSize:int, contact matrix bin size """ minC = np.min(mat) a = (mat[:, 0] - minC) / binSize b = (mat[:, 1] - minC) / binSize a = a.astype(int) b = b.astype(int) ss = {} for ...
78,656
def delete_api_key(auth_header: Optional[models.AuthHeader] = None): """Delete a user's API key.""" Users.delete('apikey', auth=auth_header)
78,657
def register_connection(alias, name, host=None, port=None, is_slave=False, read_preference=False, slaves=None, username=None, password=None, **kwargs): """Add a connection. :param alias: the name that will be used to refer to this connection throughout Mo...
78,658
def query(query_list, feature_list, out_dir, top=200, pca_thresh=0.9, out_dim=None, pca_file='-1', qe_fn=None, mask_pred=False, euclidean_dist=False, rmac=False, mac=False, aml=False): """Query by list.""" print(Notify.INFO, 'Read feature', Notify.ENDC) print(Notify.INFO, 'Use R-MAC: '...
78,659
def crf1d(cost, xs, ys, reduce='mean'): """Calculates negative log-likelihood of linear-chain CRF. It takes a transition cost matrix, a sequence of costs, and a sequence of labels. Let :math:`c_{st}` be a transition cost from a label :math:`s` to a label :math:`t`, :math:`x_{it}` be a cost of a label :...
78,660
def abs_date_from_phrase(text): """ Identify the first absolute date in text Returns ((month, day), start, end) or None Doesn't currently support British dates (e.g. '28 February') """ dates = set() months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'septembe...
78,661
def load_fonts(path: Text = None): """Discover all files in the directory given by `path` and load them as fonts. font filename format: [font name]_[char width]x[line height].[image extension] """ # if no path is supplied the fonts are loaded into the module # from the resources package...
78,662
def _read_CD_Chirascan( infile, outfile=None ): """CD read method for the Chirascan output format. .. seealso:: :func:`.read_CD` """ def reshape(row): df = ru.add_column(pd.DataFrame(row.iloc[1:]).reset_index(), 'w', row.iloc[0]) df = df.assign(bin=range(1, df.shape[0] + 1)) ...
78,663
def new(key, *args, **kwargs): """Create a new XOR cipher :Parameters: key : byte string The secret key to use in the symmetric cipher. Its length may vary from 1 to 32 bytes. :Return: an `XORCipher` object """ return XORCipher(key, *args, **kwargs)
78,664
def _quadsum1(x0, a, n, ind): """ sum_i (yi-x0)^2/(ai*ai) = 1 with i in ind Args: x0(array): a(array): n(int): number of dimensions ind(list(int)): number of dimensions involved Returns: array: n+1 x n+1 """ x0 = np.asarray(x0) a = np.asarray(a) ...
78,665
def log(message, project_code="MAIN", message_type="Notice"): """Logs custom messages to a separate CrashTrakr_log.txt file. Args: message: The message we wish to log project_code: The internal code to the project we wish to save data for. MAIN default if the log is not related to ...
78,666
def remove_indicator(request, _id): """ Remove an Indicator from CRITs. :param request: Django request object (Required) :type request: :class:`django.http.HttpRequest` :param _id: The ObjectId of the indicator to remove. :type _id: str :returns: :class:`django.http.HttpResponse`, ...
78,667
def zharkov_panh(v, temp, v0, a0, m, n, z, t_ref=300., three_r=3. * constants.R): """ calculate pressure from anharmonicity for Zharkov equation the equation is from Dorogokupets 2015 :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in...
78,668
def nearest_edge(energy: float)-> Tuple[str, str]: """Return nearest x-ray edge for a given energy. Parameters ---------- energy X-ray energy in eV. Returns ------- : Absorption element. : Absorption edge. Raises ------ ValueError If ``energ...
78,669
def all_pairs(thebot): """Find all pairs and update the bot.""" # Gather some bot values base = thebot["pairs"][0].split("_")[0] exchange = thebot["account_name"] logger.info("Bot base currency: %s" % base) logger.info("Finding pairs: %s_ALL" % base) # Start from scratch newpairs = li...
78,670
def add_profile(**kwargs): """Adds a profile stub to scholarship graph""" config = kwargs.get("config") current_user = kwargs.get("current_user") config_manager = kwargs.get('config_manager') profile = EmailProfile(config) connection = config_manager.conns BF = config_manager.nsm.bf SCH...
78,671
def test_get_current_voucher(user): """ Test that get_current_voucher returns the most recently updated voucher for a user """ assert get_current_voucher(user) is None voucher1 = VoucherFactory(user=user) assert get_current_voucher(user) == voucher1 voucher2 = VoucherFactory(user=user) a...
78,672
def rect_break_or_contact_box(rect: Rect, box: Rect): """ Determine if the `rect` breaks the `box` or it contacts the border of `box` @param rect The Rect of the target rectangle @param box The target box """ return ( rect.left <= box.left or rect.right >= box.right or r...
78,673
def validate_keep(keep): """validates the value of the keep parameter If it's not coercable to an int or equal to the special string values, raise a ValueError. Otherwise, return `keep`. :param keep: value to validate :type keep: int or str :return: the validated value of keep :rtype: eith...
78,674
def default_database(): """ Returns DATABASE if env is set """ return os.environ.get('DATABASE', '')
78,675
def __get_instruments(currency: str, kind: str, expired: bool): """ Create a message to get all positions for a given currency on delta. :param currency: String symbol (e.g. 'BTC' or 'ETH') :param kind: Type of contract (either 'future' or 'option') :return: Message (dict) """ # Sanitize in...
78,676
async def test_unit_get_current_version_both_files_exist(mock_hub, hub, tmp_path): """ SCENARIO #4 - override_version_file DOES EXIST - main_version_file DOES EXIST """ # Link the function to the mock_hub mock_hub.saltenv.ops.get_current_version = hub.saltenv.ops.get_current_version # S...
78,677
def posths_enrollment_factors(persons, posths): """ Post high school enrollment rates by county, age, income and school type (public university, public community college, private university, private trade and vocational). TODO items: - Right now this is done at the county-level does it make...
78,678
def sha256_file(fname): """ Return sha256 of a given filename Copied from https://stackoverflow.com/a/3431838 """ hash_sha256 = hashlib.sha256() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_sha256.update(chunk) return hash_sha256.hexdig...
78,679
def create_iam_resources(env='dev', app='', **_): """Create the IAM Resources for the application. Args: env (str): Deployment environment/account, i.e. dev, stage, prod. app (str): Spinnaker Application name. Returns: True upon successful completion. """ session = boto3.se...
78,680
def _calculate_vm_load(vm_list): """ Given a list of VMs, Calculate the sum of the load. """ load = 0 for server in vm_list: pos = server.rfind('-') if pos < 0: pos = len(server)-1 load += weight(server[:pos]) return load
78,681
def get_list_of_commands(svg_dirs): """ Get a list of commands for converting each svg to png using cairosvg :param svg_dirs: the list of directories containing svg files :return: a list of commands """ command_list = [] # Each directory must be processed separately so that PNGs can be sequ...
78,682
def build_ufunc_wrapper(library, context, fname, signature, objmode, cres): """ Wrap the scalar function with a loop that iterates over the arguments """ assert isinstance(fname, str) byte_t = Type.int(8) byte_ptr_t = Type.pointer(byte_t) byte_ptr_ptr_t = Type.pointer(byte_ptr_t) intp_t ...
78,683
def __check_weave(): """Apparently presence of scipy is not sufficient since some versions experience problems. E.g. in Sep,Oct 2008 lenny's weave failed to work. May be some other converter could work (? See http://lists.debian.org/debian-devel/2008/08/msg00730.html for a similar report. Follo...
78,684
def test_confirm_valid(mock_choice, mock_print): """Validates if valid cases are working for sdu.validataion.confirm Parameters ---------- mock_choice : contains info about patched input() mock mock_print : contains info about patched print() mock Cases ----- - Both va...
78,685
def levensthein_dist(input_command: str, candidate: str) -> int: """ Implement the Levenshtein distance algorithm to determine, in case of a non-existing handle, if theres a very similar command to suggest. :param input_command: The non-existing handle the user gave as input :param candidate: The (...
78,686
def find_multiset_union(role1, role2, normalize=False, parameters=None): """ Finds the union of a multiset Parameters ------------- role1 First role originators role2 Second role originators normalize Do the normalization of the roles parameters Parameter...
78,687
def test_node_exporter_service(host): """Test that the node_exporter service is running.""" node_exporter_service = host.service("prometheus-node-exporter") assert node_exporter_service.is_enabled assert node_exporter_service.is_running
78,688
def Cijkl(C): """ Populates 4D elastic tensor from 6x6 elastic tensor :param C: 6x6 elastic constants tensor :return: 3x3x3x3 elastic Cijkl tensor """ c=np.zeros(shape=(3,3,3,3)) CC=np.zeros(shape=(9,9)) CC[0:6,0:6]=C[0:6,0:6] CC[6:9,6:9]=C[3:6,3:6] CC[0:6,6:9]=C[0:6,3:6] CC[6:9,0:6]=C[3:6,0:6] c[0,0,0,0]=...
78,689
def batch_reduce(x: Tensor): """return x.view(x.size(0), -1).sum(1)""" return flatten(x).sum(1)
78,690
def test_menu__preferences_menu__1(prefs_menu): """Asserting that the menu with the index 2 is `Preferences`.""" assert (prefs_menu.menu_item_title == prefs_menu.get_menu_item_title_under_test())
78,691
def send_task_func(task_id): """下发爬取任务""" with app.app_context(): scheduler_logger.info(f'开始调度任务:【task-id:{task_id}】') task_obj = task_model_proxy.find(id=task_id) if not task_obj: scheduler_logger.info(f'该任务已完成或已删除!:【task-id:{task_id}】') return # 判断当前主任务...
78,692
def _merge_flat_fsdp_opt_state(shards_to_load: List[Dict]) -> Dict: """Logic described here: https://tinyurl.com/2p86zffr""" result = shards_to_load[0][OPT_KEY] pad_info = _get_pad_info(shards_to_load[-1]) world_size = dist_utils.get_data_parallel_world_size() os2model_key = dict( zip(shards...
78,693
def split_heads_2d(x, num_heads): """Split channels (dimension 4) into multiple heads (becomes dimension 1). Args: x: a Tensor with shape [batch, height, width, channels] num_heads: an integer Returns: a Tensor with shape [batch, num_heads, height, width, channels / num_heads] """ return tf.transp...
78,694
def main(): """ Launcherfix and NVIDIA PhysX support. """ # Fixes the startup process. util.set_environment('WINEDLLOVERRIDES','dxgi=n') util.enable_dxvk_async() installpath = os.getcwd() if not os.path.isfile(os.path.join(os.path.abspath(installpath), 'bin', 'Win64_Shipping_Client', 'Man...
78,695
def read_df(df, metric): """ You can use `read_df(df,metric)` to load data from a `<class 'pandas.core.frame.DataFrame'>` object. It will return two objects. 1. a `DataFrame` with all hyperparameters' value and the value of metric you choose 2. a `list` of all hyperparameters' name """ p...
78,696
def solve_fast_diag(v: Sequence[AlignedArray], grid: grids.Grid, q0: Optional[AlignedArray] = None, implementation: Optional[str] = None) -> AlignedArray: """Solve for pressure using the fast diagonalization approach.""" del q0 # unused if grid.device_l...
78,697
def extract_data(): """Extract data from HTML file downloaded from AEIR website.""" cards = [] # HTML scraping soup = BeautifulSoup(open(HTML_FILE), features="html.parser") # Informations are in the recto of the card. The verso part is not relevant divs = soup.find_all("div", {"class": "card ...
78,698
def py_to_file(filename: str, content: str) -> None: """ 解密内容 :param filename: 文件 :param content: 内容 :return: """ with open(filename, "wb") as f: f.write(base64.b64decode(content))
78,699