content
stringlengths
22
815k
id
int64
0
4.91M
def sigmoid(x: np.ndarray, derivative: bool = False) -> np.ndarray: """ The sigmoid function which is given by 1/(1+exp(-x)) Where x is a number or np vector. if derivative is True it applied the derivative of the sigmoid function instead. Examples: >>> sigmoid(0) 0.5 >>> abs(sigmo...
5,353,200
def recv_rectangle(data): """ Handles receiving a rectangle Args: data (list): the data sent over by the server """ global board_elements global canvas if len(data) == 5: top_left = (int(data[1].split(" ")[0]), int(data[1].split(" ")[1])) bottom_right = (int(data[2]....
5,353,201
def create_hierarchy( num_samples, bundle_size, directory_sizes=None, root=".", start_sample_id=0, start_bundle_id=0, address="", n_digits=1, ): """ SampleIndex Hierarchy Factory method. Wraps create_hierarchy_from_max_sample, which is a max_sample-based API, not a numSam...
5,353,202
def run_process(grammar, commandline, tmpdir): """ 'PROCESS' test command runner. It will call ``grammarinator-process`` with the specified command line. Tests whether the processing of the grammar (creating a fuzzer from it) is working properly. :param grammar: file name of the grammar that contai...
5,353,203
def mock_config_file_with_auth_browser(): """A pytest fixture that creates a temporary directory and a config file to match. Deletes directory after test""" # Load auth config for testing test_auth_file = os.path.join(resource_filename('gtmcore', 'auth{}te...
5,353,204
def eval_sysu(distmat, q_pids, g_pids, q_camids, g_camids, max_rank = 20): """Evaluation with sysu metric Key: for each query identity, its gallery images from the same camera view are discarded. "Following the original setting in ite dataset" """ num_q, num_g = distmat.shape if num_g < max_rank: ...
5,353,205
def espa_login() -> str: """ Get ESPA password using command-line input :return: """ return getpass.getpass("Enter ESPA password: ")
5,353,206
def search_hyperparameters(simulation_folder, method='RF', mode='classification'): """ Function for searching best hyperparameters for random forest algorithm :param simulation_folder: str, name of subfolder for given data set :return: none, hyperparameters are saved down as side effect """ Sta...
5,353,207
def row_up1_array(row, col): """This function establishes an array that contains the index for the row above each entry""" up1_array = np.zeros((row, col), dtype=np.uint8) for i in range(row): up1_array[i, :] = np.ones(col, dtype = np.uint8) * ((i - 1) % row) return up1_array
5,353,208
def lcm(a, b): """Return lowest common multiple.""" return a * b // gcd(a, b)
5,353,209
def chl_mean_hsl(weights: np.ndarray) -> Callable[[np.ndarray], np.ndarray]: """ return a function that can calculate the channel-wise average of the input picture in HSL color space """ return lambda img: np.average(cv2.cvtColor(img, cv2.COLOR_BGR2HLS), axis=(0, 1), weights=weights)
5,353,210
def cosine_mrl_option(labels, predicts): """For a minibatch of image and sentences embeddings, computes the pairwise contrastive loss""" #batch_size, double_n_emd = tensor.shape(predicts) #res = tensor.split(predicts, [double_n_emd/2, double_n_emd/2], 2, axis=-1) img = l2norm(labels) text = l2norm(...
5,353,211
def escape_cdata(cdata): """Escape a string for an XML CDATA section""" return cdata.replace(']]>', ']]>]]&gt;<![CDATA[')
5,353,212
def insert_hosts(raw_data, to_site_id, to_taxon_id): """Insert hosts.""" log(f'Inserting {DATASET_ID} hosts') raw_data['host_id'] = db.get_ids(raw_data, 'hosts') raw_data['site_key'] = tuple(zip( raw_data.Latitude_Original, raw_data.Longitude_Original, raw_data.verbatim_elevati...
5,353,213
def _collect_data_for_docstring(func, annotation): """ Collect data to be printed in docstring. The data is collected from custom annotation (dictionary passed as a parameter for the decorator) and standard Python annotations for the parameters (if any). Data from custom annotation always overrides ...
5,353,214
def _strip_unbalanced_punctuation(text, is_open_char, is_close_char): """Remove unbalanced punctuation (e.g parentheses or quotes) from text. Removes each opening punctuation character for which it can't find corresponding closing character, and vice versa. It can only handle one type of punctuation ...
5,353,215
def read(fin, alphabet=None): """Read and parse a fasta file. Args: fin -- A stream or file to read alphabet -- The expected alphabet of the data, if given Returns: SeqList -- A list of sequences Raises: ValueError -- If the file is unparsable """ seqs = [s for s...
5,353,216
def trip_destination( trips, tours_merged, chunk_size, trace_hh_id): """ Choose a destination for all 'intermediate' trips based on trip purpose. Final trips already have a destination (the primary tour destination for outbound trips, and home for inbound trips.) """ t...
5,353,217
def get_min_max_value(dfg): """ Gets min and max value assigned to edges in DFG graph Parameters ----------- dfg Directly follows graph Returns ----------- min_value Minimum value in directly follows graph max_value Maximum value in directly follows grap...
5,353,218
def process_post(category_id, post_details, user): """Check topic is present in Discourse. IF exists then post, otherwise create new topic for category """ error = False error_message = '' # DISCOURSE_DEV_POST_SUFFIX is used to differentiate the same target name from different dev systems in Discou...
5,353,219
def vgg_fcn(num_classes=1000, pretrained=False, batch_norm=False, **kwargs): """VGG 16-layer model (configuration "D") Args: num_classes(int): the number of classes at dataset pretrained (bool): If True, returns a model pre-trained on ImageNet batch_norm: if you want to introduce batch n...
5,353,220
def test_write(string: str) -> None: """Test illud.outputs.standard_output.StandardOutput.write.""" stdout_mock = MagicMock(sys.stdout) with patch('sys.stdout', stdout_mock): standard_output: StandardOutput = StandardOutput() standard_output.write(string) stdout_mock.write.assert_called_on...
5,353,221
def apply_heatmap( frame: npt.NDArray[np.uint8], cmap: Union[str, Colormap] = "Pastel1", normalize: bool = True, ) -> npt.NDArray[np.uint8]: """Apply heatmap to an input BGR image. Args: frame (npt.NDArray[np.uint8]) : Input image (BGR). cmap (Union[str, Colormap], optional)...
5,353,222
def fmt_time(timestamp): """Return ISO formatted time from seconds from epoch.""" if timestamp: return time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(timestamp)) else: return '-'
5,353,223
def lislice(iterable, *args): """ (iterable, stop) or (iterable, start, stop[, step]) >>> lislice('ABCDEFG', 2) ['A', 'B'] >>> lislice('ABCDEFG', 2, 4) ['C', 'D'] >>> lislice('ABCDEFG', 2, None) ['C', 'D', 'E', 'F', 'G'] >>> lislice('ABCDEFG', 0, None, 2) ['A', 'C', 'E', 'G'] """...
5,353,224
async def up(ctx): """ A command to update the kebab cote. """ global cote cote += 1 msg = "```" msg += "+1 pour Tristan : ta cote est maintenant de " msg += str(cote) msg += "```" await ctx.send(msg)
5,353,225
def solve_with_duplicate_optional_items(data, max_height, max_width): """Solve the problem by building 2 optional items (rotated or not) for each item.""" # Derived data (expanded to individual items). data_widths = data['width'].to_numpy() data_heights = data['height'].to_numpy() data_availability ...
5,353,226
def calculate_transition_cost(number_objs: int, target_storage_class: str) -> float: """ Calculates the cost of transition data from one class to another Args: number_objs: the number of objects that are added on a monthly basis target_storage_class: the storage class the objects will resid...
5,353,227
def _exceptionwarning(ui): """Produce a warning message for the current active exception""" # For compatibility checking, we discard the portion of the hg # version after the + on the assumption that if a "normal # user" is running a build with a + in it the packager # probably built from fairly cl...
5,353,228
def get_covid(): """This module sends off a covid notification. You can't get covid from this.""" covid_data = covid_handler() covid_content = Markup("Date: " + str(covid_data["date"]) + ",<br/>Country: " + str( covid_data["areaName"]) + ",<br/>New Cases: " + str( covid_data["newCasesBy...
5,353,229
def chunks(l, n): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i : i + n]
5,353,230
def send_songogram(your_name, artist_first_name, artist_last_name, song_name, number_to_call): """ Function for sending a Sonogram. :param your_name: string containing the person sending the sonogram's name. :param artist_first_name: string containing the musician's first name. :param artist_last_name: ...
5,353,231
def set_proto_message_event( pb_message_event, span_data_message_event): """Sets properties on the protobuf message event. :type pb_message_event: :class: `~opencensus.proto.trace.Span.TimeEvent.MessageEvent` :param pb_message_event: protobuf message event :type span_data_messa...
5,353,232
def segm_and_cat(sersic_2d_image): """fixture for segmentation and catalog""" image_mean, image_median, image_stddev = sigma_clipped_stats(sersic_2d_image, sigma=3) threshold = image_stddev * 3 # Define smoothing kernel kernel_size = 3 fwhm = 3 # Min Source size (area) npixels = 4 ** ...
5,353,233
def p_function_definition(p): """function_definition : declaration_specifiers declarator declaration_list compound_statement | function_definition_full compound_statement | declarator declaration_list compound_statement | declarator compound_statement""" global LAST_FUNCTION_DECLARATION symTab =...
5,353,234
def break_word_by_trailing_integer(pname_fid: str) -> Tuple[str, str]: """ Splits a word that has a value that is an integer Parameters ---------- pname_fid : str the DVPRELx term (e.g., A(11), NSM(5)) Returns ------- word : str the value not in parentheses value : ...
5,353,235
def parse_args(): """ parse command line arguments :return dict: dictionary of parameters """ argparser = argparse.ArgumentParser() # training data argparser.add_argument('--trainfiles', nargs='*', default=['./data/valid.tfrecords'], help='Data file(s) for training (tfrecord).') argpa...
5,353,236
def preprocess_data(image, label, is_training): """CIFAR data preprocessing""" image = tf.image.convert_image_dtype(image, tf.float32) if is_training: crop_padding = 4 image = tf.pad(image, [[crop_padding, crop_padding], [crop_padding, crop_padding], [0, 0]], 'REFLECT') ima...
5,353,237
def delete_env(dlpx_obj, env_name): """ Deletes an environment engine: Dictionary of engines env_name: Name of the environment to delete """ engine_name = dlpx_obj.dlpx_engines.keys()[0] env_obj = find_obj_by_name(dlpx_obj.server_session, environment, env_n...
5,353,238
def write_to_json_file(content, path: str, indent: int = 4, sort_keys: bool = False, silent: bool = True) -> None: """ Convenience function to write the given content to a json file :param content: Content to write t...
5,353,239
def load_Counties(): """ Use load_country() instead of this function """ # Get data # Load data using Pandas dfd = { 'positive': reread_csv(csv_data_file_Global['confirmed_US']), 'death': reread_csv(csv_data_file_Global['deaths_US']), } return dfd
5,353,240
def extract_parmtop_residue_with_name(filename, resname): """ fixme - update doc Extract residue name and atom name/type mapping from input parmtop. Note: Only one residue must be present in the topology. Parameters ---------- filename: Path Filename of the input parmtop. Retur...
5,353,241
def validate_model_present(program_name, optional_arg_map): """ Determine if the model file was passed separately or requires extraction from the archive. If the model is in the archive, extract it to the temporary model location, and set that file as the MODEL_FILE_SWITCH argument. The MODEL_FILE_S...
5,353,242
def issetiterator(object: Iterator[Any]) -> bool: """Returns True or False based on whether the given object is a set iterator. Parameters ---------- object: Any The object to see if it's a set iterator. Returns ------- bool Whether the given object is a set iterator. "...
5,353,243
def temporal_discretization(Y, method='ups_downs', kwargs={}): """This function acts as a switcher for temporal discretizations and wraps all the functions which carry out discretization over time of time-series. Parameters ---------- Y : array_like, shape (N, M) the signal of each element ...
5,353,244
def delete(client: ModelTrainingClient, train_id: str, file: str, ignore_not_found: bool): """ Delete a training.\n For this command, you must provide a training ID or path to file with one training. The file must contain only one training. If you want to delete multiples trainings than you should u...
5,353,245
def test_pre_flop_pot(n_players: int, small_blind: int, big_blind: int): """Test preflop the state is set up for player 2 to start betting.""" state, pot = _new_game( n_players=n_players, small_blind=small_blind, big_blind=big_blind, ) n_bet_chips = sum(p.n_bet_chips for p in state.players) ...
5,353,246
def plotModeScatter( pc , xMode=0, yMode=1, zMode=None, pointLabels=None, nTailLabels=3, classes=None): """ scatter plot mode projections for up to 3 different modes. PointLabels is a list of strings corresponding to each shape. nTailLabels defines number of points that are labelled at the tails of the distribution...
5,353,247
def log_benchmarks(benchmarks): """Record all the benchmarks in the log""" log.debug('Benchmarks') log.debug('==========') for bench in benchmarks: log.debug(bench) log.debug('')
5,353,248
def cron_worker(request): """Parse JSON/request arguments and start ingest for a single date export""" request_json = request.get_json(silent=True) request_args = request.args if request_json and 'image' in request_json: image_id = request_json['image'] elif request_args and 'image' in requ...
5,353,249
def test_debug(): """Log an debug message""" print("This message is a %s" % colors.debug("debug message."))
5,353,250
def test_r1t6(capsys): """Check that you cannot transfer between accounts before logging in Arguments: capsys -- object created by pytest to capture stdout and stderr """ helper( capsys=capsys, terminal_input=['transfer', 'login', 'atm', 'logout', 'No'], intput_valid_acc...
5,353,251
def calculatetm(seq): """ Calculate Tm of a target candidate, nearest neighbor model """ NNlist = chopseq(seq, 2, 1) NNtable = ['AA', 'AC', 'AG', 'AT', 'CA', 'CC', 'CG', 'CT', 'GA', 'GC', 'GG', 'GT', 'TA', 'TC', 'TG', 'TT'] NNendtable = ['A', 'C', 'G', 'T'] NNcount = np.zeros(16) NNend = np.zero...
5,353,252
def share_article_to_group(user, base_list_id, article_id, group_id, target_list_id): """ @api {post} /user/list/:id/article/:id/share/group/:id/list/:id Share a article to group list. @apiName Share a article into a group list. @apiGroup Share @apiUse AuthorizationTokenHeader @apiUse Unauthor...
5,353,253
def _patch_command_processing(command_plugin): """ Patches the command processing functionality to work with promises. :param command_plugin: command plugin to modify. :return: """ if hasattr(command_plugin.__class__, '_old_process_command_response'): logger.debug('Already patched') ...
5,353,254
def get_data_shape(X_train, X_test, X_val=None): """ Creates, updates and returns data_dict containing metadata of the dataset """ # Creates data_dict data_dict = {} # Updates data_dict with lenght of training, test, validation sets train_len = len(X_train) test_len = len(X_test) d...
5,353,255
def setupAnnotations(context): """ set up the annotations if they haven't been set up already. The rest of the functions in here assume that this has already been set up """ annotations = IAnnotations(context) if not FAVBY in annotations: annotations[FAVBY] = PersistentList() r...
5,353,256
def _get_media(media_types): """Helper method to map the media types.""" get_mapped_media = (lambda x: maps.VIRTUAL_MEDIA_TYPES_MAP[x] if x in maps.VIRTUAL_MEDIA_TYPES_MAP else None) return list(map(get_mapped_media, media_types))
5,353,257
def get_int_property(device_t, property): """ Search the given device for the specified string property @param device_t Device to search @param property String to search for. @return Python string containing the value, or None if not found. """ key = cf.CFStringCreateWithCString( ...
5,353,258
def _get_unique_barcode_ids(pb_index, isoseq_mode=False): """ Get a list of sorted, unique fw/rev barcode indices from an index object. """ bc_sel = (pb_index.bcForward != -1) & (pb_index.bcReverse != -1) bcFw = pb_index.bcForward[bc_sel] bcRev = pb_index.bcReverse[bc_sel] bc_ids = sorted(li...
5,353,259
def AddCommonArguments(parser): """Adds arguments common to parsers. Args: parser: ArgumentParser object, used to parse flags. """ parser.add_argument("--email", type=str, dest="email", help="Email account to use for authen...
5,353,260
def tests(session_: Session, django: str) -> None: """Run the test suite.""" requirements = Path("requirements.txt") session_.run( "poetry", "export", f"-o{requirements}", "--dev", "--without-hashes", external=True, ) session_.install(f"-r{requirements...
5,353,261
def clean_logs(test_yaml, args): """Remove the test log files on each test host. Args: test_yaml (str): yaml file containing host names args (argparse.Namespace): command line arguments for this program """ # Use the default server yaml and then the test yaml to update the default #...
5,353,262
def call_posterior_haplotypes(posteriors, threshold=0.01): """Call haplotype alleles for VCF output from a population of genotype posterior distributions. Parameters ---------- posteriors : list, PosteriorGenotypeDistribution A list of individual genotype posteriors. threshold : float ...
5,353,263
def to_linprog(x, y, xy_dist) -> LinProg: """ Parameters ---------- x : ndarray 1 - dimensional array of weights y : ndarray 1 - dimensional array of weights xy_dist : ndarray 2 - dimensional array containing distances between x and y density coordinates Returns ...
5,353,264
def get_discorded_labels(): """ Get videos with citizen discorded labels Partial labels will only be set by citizens """ return get_video_labels(discorded_labels)
5,353,265
def set_common_tags(span: object, result: object): """Function used to set a series of common tags to a span object""" if not isinstance(result, dict): return span for key, val in result.items(): if key.lower() in common_tags: span.set_tag(key, val) re...
5,353,266
def local_timezone(): """ Returns: (str): Name of current local timezone """ try: return time.tzname[0] except (IndexError, TypeError): return ""
5,353,267
def ask_credentials(): """Interactive function asking the user for ASF credentials :return: tuple of username and password :rtype: tuple """ # SciHub account details (will be asked by execution) print( " If you do not have a ASF/NASA Earthdata user account" " go to: https://sea...
5,353,268
def lab2lch(lab): """CIE-LAB to CIE-LCH color space conversion. LCH is the cylindrical representation of the LAB (Cartesian) colorspace Parameters ---------- lab : array_like The N-D image in CIE-LAB format. The last (``N+1``-th) dimension must have at least 3 elements, correspondi...
5,353,269
def get_valid_principal_commitments(principal_id=None, consumer_id=None): """ Returns the list of valid commitments for the specified principal (org or actor. If optional consumer_id (actor) is supplied, then filtered by consumer_id """ log.debug("Finding commitments for principal: %s", principal_id...
5,353,270
def callattice(twotheta, energy_kev=17.794, hkl=(1, 0, 0)): """ Calculate cubic lattice parameter, a from reflection two-theta :param twotheta: Bragg angle, deg :param energy_kev: energy in keV :param hkl: reflection (cubic only :return: float, lattice contant """ qmag = calqmag(twotheta...
5,353,271
def reset_password( *, db: Session = Depends(get_db), current_user: User = Depends(get_current_active_user), background_tasks: BackgroundTasks, ): """reset current user password""" email = current_user.email # send confirm email if settings.EMAILS_ENABLED and email: ...
5,353,272
def rule_valid_histone_target(attr): """ { "applies" : ["ChIP-Seq", "experiment_target_histone"], "description" : "'experiment_target_histone' attributes must be 'NA' only for ChIP-Seq Input" } """ histone = attr.get('experiment_target_histone', [''])[0] if attr.get('experiment_type', [""])[0].lo...
5,353,273
def extend(curve: CustomCurve, deg): """returns curve over the deg-th relative extension""" E = curve.EC q = curve.q K = curve.field if q % 2 != 0: R = K["x"] pol = R.irreducible_element(deg) Fext = GF(q ** deg, name="z", modulus=pol) return E.base_extend(Fext) ch...
5,353,274
def flatten3D(inputs: tf.Tensor) -> tf.Tensor: """ Flatten the given ``inputs`` tensor to 3 dimensions. :param inputs: >=3d tensor to be flattened :return: 3d flatten tensor """ shape = inputs.get_shape().as_list() if len(shape) == 3: return inputs assert len(shape) > 3 retu...
5,353,275
def get_classes(dataset): """Get class names of a dataset.""" alias2name = {} for name, aliases in dataset_aliases.items(): for alias in aliases: alias2name[alias] = name if mmcv.is_str(dataset): if dataset in alias2name: labels = eval(alias2name[dataset...
5,353,276
def split_exclude_string(people): """ Function to split a given text of persons' name who wants to exclude with comma separated for each name e.g. ``Konrad, Titipat`` """ people = people.replace('Mentor: ', '').replace('Lab-mates: ', '').replace('\r\n', ',').replace(';', ',') people_list = peop...
5,353,277
def now(tz=DEFAULT_TZ): """ Get the current datetime. :param tz: The preferred time-zone, defaults to DEFAULT_TZ :type tz: TzInfo (or similar pytz time-zone) :return: A time-zone aware datetime set to now :rtype: datetime """ return datetime.now(tz=tz)
5,353,278
def egd_add_metatags(context): """Override `Web Page` Doctype template if CMS page.""" if is_app_for_actual_site(): # Allow CMS webpages if context.doctype == "Web Page": context.template = "templates/web.html" # Override metatags if not "metatags" in context: context.metatags = frappe._dict({}) con...
5,353,279
def MultMat(dest, A, B): """ Multiply two matrices together. Store result in "dest". """ I = len(A) J = len(B[0]) K = len(B) # or len(A[0]) for i in range(0,I): for j in range(0,J): dest[i][j] = 0.0 for k in range(0,K): dest[i][j] += A[i][k] * B[k...
5,353,280
def peek_with_kwargs(init, args=[], permissive=False): """ Make datatypes passing keyworded arguments to the constructor. This is a factory function; returns the actual `peek` routine. Arguments: init (callable): type constructor. args (iterable): arguments NOT to be keyworded; order...
5,353,281
def idc_asset_manage(request,aid=None,action=None): """ Manage IDC """ if request.user.has_perms(['asset.view_asset', 'asset.edit_asset']): page_name = '' if aid: idc_list = get_object_or_404(IdcAsset, pk=aid) if action == 'edit': page_name = '编辑ID...
5,353,282
def set_justspeaklasttime(speackdata): """ Adds a warning to user """ data_file_path = os.getcwd() + '/just_speack_data.json' if not os.path.exists(data_file_path): with open(data_file_path, 'w', encoding='UTF-8') as data_file: data_file.write(json.dumps({})) data_fi...
5,353,283
def get_detected_column_types(df): """ Get data type of each columns ('DATETIME', 'NUMERIC' or 'STRING') Parameters: df (df): pandas dataframe Returns df (df): dataframe that all datatypes are converted (df) """ assert isinstance(df, pd.DataFrame), 'Parameter must be DataFrame' ...
5,353,284
def set_bin_path(): """ Sets the juju binary path """ candidates = [ '/snap/bin/juju', '/snap/bin/conjure-up.juju', '/usr/bin/juju', '/usr/local/bin/juju', ] _check_bin_candidates(candidates, 'bin_path') # Update $PATH so that we make sure this candidate is used ...
5,353,285
def distance(coords): """Calculates the distance of a path between multiple points Arguments: coords -- List of coordinates, e.g. [(0,0), (1,1)] Returns: Total distance as a float """ distance = 0 for p1, p2 in zip(coords[:-1], coords[1:]): distance += ((p2[0] - p1[0]) ** 2...
5,353,286
def roll_dice(dicenum, dicetype, modifier=None, conditional=None, return_tuple=False): """ This is a standard dice roller. Args: dicenum (int): Number of dice to roll (the result to be added). dicetype (int): Number of sides of the dice to be rolled. modifier (tuple): A tuple `(operator, val...
5,353,287
def build_central_hierarchical_histogram_computation( lower_bound: float, upper_bound: float, num_bins: int, arity: int = 2, max_records_per_user: int = 1, epsilon: float = 1, delta: float = 1e-5, secure_sum: bool = False): """Create the tff federated computation for central hierarchic...
5,353,288
def initialise_halo_params(): """Initialise the basic parameters needed to simulate a forming Dark matter halo. Args: None Returns: G: gravitational constant. epsilon: softening parameter. limit: width of the simulated universe. radius: simulated radius of each particle ...
5,353,289
def read_data(image_paths, label_list, image_size, batch_size, max_nrof_epochs, num_threads, shuffle, random_flip, random_brightness, random_contrast): """ Creates Tensorflow Queue to batch load images. Applies transformations to images as they are loaded. :param random_brightness: :param...
5,353,290
def test_run_retries(): """Should retry until a success condition is reached""" responses = [httpretty.Response(body="Internal Server Error", status=500), httpretty.Response(body="Internal Server Error", status=500), httpretty.Response(body="<html></html>", status=200)] htt...
5,353,291
def reorder_matrix (m, d) : """ Reorder similarity matrix : put species in same cluster together. INPUT: m - similarity matrix d - medoid dictionary : {medoid : [list of species index in cluster]} OUTPUT : m in new order new_order - order of species indexes in matrix """ new_or...
5,353,292
def extract_sound(video_filename): """Given the name of a video, extract the sound to a .wav file, and return the filename of the new file.""" # Generate a filename for the temporary audio file with NamedTemporaryFile(suffix='.wav') as tf: wave_filename = tf.name # Extract the sound from the v...
5,353,293
def init_plugins(config_path: Optional[str] = None) -> None: """ init_plugins loads the plugins from the specified config, the path specified by TORCHX_CONFIG environment variable or the default location at /etc/torchx/config.yaml. """ if not config_path: config_path = os.getenv(TORCHX_C...
5,353,294
def valid_utility_climate_zone_combos(utility, year): """Returns all utility-climate zone combinations""" utility_cz = get_all_valid_utility_climate_zone_combinations(year, utility) click.echo( json.dumps( utility_cz.groupby("utility")["climate_zone"] .agg(lambda x: ", ".join...
5,353,295
def reward_penalized_log_p(mol): """ Reward that consists of log p penalized by SA and # long cycles, as described in (Kusner et al. 2017). Scores are normalized based on the statistics of 250k_rndm_zinc_drugs_clean.smi dataset :param mol: rdkit mol object :return: float """ # normalizat...
5,353,296
def loadmat(filename, variable_names=None): """ load mat file from h5py files :param filename: mat filename :param variable_names: list of variable names that should be loaded :return: dictionary of loaded data """ data = {} matfile = h5py.File(filename, 'r') if variable_names is N...
5,353,297
def date_start_search(line): """予定開始の日付を検出し,strで返す.""" # 全角スペース zen_space = ' ' # 全角0 zen_zero = '0' nichi = '日' dollar = '$' # 全角スペースを0に置き換えることで無理やり対応 line = line.replace(zen_space, zen_zero) index = line.find(nichi) # 日と曜日の位置関係から誤表記を訂正 index_first_dollar = line.find(dol...
5,353,298
def train_sub1(sess, x, y, bbox_preds, x_sub, y_sub, nb_classes, nb_epochs_s, batch_size, learning_rate, data_aug, lmbda, aug_batch_size, rng, img_rows=48, img_cols=48, nchannels=3): """ This function creates the substitute by alternatively augmenting the training d...
5,353,299