content
stringlengths
22
815k
id
int64
0
4.91M
def format_endpoint_argument_doc(argument): """Return documentation about the argument that an endpoint accepts.""" doc = argument.doc_dict() # Trim the strings a bit doc['description'] = clean_description(py_doc_trim(doc['description'])) details = doc.get('detailed_description', None) if detai...
49,900
def from_edgelist(filename, directed=False, num_vertices=None, **kwargs) -> Graph: """ Construct an ``sgtl.Graph`` object from an edgelist file. The edgelist file represents a graph by specifying each edge in the graph on a separate line in the file. Each line looks like:: id1 id2 <weight> ...
49,901
def shn_shelter_rheader(r, tabs=[]): """ Resource Headers """ if r.representation == "html": rheader_tabs = shn_rheader_tabs(r, tabs) record = r.record rheader = DIV(TABLE( TR( TH(Tstr("Name") + ": "), record.name ...
49,902
def explode_scalars(input_indices_vtk, input_values_vtk='', output_stem='', exclude_values=[-1], background_value=-1, output_scalar_name='scalars', remove_background_faces=True, reindex=True, verbose=False): """ Write out a separate...
49,903
def usig1(bitarray: UBitArray32) -> UBitArray32: """ (uppercase sigma 1) Computes the XOR of three sets of bits which result from rotating the input set rightwards by 6, then 11, and then 25. Args: bitarray: (UBitArray32) The set of bits to operate on. Returns: (UBitArray3...
49,904
def fullRadar(dicSettings, mcTable): """ Calculates the radar variables over the entire range Parameters ---------- dicSettings: a dictionary with all settings output from loadSettings() mcTable: McSnow data output from getMcSnowTable() Returns ------- specXR: xarray dataset with t...
49,905
def cli(env, host_id, subnet_id): """Assigns subnets to a given host""" block_manager = SoftLayer.BlockStorageManager(env.client) subnet_id_list = list(subnet_id) click.echo('Test to spit out %s' % subnet_id_list[0]) click.echo('\n Test to spit out 2 %s' % type(subnet_id)) #print out the subn...
49,906
def debugsuccessorssets(ui, repo, *revs, **opts): """show set of successors for revision A successors set of changeset A is a consistent group of revisions that succeed A. It contains non-obsolete changesets only unless closests successors set is set. In most cases a changeset A has a single succe...
49,907
def connect_db(uri, default_db_name=None, factory=pymongo.MongoClient): """ Use pymongo to parse a uri (possibly including database name) into a connected database object. This serves as a convenience function for the common use case where one wishes to get the Database object and is less concerned...
49,908
def send_email(to_email, subject, message): """This function is used to send email. Takes in email_to, subject, message as parameters :param to_email: person to be sent email :param subject: subject of the email :param message: message of the email :return: a message, success or fail """ ...
49,909
def parse_path(path: Path): """Obtain filename, task, framework and engine from saved path. """ if re.match(r'^.*?[!/]*/[A-Za-z]+-[A-Za-z]+/[A-Za-z_]+/\d+$', str(path.with_suffix(''))): filename = path.name architecture = path.parent.parent.parent.stem task = Task[path.parent.name] ...
49,910
def check_newer_version(command: str): """ Query for the latest release of the chaostoolkit to compare it with the current's version. If the former is higher then issue a warning inviting the user to upgrade its environment. """ try: command = command.strip() r = requests.get(LAT...
49,911
def pipeline( project_id=PROJECT_ID, region=REGION, args=json.dumps([ '--task', 'language_modeling', 'data-bin/wikitext-103', '--save-dir', 'checkpoints/transformer_wikitext-103', '--arch', 'transformer_lm', '--share-decoder-input-output-embed', '--dropout', '0.1', ...
49,912
def prettyprint(s, toUpper=False): """Given a string, replaces underscores with spaces and uppercases the first letter of each word ONLY if the string is composed of lowercased letters. If the param, toUpper is given then s.upper is returned. Examples: "data_quality" -> "Data Quality" "copy_number...
49,913
def doFilter(rule, dstPath): """ 过滤 """ global useStart global useEnd global useConatins global searchInChild # 文件名后缀(可以包含 点号) global fileNameSuffix temp = rule.get("searchInChild", False) if True == temp: searchInChild = True print "searchInChild is " + s...
49,914
def generate(schema_id: str) -> tuple: """Generates sample data from a schema :param str schema_id: Schema id :return: A http response :rtype: tuple """ search = [{'schema': schema_id}] if ObjectId.is_valid(schema_id): search.append({'_id': ObjectId(schema_id)}) schema = app....
49,915
def recombine_edges(output_edges): """ Recombine a list of edges based on their rules. Recombines identical Xe isotopes. Remove isotopes. :param output_edges: :return: """ mol = Chem.MolFromSmiles(".".join(output_edges)) # Dictionary of atom's to bond together and delete if they come in ...
49,916
def convert_up(filename): """ Convert a file from old format to new format. """ out_filename = filename + ".upconverted" if os.access(out_filename, os.F_OK): os.remove(out_filename) print "upconverting", filename, "to", out_filename with open(filename, 'r') as infile: with ...
49,917
def initializeHdf5Write(filepath, groupname=None, **kwds): """ Prepares an hdf5 file for output Parameters ---------- filepath : `str` The output file name groupname : `str` or `None` The output group name Returns ------- group : `h5py.File` or `h5py.Group` The ...
49,918
def run(data, out, binary): """Run randomness tests on DATA and write results to OUT. DATA is a newline-delimited text file which contains output of a random number generator. Individual results of each test are printed as they come. Once they are all finished, the results are written to OUT. ...
49,919
def to_num_groups(word_groups): """ This function returns the a list of 24 numbers from a list of 24 words representing the payload """ with open('wordlist.txt', 'rb') as (file): words = file.readlines() words = [word.decode('utf8').strip() for word in words] num_groups = [words.inde...
49,920
def notify_not_mergeable_prs_in_slack(not_mergeable_prs: list): """ Send notification to slack with the IDs of PRs with conflicts - not_mergeable_prs [array]: list of Pull Resquest IDs in string format """ data = { 'prs_list': ', '.join(not_mergeable_prs) } requests.post(SLACK_WEBH...
49,921
def _rsqrt(step_number, tail_start, body_value): """Computes a tail using a scaled reciprocal square root of step number. Args: step_number: Absolute step number from the start of training. tail_start: Step number at which the tail of the curve starts. body_value: Value relative to which the tail shoul...
49,922
def set_formula_in_row(ws, num, row, mr_col=1): """ This "loops" through single cells in a column and applies mixing ratio formulas. The format of the formulas is quite convulted for legacy reasons. Existing procedures made adhering to this format easier, but the gist is below. Samples come in sets of ...
49,923
def prepare_ablation_from_path( path: Union[str, pathlib.Path], directory: Union[str, pathlib.Path], save_artifacts: bool, ) -> List[Tuple[pathlib.Path, pathlib.Path]]: """Prepare a set of ablation study directories. :param path: Path to configuration file defining the ablation studies. :param ...
49,924
def print_confusion_matrix(confusion_matrix, class_names, title=None, dataset='Test', cmap=plt.cm.Blues, figsize = (16,10), fontsize=14): """Prints a confusion matrix, as returned by sklearn.metrics.confusion_matrix, as a heatmap. Arguments --------- confusion_matrix: numpy.ndarray The nump...
49,925
def read_txt_into_list(file_path): """ read the list from the file, each elem in a line compose a list, each line compose to a list, the elem "None" would be filtered and not considered :param file_path: the file path to read :return: list of list """ assert os.path.isfile(file_path), "the f...
49,926
def currentTime(*args, **kwargs): """ Modifications: - if no args are provided, the command returns the current time """ if not args and not kwargs: return cmds.currentTime(q=1) else: return cmds.currentTime(*args, **kwargs)
49,927
def get_shapes(gdf: gpd.GeoDataFrame, colname: str) -> list: """ Extract and associate and format geometry and data in GeoDataFrame. """ assert "geometry" in gdf.columns, f"Expected `geometry` in {gdf.columns=}" assert colname in gdf.columns, f"Expected {colname!r} in {gdf.columns=}." return [(...
49,928
def _decodeUserData(byteIter, userDataLen, dataCoding, udhPresent): """ Decodes PDU user data (UDHI (if present) and message text) """ result = {} if udhPresent: # User Data Header is present result['udh'] = [] udhLen = next(byteIter) ieLenRead = 0 # Parse and store U...
49,929
def import_all_vulndata(overwrite=False, nexpose_server={}): """ Uses the NexposeAPI and imports each and every vulnerability to Kvasir. Can take a looooong time. Args: overwrite: Whether or not to overwrite an existing t_vulndata record Returns: msg: A string message of status. ""...
49,930
def add_category(category_name): """ REST-like endpoint to add a category :returns: Customized output from GIPHY :rtype: json """ user = ( models.database.session.query(models.users.User) .filter( models.users.User.token == flask.request.cookies["X-Auth-Token"] ...
49,931
def write_predictions( pickle_file_name, denorm_recon_radar_matrices, full_storm_id_strings, storm_times_unix_sec, mse_by_example, upconvnet_file_name): """Writes predictions (reconstructed radar images) to Pickle file. E = number of examples :param pickle_file_name: Path to output file. ...
49,932
def scale_multipolygon(im_name, mpoly, height, width): """scales a multipolgon using the gridsizes provided by kaggle admins""" grid_sizes = pd.read_csv(os.path.join(global_vars.DATA_DIR,'grid_sizes.csv'), index_col=0) x_max = grid_sizes.loc[im_name, 'Xmax'] y_min = grid_sizes.loc[im_name, 'Ymin'] ...
49,933
async def send_embed( channel: Messageable, embed_text: str, title: str = "", url: Optional[str] = None, colour: Colour = Colour(settings.embed_color_normal), footer_text: Optional[str] = None, footer_icon: Optional[str] = None, timestamp: Optional[datetim...
49,934
def syslog_local_monitor_disable(handle): """ This method disables logs on local monitor. Args: handle (UcscHandle) Returns: CommSyslogMonitor: Managed Object Raises: UcscOperationError: If CommSyslogMonitor is not present Example: mo = syslog_local_monitor_di...
49,935
def test_reload_command(mocker): """ When: - reloading data from to the api to integration context Then: - checks if the reloading finished successfully """ mock_data_from_api = RAW_DATA mocker.patch.object(Client, "http_request", return_value...
49,936
def git_push_obj(verbose, remote, obj=None): """ Push given object to git :param obj: object wich will be pushed to git :type obj: any one implements the interface of pushing to git :rparam boolean: If success return True """ try: LOGGER.info("%s: pushing to remote - %s", verbose, ...
49,937
def partial_generator(api_list, seed = datetime.now().microsecond): """ Randomly denys access to certain API functions :param api_list: The list of functions in the api :param seed: An int, allows for seeding the tests with a certain seed to create predictable results :return: Returns an api where r...
49,938
def get_key_from_event(*, event: dict) -> str: """Return S3 Object's Key from Lambda event Args: event (dict): Lambda event object """ record = event['Records'][0] obj_key = record['s3']['object'].get('key') if obj_key: return obj_key else: raise ObjectKeyError('KeyE...
49,939
def country_name_from_code(code:str) -> str: """Return the full country name in English""" # TODO: error handling if code is not found return country_dict[code.upper()]
49,940
def test_delegate_from_class_method(): """Test delegate implemented with a Python class method.""" d = StringDelegate(HelloClass.c_hello) ob = DelegateTest() assert ob.CallStringDelegate(d) == "hello" assert d() == "hello" ob.stringDelegate = d assert ob.CallStringDelegate(ob.stringDelega...
49,941
def test_noop(): """test src code is found properly. """ assert(noop() is None)
49,942
def draw_names(canvas, name_data, lookup_names): """ Given a dict of baby name data and a list of name, plots the historical trend of those names onto the canvas. Input: canvas (Tkinter Canvas): The canvas on which we are drawing. name_data (dict): Dictionary holding baby name data ...
49,943
def import_buffer_to_ast(buf, module_name): """ Import content from buf and return a Python AST.""" return hy_compile(import_buffer_to_hst(buf), module_name)
49,944
def svn_wc_delete(*args): """ svn_wc_delete(char const * path, svn_wc_adm_access_t * adm_access, svn_cancel_func_t cancel_func, svn_wc_notify_func_t notify_func, apr_pool_t pool) -> svn_error_t """ return _wc.svn_wc_delete(*args)
49,945
def magma_dsyevd_m(ngpu, jobz, uplo, n, A, lda, w, work, lwork, iwork, liwork): """ Compute eigenvalues of real symmetric matrix. Multi-GPU, data on host """ uplo = _uplo_conversion[uplo] info = c_int_type() status = _libmagma.magma_dsyevd_m(ngpu, jobz, uplo, n, int(A), lda, ...
49,946
def test_cray_ims_deleted_images_base(cli_runner, rest_mock): """ Test cray ims images base command """ runner, cli, _ = cli_runner result = runner.invoke(cli, ['ims', 'deleted', 'images']) assert result.exit_code == 0 outputs = [ "update", "delete", "deleteall", "de...
49,947
def Base_image_filter(self, param): """ - name: image filter image_filter: input: input.png output: output.png filter: - ModeFilter: 12 - GaussianBlur: 5 - ModeFilter: 12 - GaussianBlur: 1 """ input_filename, filename = inout_fname(pa...
49,948
def deprecated(func): """ A decorator used to mark functions that are deprecated with a warning. """ @functools.wraps(func) def wrapper(*args, **kwargs): # https://stackoverflow.com/questions/2536307/decorators-in-the-python-standard-lib-deprecated-specifically # may not want to turn...
49,949
def queryAnnotations( paths, # type: List[String] startTime=None, # type: Optional[Date] endTime=None, # type: Optional[Date] types=None, # type: Optional[List[String]] ): # type: (...) -> List[Annotation] """Queries user stored annotations from the Tag history system for a set of paths,...
49,950
def has_other_useful_output(content_text): """Returns whether |content_text| has other useful output. Namely, console errors/warnings & alerts/confirms/prompts. """ prefixes = ('CONSOLE ERROR:', 'CONSOLE WARNING:', 'ALERT:', 'CONFIRM:', 'PROMPT:') def is_useful(line): retu...
49,951
def scrape(pagelim, endpoint, term=''): """ Retrieves all pages of the specified URL format up to the page limit. Most of this code is spent on the loop structure to make sure we can automatically get all the pages needed without storing empty data. The latter half of this function i...
49,952
def TransformContainerAnalysisData(image_name, occurrence_filter=None): """Transforms the occurrence data from Container Analysis API.""" occurrences = FetchOccurrencesForResource(image_name, occurrence_filter) analysis_obj = container_analysis_data_util.ContainerAnalysisData(image_name) for occurrence in occur...
49,953
def get_lednet(model_name=None, pretrained=False, root=os.path.join("~", ".torch", "models"), **kwargs): """ Create LEDNet model with specific parameters. Parameters: ---------- model_name : str or None, default None Model name for loading pretra...
49,954
def test_writer_class_fs(): """File System writer is the appropriate class when a protocol isn't present.""" client = Client('/path/to/somewhere') assert client.base == '/path/to/somewhere' assert client.writer_class == FSWriteContent client = Client('file://somewhere') assert client.base =...
49,955
def sb_related_posts(post, num=5): """ cursor.execute("select object_id, count(distinct term_taxonomy_id) as weight from wp_2_term_relationships t inner join wp_2_posts p on p.ID=t.object_id where term_taxonomy_id in (%s) and post_type='post' and post_status='publish' and object_id != %s group by object_id orde...
49,956
def printDictionary(dictionary): """ Prints input dictionary. """ print(json.dumps(dictionary, indent = 4))
49,957
def lock_attr(attr, lock='lock'): """ If lock is 'lock', lock attr and hide it in the CB. This is for removing attributes like translation on control nodes, where we don't want it cluttering the channel box. If lock is "lock_visible", lock attr, but leave it in the CB. This is for attributes we d...
49,958
def cluster_randomly_weigthed(document, prob_coref=0.03): """ Randomly creates a coreferring link between a mention, m2, and any preceding mention, m1. Probability of selecting a closer antecedent is higher, according to a geometric distribution Probability of selecting an antecedent is prob_c...
49,959
def load_ids(queue_item_ids): """ Wrap API search """ print("### Start search process ###") for section in CONFIG: if section == "DEFAULT": continue with open(CONFIG[section]['geojson']) as json_file: geojson_geometry = json.load(json_file) search_requ...
49,960
def getOffset(self,name): """ get the offset """ return [self.xoffset,self.yoffset]
49,961
def to_nbsphinx(s): """Use the sphinx naming style for anchors of headings""" s = s.replace(" ", "-").lower() return "".join(filter(lambda c : c not in "()", s))
49,962
def get_training_data(file_name): """ Read the given training data file or default training data file and return the training data params: training_data_file - string - Training data file path returns: training_data - Datafrmae """ logger.debug("<<<< 'Current Executing Function' >>>>") if fi...
49,963
def isrest(peak): """Determine whether the first 512 bytes are written in reST.""" try: a, b = re.match('^(.+?)\n((?:-|=|#)+)', peak).groups() except (ValueError, AttributeError): return False return len(b) >= len(a)
49,964
def load_raw(stream): """ Load a schism YAML """ # First round to get environmental variables loader = RawLoader(stream) try: data = loader.get_single_data() finally: loader.dispose() stream.seek(0) # Second round with substitution env = {} for key in substitute_...
49,965
def compare_time_stats(grouped, ref_grouped): """Given two nested dictionaries generated by get_dict_from_json, after running calculate_time_stats on both, compare the performance of the given run to a reference run. A string will be returned with instances where there is a significant performance difference...
49,966
def task_name_to_model_class(name: str) -> Tuple[Type[GraphTaskModel], Dict[str, Any]]: """ Map task name to a model class and default hyperparameters for that class. """ task_info = TASK_NAME_TO_DATASET_AND_MODEL_INFO.get(name.lower()) if task_info is None: raise ValueError("Unknown task ty...
49,967
def compute_pairwise_similarities(string_series_1: pd.Series, string_series_2: pd.Series, **kwargs) -> pd.Series: """ Computes the similarity scores between two Series of strings row-wise. :param string_series_1: pandas.Series. The input S...
49,968
def blur(img): """ :param img: the original image :return: img, the blurred image This function make image blurred """ old_image = img blurred = SimpleImage.blank(old_image.width, old_image.height) for y in range(old_image.height): for x in range(old_image.width): cou...
49,969
def delete_all_cache(package): """ Remove cached data, this will delete entire cache folder. """ _delete_macos(package) home, _ = _get_home(package) try: _delete_folder(home) with open(version_path, 'w') as fopen: fopen.write(version) return True except Ba...
49,970
def launch(pipeline, id, revision, command_only, params_in, params_out, save_all, show_hidden, url): """ Launch a pipeline using a web GUI or command line prompts. Uses the pipeline schema file to collect inputs for all available pipeline parameters. Parameter names, descriptions and help text are show...
49,971
def plot_results_classes(results, classes, path): """ Plots the f1 measure of the methods for each class in results :param results: dict A dict containing different methods as keys and for each key an array with accuracy, average prediction and average recall. :param path: string or os.path ...
49,972
def _validator(record_type, ref): """ Create a DataValidator instance. """ if record_type == mds.STATUS_CHANGES: return mds.DataValidator.status_changes(ref=ref) elif record_type == mds.TRIPS: return mds.DataValidator.trips(ref=ref) else: raise ValueError(f"Invalid record...
49,973
def create_gif(pictures: list, watermark: str, user_id: int, private=0) -> BytesIO: """ Creates gif with watermark from list of PIL images and adds it to database. Returns BytesIO object :param pictures: list of PIL.Image objects :param watermark: watermark text, takes from user name ...
49,974
def td3Student(env_fn, actor_critic=td3_core.MLPActorCritic, ac_kwargs=dict(), seed=0, steps_per_epoch=4000, epochs=100, replay_size=int(1e6), gamma=0.99, polyak=0.995, pi_lr=1e-3, q_lr=1e-3, batch_size=100, start_steps=10000, update_after=1000, update_every=50, act_noise=0.1, target_noise=0.2, ...
49,975
def getLogger(logFile='', logLevel='DEBUG', logOutName='api.log', rotateTime='midnight', backupCount=10): """ Get new Logger for logging """ levels = {'FATAL': logging.FATAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO, 'DEBUG'...
49,976
def ret_comb_index(bi_tot, get_indices=False, isotope=None): """ :param bi_tot: :return: """ bi_1 = int(str(bi_tot)[-2:]) bi_2 = int(str(bi_tot)[0:-2]) if get_indices: return (bi_1, bi_2 - 1, isotope) else: return (bi_1, bi_2 - 1)
49,977
def run_list(arg): """ Convert a :class:`~list` to a `RUN` instruction. :param arg: List that represents instruction arguments. :return: Fully-qualified `RUN` instruction. """ indent = len(run_list.instruction_name) + 1 return formatting.list_with_conditional_command_line_breaks(arg, indent...
49,978
def count_loops(G): """ Count the loop edges in a graph. Parameters ---------- G : NetworkX graph """ loops = get_loops(G) return len(loops)
49,979
def plot_prediction(actual, prediction, title='Google Trading vs Prediction', y_label='Price USD', x_label='Trading Days'): """ Plots train, test and prediction :param actual: DataFrame containing actual data :param prediction: DataFrame containing predicted values :param title: Title of the plot ...
49,980
def test_isotope_symbols(): """Tests that SELFIES symbols with isotope specifications are constrained properly. """ reset_alphabet() assert sf.decoder("[13Cexpl][Branch1_1][C][Cl][Branch1_1][C][F]" "[Branch1_1][C][Br][Branch1_1][C][I]") \ == "[13C](Cl)(F)(Br)CI" ...
49,981
async def post_projectversion_toggle_ci(request): """ Toggles the ci enabled flag on a projectversion. --- description: Toggles the ci enabled flag on a projectversion. tags: - ProjectVersions consumes: - application/x-www-form-urlencoded parameters: - name: projectv...
49,982
def execute(env): """Perform pre-stage tasks for running a component. Parameters ---------- env : dict A dict of component parameter values from WMT. """ file_list = [] for k, v in env.items(): if k.startswith('_ingest_') and v != 'Off': file_list.append(v.encode(...
49,983
def edit_item(category, item): """App route function to edit an item.""" # Verify user login. If not, redirect to login page. login_status = None if 'email' in login_session: login_status = True else: flash('Please log in.') return redirect(url_for('home')) # Query databa...
49,984
def sanity_check_gcon(): """Sanity check gcon.""" cmd = gcon_py + " --help" errmsg = gcon_py + " is not installed." execute(cmd=cmd, errmsg=errmsg) return gcon_py
49,985
def make_ddf(view_map, submissionNode, daf_name, make_condor=False, outdir=None): """ Make ddf files, and bonus condor file """ query_template = """PREFIX libraryOntology: <http://jumpgate.caltech.edu/wiki/LibraryOntology#> PREFIX submissionOntology: <http://jumpgate.caltech.edu/wiki/UcscSubmissionOntol...
49,986
def get_Cust_Bookings_Hours(request, *args, **kwargs): """Request Chart Points per Themes""" bookings_H_tmp = requests.get('http://127.0.0.1:5000/customer/bookings/hours').text bookings_Hours_list = json.loads(bookings_H_tmp) bookings_Hours = [ ['Heures', 'Nombre de réservations', {"role": "anno...
49,987
def deprecated_version(filename, expression): """ Summary. Extract program version N-1. Args: :filename (str): Name of file contents searched for N-1 version num. :expression (str): Regex or string which matches deprecated version Returns: exact match, TYPE: str or Non...
49,988
def canCoerceType(typeA, typeB): """Can values of typeA be coerced into typeB?""" import scenic.syntax.veneer as veneer # TODO improve if get_type_origin(typeA) is typing.Union: # only raise an error now if none of the possible types will work; # we'll do more careful checking at runtime return any(canCoerceTy...
49,989
def judo_turnier(): """Show participants for judo turnier.""" participants = Participant.query.filter_by(user_id=current_user.id, event=EVENT_JUDO_TURNIER).all() form = ParticipantDeleteForm(request.form) return render_template('events/judo-turnier.html', ...
49,990
def _yamlfiles(zipfile, has_subdirs=False): """Helper to get a yaml file (according to POLICYD_VALID_EXTS extensions) and the infolist item from a zipfile. If the `has_subdirs` param is True, the the only yaml files that have a directory component are read, and then first part of the directory comp...
49,991
def preprocess_mapper(features, params, lookup_table): """Model-specific preprocessing of features from the dataset.""" features["question_inputs"] = text_utils.build_text_inputs( text=features["question"], length=params["question_length"], lookup_table=lookup_table) features["context_inputs"] ...
49,992
def get_user_playlists(): """Return all of the user's playlists""" logging.info("fetching user playlists") url = "https://api.spotify.com/v1/me/playlists" return get_all_pages(url)
49,993
def test_supported_backends(): """Dummy test, make sure the supported_backends return the desired list.""" assert supported_backends() == [TENSORFLOW, PYTORCH]
49,994
def set_circuit_ic_mrucc(n_qubits, v_n, a_n, c_n, DS, theta_list, ndim1, a2a): """ """ circuit = QuantumCircuit(n_qubits) if DS: circuit = icmr_ucc_singles(circuit,v_n, a_n, c_n, theta_list, 0) circuit = icmr_ucc_doubles(circuit,v_n, a_n, c_n, theta_list, ndim1, a2a) else: c...
49,995
def dct2spatial(image): """ Rearrange DCT image from [H//8, W//8, 64] to [H,W] """ assert image.shape[2] == 64 block_view = (image.shape[0], image.shape[1], 8, 8) image_shape = (image.shape[0] * 8, image.shape[1] * 8) block_permute = 0, 2, 1, 3 result = image.reshape(block_view).transp...
49,996
def theta2rotx(theta: np.ndarray) -> np.ndarray: """ Rx = [[1, 0, 0], [0, c(t), -s(t)], [0, s(t), c(t)]] :param theta: angle(s) in degrees, positive is counterclockwise :return: rotation_matrices """ theta = np.deg2rad(np.asarray(theta).reshape(-1)) rotation_matrices = np...
49,997
def sighandler(signum, unused_frame): """A signal handler that toggles flags about received signals.""" if signum in (signal.SIGTERM, signal.SIGINT): __FLAGS['down'] = True if signum == signal.SIGHUP: __FLAGS['hup'] = True
49,998
def send_post_version_operation(operation, version, token, **kwargs): """ Signal emitter for after a version operation occurs :param operation: Operation constants :param version: Version instance :param token: A unique token for the transaction :param kwargs: """ post_version_operation...
49,999