content
stringlengths
22
815k
id
int64
0
4.91M
def get_bucket_metadata(bucket, user_settings=None, access=ServiceAccount.STORAGE): """ Retrieves metadata about the given bucket. :param str bucket: name of the Google cloud storage bucket :param dict user_settings: optional, A dictionary of settings specifying credentials for appropriate services. ...
29,700
def remove_conjunction(conjunction: str, utterance: str) -> str: """Remove the specified conjunction from the utterance. For example, remove the " and" left behind from extracting "1 hour" and "30 minutes" from "for 1 hour and 30 minutes". Leaving it behind can confuse other intent parsing logic. ...
29,701
def othertitles(hit): """Split a hit.Hit_def that contains multiple titles up, splitting out the hit ids from the titles.""" id_titles = hit.Hit_def.text.split('>') titles = [] for t in id_titles[1:]: fullid, title = t.split(' ', 1) hitid, id = fullid.split('|', 2)[1:3] titles.a...
29,702
def unlock_device(password=None, device=None) -> bool: """ Unlocks a device given a device name and the password :param password: :param device: :return: True is sucess, False if error """ command_input = ["adb", "-s", device, "shell", "input", "text", password] command_submit = ["adb",...
29,703
def close(account_id: str) -> None: """ Closes the account. :param account_id: the account to close :return: Nothing """ logger.info('closing-account', account_id=account_id) with transaction.atomic(): account = Account.objects.get(pk=account_id) account.close() acco...
29,704
def create_from_mne_epochs(list_of_epochs, window_size_samples, window_stride_samples, drop_last_window): """Create WindowsDatasets from mne.Epochs Parameters ---------- list_of_epochs: array-like list of mne.Epochs window_size_samples: int window size ...
29,705
def definstance(name, ty, expr): """ Arguments: - `name`: a string - `ty`: a type of the form ClassName(t1,...,tn) """ root, _ = root_app(root_clause(ty)) if root.info.is_class: class_name = root.name c = defexpr(name, expr, type=ty, unfold=[class_name]) conf.cur...
29,706
def do(*args, **kwargs): """ Function to perform steps defined under ``nornir:actions`` configuration section at: * Minion's configuration * Minion's grains * Minion's pillar data * Master configuration (requires ``pillar_opts`` to be set to True in Minion config file in order to work...
29,707
def read_plaintext_inputs(path: str) -> List[str]: """Read input texts from a plain text file where each line corresponds to one input""" with open(path, 'r', encoding='utf8') as fh: inputs = fh.read().splitlines() print(f"Done loading {len(inputs)} inputs from file '{path}'") return inputs
29,708
def extract_tool_and_dsname_from_name(row): """ Extract Basecall (MB1.6K) into Basecall and MB1.6K, and 1600 three fields :param instr: :return: """ try: toolname, dsname = row['name'].strip().split(' ') dsname = dsname[1:-1] except: # No tag process toolname = row['...
29,709
def pyramid_pooling(inputs, layout='cna', filters=None, kernel_size=1, pool_op='mean', pyramid=(0, 1, 2, 3, 6), flatten=False, name='psp', **kwargs): """ Pyramid Pooling module. """ shape = inputs.get_shape().as_list() data_format = kwargs.get('data_format', 'channels_last') static_...
29,710
def flush(): """Flush out the send buffers.""" _MPI_RANK_ACTOR.flush()
29,711
def df(r, gamma): """ divergence-free function """ eta = soft_threshold(r, gamma) return eta - np.mean(eta != 0) * r
29,712
def main(logging_level: str) -> None: """noisy-moo CLI""" logging_levels = { "debug": logging.DEBUG, "info": logging.INFO, "warning": logging.WARNING, "error": logging.ERROR, "critical": logging.CRITICAL, } logging.basicConfig( format="%(asctime)s [%(level...
29,713
def clip_3d_liang_barsky(zmin, zmax, p0, p1): """Clips the three-dimensional line segment in the canonial view volume by the algorithm of Liang and Barsky. Adapted from James D. Foley, ed., __Computer Graphics: Principles and Practice__ (Reading, Mass. [u.a.]: Addison-Wesley, 1998), 274 as well as h...
29,714
def RunLatencyTest(sending_vm, receiving_vm, use_internal_ip=True): """Run the psping latency test. Uses a TCP request-response time to measure latency. Args: sending_vm: the vm to send the tcp request. receiving_vm: the vm acting as the server. use_internal_ip: whether or not to use the private IP ...
29,715
def get_descriptor_list(stackdriver): """Return a list of all the stackdriver custom metric descriptors.""" type_map = stackdriver.descriptor_manager.fetch_all_custom_descriptors( stackdriver.project) descriptor_list = type_map.values() descriptor_list.sort(compare_descriptor_types) return descriptor_li...
29,716
def dankerize(string: str, upper_case_ratio=0.2) -> str: """ Transform a string to lower case, and randomly set some characters to upper case and return the result. string: the string to dankerize upper_case_ratio: the upper_case/letter ratio """ ret = "" for i in range(len(...
29,717
def distance_constraints_too_complex(wordConstraints): """ Decide if the constraints on the distances between pairs of search terms are too complex, i. e. if there is no single word that all pairs include. If the constraints are too complex and the "distance requirements are strict" flag is set, ...
29,718
def greedy_search(model, decoding_function, initial_ids, initial_memories, int_dtype, float_dtype, max_prediction_length, batch_size, eos_id, do_sample, ...
29,719
def database_mostcited(response: Response, request: Request=Query(None, title=opasConfig.TITLE_REQUEST, description=opasConfig.DESCRIPTION_REQUEST), morethan: int=Query(15, title=opasConfig.TITLE_CITED_MORETHAN, description=opasConfig.DESCRIPTION_CITED_MORETHAN), ...
29,720
def captures_ok(api, cfg, size, utils): """ Returns normally if patterns in captured packets are as expected. """ sender_hardware_addr = [ [0x00, 0x0C, 0x29, 0xE3, 0x53, 0xEA], [0x00, 0x0C, 0x29, 0xE3, 0x54, 0xEA], [0x00, 0x0C, 0x29, 0xE3, 0x55, 0xEA], [0x00, 0x0C, 0x29, ...
29,721
def format_event_leef(event): """Format an event as QRadar / LEEF""" syslog_header = f'<13>1 {event["actionTime"]} {hostname}' leef_header = f'LEEF:2.0|TrinityCyber|PTI|1|{event.pop("id")}|xa6|' fields = dict() fields["devTime"] = event.pop("actionTime") fields[ "devTimeFormat" ] =...
29,722
def _file_path(ctx, val): """Return the path of the given file object. Args: ctx: The context. val: The file object. """ return val.path
29,723
def Mapping_Third(Writelines, ThirdClassDict): """ :param Writelines: 将要写入的apk的method :param ThirdClassDict: 每一个APK对应的第三方的字典 :return: UpDateWritelines """ UpDateWriteLines = [] for l in Writelines: if l.strip() in list(ThirdClassDict.keys()): UpDateWriteLines.extend(Thir...
29,724
def rotate_points_around_origin(points, origin, angle): """ Rotate a 2D array of points counterclockwise by a given angle around a given origin. The angle should be given in degrees. """ angle = angle * np.pi / 180 ox, oy = origin.tolist() new_points = np.copy(points) new_points[:, 0] ...
29,725
def get_names_to_aliases(inp) -> dict: """ Returns pair, - out[0] = dictionary of names to sets of aliases - out[1] = erros when calling names_to_links, i.e., when file-reading @param inp: string vault directory or names_to_links dictionary if string then get_names_to_links method is used ...
29,726
def main(): """ A simple test program to do PFASST runs for the heat equation """ # initialize level parameters level_params = dict() level_params['restol'] = 1E-10 level_params['dt'] = 0.25 # initialize sweeper parameters sweeper_params = dict() sweeper_params['collocation_cla...
29,727
def main(): """Main Func""" print("This is Password Generator.") length = int(input("\nEnter the length of password: ")) pwd = pwd_generator(length) print("Password generated! -> ", pwd) try_decision = input("\nTry again? (y/n): ") if try_decision == "y": main() else: pri...
29,728
def controller_plots(model_dir, ds, ds_eval, groundtruth, prediction, communication): """ :param model_dir: directory containing the trained model :param ds: name of the dataset :param ds_eval: name of the dataset for the evaluation (usually the manual one) :param groundtruth: evidence :param ...
29,729
def length(vec): """ Length of a given vector. If vec is an scalar, its length is 1. Parameters ---------- vec: scalar or arr Input vector Returns ------- length: int Length of vec. If vec is an scalar, its length is 1. ...
29,730
def help_(ctx): """Show this delightful help message and exit.""" click.echo(ctx.parent.get_help())
29,731
def test_fetch_genes_to_hpo_to_disease(hpo_genes_file): """Test fetch resource""" # GIVEN an URL url = scout_requests.HPO_URL.format("genes_to_phenotype.txt") with open(hpo_genes_file, "r") as hpo_file: content = hpo_file.read() responses.add( responses.GET, url, bod...
29,732
def build_eval_infeeds(params): """Create the TPU infeed ops.""" eval_size = get_eval_size(params) num_eval_steps = eval_size // params.eval_batch_size dev_assign = params.device_assignment host_to_tpus = {} for replica_id in range(params.num_replicas): host_device = dev_assign.host_device(replica=rep...
29,733
def add_auth(opts): """Add authorization entry. If all options are None, then use interactive 'wizard.' """ conn = opts.connection if not conn: _stderr.write( "VOLTTRON is not running. This command " "requires VOLTTRON platform to be running\n" ) retu...
29,734
def save_training_config(args_dict: Dict[str, Any], model_out_path: Path): """Saves training_config to a file. :param args_dict: dictionary with all training parameters. :param model_out_path: where to store training_config.json. """ _, training_args = load_config(schema_version=CURRENT_SCHEMA_VERS...
29,735
def get_featured_parks(request): """ Returns recommended parks as JSON """ featured_parks = Park.objects.filter(featured=True).prefetch_related('images') response = { 'featured_parks': [{'id': n.pk, 'name': n.name, 'image': n.thumbnail} for n in featured_parks] } return HttpResponse(json...
29,736
def plot_accuracy(raw_all_grids_df, option=None): """ Input: raw condition df facets: None, 'subjects', Output: figure(s) that visualize the difference in accuracy btw. el and pl """ # Rearrange columns for better readability in temporal order of the experiment condition...
29,737
def locate_references(path: Union[Path, str], encoding: str = DEFAULT_ENCODING): """Locates add_reference in path. It looks recursively for add_reference markers, taking note of the module, line short_purpose and actual reference string. Returns None """ if os.path.isdir(path): ...
29,738
def make_data_output(structures: Sequence[Artefact[bytes]]) -> Artefact[list[Any]]: """Take xyz structure from xtb and parse them to a list of dicts.""" def to_dict(xyz: bytes) -> dict[str, Any]: as_str = xyz.decode().strip() energy = float(as_str.splitlines()[1].split()[1]) return {"st...
29,739
def total_angular_momentum(particles): """ Returns the total angular momentum of the particles set. >>> from amuse.datamodel import Particles >>> particles = Particles(2) >>> particles.x = [-1.0, 1.0] | units.m >>> particles.y = [0.0, 0.0] | units.m >>> particles.z = [0.0, 0.0] | units.m ...
29,740
def svn_repos_get_logs3(*args): """ svn_repos_get_logs3(svn_repos_t repos, apr_array_header_t paths, svn_revnum_t start, svn_revnum_t end, int limit, svn_boolean_t discover_changed_paths, svn_boolean_t strict_node_history, svn_repos_authz_func_t authz_read_func, svn_log_m...
29,741
def insertTimerOnOutput (signal, type): """ Plug the signal sout of the return entity instead of `signal` to input signal to enable the timer. - param signal an output signal. - return an Timer entity. """ Timer = getTimerType (type) timer = Timer ("timer_of_" + signal.name) plug(sig...
29,742
def anomaly_metrics(contended_task_id: TaskId, contending_task_ids: List[TaskId]): """Helper method to create metric based on anomaly. uuid is used if provided. """ metrics = [] for task_id in contending_task_ids: uuid = _create_uuid_from_tasks_ids(contending_task_ids + [contended_task_id]) ...
29,743
def alarm(): """.""" if request.method == 'POST': response = {'message': 'POST Accepted'} logging.info('alarm POSTED!') data = request.data logging.info(data) string = json.dumps(data) producer.send('SIP-alarms', string.encode()) return response return...
29,744
def train_net(solver_prototxt, roidb, output_dir, pretrained_model=None, detection_pretrained_model =None, max_iters=40000): """Train a TD-CNN network.""" roidb = filter_roidb(roidb) sw = SolverWrapper(solver_prototxt, roidb, output_dir, pretrained_model=pretrained_model, detection_pretrained...
29,745
def get_druminst_order(x): """helper function to determine order of drum instruments relies on standard sequence defined in settings """ y = shared.get_inst_name(x + shared.octave_length + shared.note2drums) return shared.standard_printseq.index(y)
29,746
def polyTransfer(*args, **kwargs): """ Transfer information from one polygonal object to another one. Both objects must have identical topology, that is same vertex, edge, and face numbering. The flags specify which of the vertices, UV sets or vertex colors will be copied. Flags: - alternateO...
29,747
def scalbnf(x, y): """ See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_scalbnf.html :param x: Argument. :type x: float32 :param y: Argument. :type y: int32 :rtype: float32 """
29,748
def find_nearest_idx(array, value): """ Find index of value nearest to value in an array :param np.ndarray array: Array of values in which to look :param float value: Value for which the index of the closest value in `array` is desired. :rtype: int :return: The index of the item in `arr...
29,749
def hard_tanh(x): """Hard tanh function Arguments: x: Input value hard_tanh(x) = {-1, for x < -2, tanh(x), for x > -2 and x < 2 1, for x > 2 } returns value according to hard tanh function """ return tf.maximum( tf...
29,750
async def get_publications(publication_id: str, embedded: bool = False): """ Given a Publication ID, get the Publication record from metadata store. """ publication = await get_publication(publication_id, embedded) return publication
29,751
def RandomNormal(inp): """ Random normally distributed weight initialization. """ return np.random.randn(inp)
29,752
async def notes_active(svd): """ For .notes command, list all of the notes saved in a chat. """ try: from userbot.modules.sql_helper.notes_sql import get_notes except AttributeError: await svd.edit("`Running on Non-SQL mode!`") return message = "`There are no saved notes in this ...
29,753
def get_transceiver_description(sfp_type, if_alias): """ :param sfp_type: SFP type of transceiver :param if_alias: Port alias name :return: Transceiver decsription """ return "{} for {}".format(sfp_type, if_alias)
29,754
def find_contiguous_set(target_sum: int, values: list[int]) -> list[int]: """Returns set of at least 2 contiguous values that add to target sum.""" i = 0 set_ = [] sum_ = 0 while sum_ <= target_sum: sum_ += values[i] set_.append(values[i]) if sum_ == target_sum and len(set...
29,755
def disconnect(filename="cache.json"): """ Connect to the local cache, so no internet connection is required. :returns: void """ global _CONNECTED, _CACHE try: with open(filename, 'r') as f: _CACHE = _recursively_convert_unicode_to_str(json.load(f))['data'] except FileNot...
29,756
def init(args): """ Initialise a new repo in your pyhome """ # Make sure repo dir exists if not os.path.exists(settings.PYHOME_REPO): os.makedirs(settings.PYHOME_REPO) print('Initialising repo ...') git.init(settings.PYHOME_REPO, args.name)
29,757
def nesoni_report_to_JSON(reportified): """ Convert a nesoni nway.any file that has been reportified to JSON See: tables.rst for info on what is stored in RethinkDB :param reportified: the reportified nway.any file (been through nway_reportify()). This is essentially a list of ...
29,758
def DeferredLightInfoEnd(builder): """This method is deprecated. Please switch to End.""" return End(builder)
29,759
def qiita_get_config(): """設定ファイルを読む.""" config = configparser.ConfigParser() path = Path(os.getenv('HOME'), '.qiita.ini') config.read_file(open(path)) return config
29,760
def move_character(character: dict, direction_index=None, available_directions=None) -> tuple: """ Change character's coordinates. :param character: a dictionary :param direction_index: a non-negative integer, optional :param available_directions: a list of strings, optional :precondition: char...
29,761
def expandednodeid_to_str(exnode): """SOPC_ExpandedNodeId or SOPC_ExpandedNodeId* to its str representation in the OPC-UA XML syntax.""" a = '' if exnode.ServerIndex: a += 'srv={};'.format(exnode.ServerIndex) nsu = string_to_str(ffi.addressof(exnode.NamespaceUri)) if nsu: a += 'nsu={...
29,762
def scrap_insta_description(inst) -> str: """ Scrap description from instagram account HTML. """ description = inst.body.div.section.main.div.header.section.find_all( 'div')[4].span.get_text() return description
29,763
def merge_by_sim(track_sim_list, track_data_dic, track_list, reid_th): """ Merge by sim. Ref: https://stackoverflow.com/questions/30089675/clustering-cosine-similarity-matrix """ print('start clustering') merge_start_time = time.time() cost_matrix = get_cost_matrix(track_sim_list, track_dat...
29,764
def get_ros_hostname(): """ Try to get ROS_HOSTNAME environment variable. returns: a ROS compatible hostname, or None. """ ros_hostname = os.environ.get('ROS_HOSTNAME') return ros_hostname if is_legal_name(ros_hostname) else None
29,765
def cycle(*args, **kargs): """ Returns the next cycle of the given list Everytime ``cycle`` is called, the value returned will be the next item in the list passed to it. This list is reset on every request, but can also be reset by calling ``reset_cycle()``. You may specify the list as...
29,766
def calc_rmsd(struct1, struct2): """ Basic rmsd calculator for molecules and molecular clusters. """ geo1 = struct1.get_geo_array() ele1 = struct1.elements geo2 = struct2.get_geo_array() ele2 = struct2.elements dist = cdist(geo1,geo2) idx1,idx2 = linear_sum_assignmen...
29,767
def validate_flat_dimension(d): """Return strue if a 'key:value' dimension is valid.""" key, _, val = d.partition(':') return validate_dimension_value(val) and validate_dimension_key(key)
29,768
def file_size(f): """ Returns size of file in bytes. """ if isinstance(f, (six.string_types, six.text_type)): return os.path.getsize(f) else: cur = f.tell() f.seek(0, 2) size = f.tell() f.seek(cur) return size
29,769
def _check_fill_arg(kwargs): """ Check if kwargs contains key ``fill``. """ assert "fill" in kwargs, "Need to have fill in kwargs."
29,770
def __get_from_imports(import_tuples): """ Returns import names and fromlist import_tuples are specified as (name, fromlist, ispackage) """ from_imports = [(tup[0], tup[1]) for tup in import_tuples if tup[1] is not None and len(tup[1]) > 0] return from_imports
29,771
def test_no_error_correction_with_two_logical_qubits(): """Checks that an error is thrown when a circuit is set up for extra ancilla for two logical qubits""" with raises(ValueError, match = "Can't set up extra ancilla with two logical qubits due to memory size restrictions"): SteaneCodeLogicalQubit(2, ...
29,772
def logging(on : bool, *, dest : TextIO = sys.stderr) -> None: """Whether to log received and transmitted JSON.""" __get_designated_connection().logging(on=on,dest=dest)
29,773
def change_dt_utc_to_local(dt): """ change UTC date time to local time zone Europe/Paris """ return convert_utctime_to_timezone(dt,'%Y%m%dT%H%M%SZ','Europe/Paris','%Y%m%dT%H%M%S')
29,774
def sarimax_ACO_PDQ_search(endo_var, exog_var_matrix, PDQS, searchSpace, options_ACO, low_memory=False, verbose=False): """ Searchs SARIMAX PDQ parameters. endo_var: is the principal variable. exog_var_matrix: is the matrix of exogenous variables. PDQS: lis...
29,775
def convert_vue_i18n_format(locale: str, po_content: Any) -> str: """ done: will markdown be parsed to html in this method? Or should we do that on the fly, everywhere... It seems the logical place will be to parse it here. Otherwise the rest of the application becomes more complex. Using ma...
29,776
def p_on(p): """ on : ON columnlist """ p[0] = p[2]
29,777
def get_index(x, value, closest=True): """Get the index of an array that corresponds to a given value. If closest is true, get the index of the value closest to the value entered. """ if closest: index = np.abs(np.array(x) - value).argsort()[0] else: index = list(x).index...
29,778
def process_spawn(window, args): """ Spawns a child process with its stdin/out/err wired to a PTY in `window`. `args` should be a list where the first item is the executable and the remaining will be passed to it as command line arguments. Returns a process object. """ return (yield Trap.PR...
29,779
def insertTaskParams(taskParams, verbose=False, properErrorCode=False, parent_tid=None): """Insert task parameters args: taskParams: a dictionary of task parameters verbose: True to see verbose messages properErrorCode: True to get a detailed error code parent_tid...
29,780
def pref_infos(): """ to update user infos """ form = UserParametersForm() # print current_user if request.method == 'POST' : print log_cis.info("updating an user - POST \n") # for debugging purposes for f_field in form : log_cis.info( "form name : %s / form data : %s ", f_field.name, f_field....
29,781
async def test_missing_optional_config(hass, calls): """Test: missing optional template is ok.""" with assert_setup_component(1, "template"): assert await setup.async_setup_component( hass, "template", { "template": { "select": { ...
29,782
def tree_cc(flag, width, mbl='-', xmin='-', xmax='-', ymin='-', ymax='-', logpath=None): """ | Phase unwrapping tree generation with low correlation search (modified ARW algorithm) | Copyright 2014, Gamma Remote Sensing, v2.9 20-Jan-2014 clw/uw Parameters ---------- flag: (input) ph...
29,783
def read_domains(file_name): """ 读取域名存储文件,获取要探测的域名,以及提取出主域名 注意:若是不符合规范的域名,则丢弃 """ domains = [] main_domains = [] no_fetch_extract = tldextract.TLDExtract(suffix_list_urls=None) file_path = './unverified_domain_data/' with open(file_path+file_name,'r') as fp: for d in fp.readl...
29,784
def collectUserInput(): """ Collects user input from console and verifies it is a letter before proceeding """ user_input = input(MSG_START).lower() while user_input != 'q': initGame(user_input) user_input = input(MSG_START).lower() print(MSG_THANKS)
29,785
def determine_last_contact_incomplete(end_time_skyfield, events, times, antenna): """ gibt letzten Kontakt vervollständigt und Anzahl der an events in unvollständiger Folge zurück :param end_time_skyfield: skyfield time :param events: array of int :param times: array of skyfield times :param ant...
29,786
def lam_est(data, J, B, Q, L = 3, paras = [3, 20], n_trees = 200, include_reward = 0, fixed_state_comp = None, method = "QRF"): """ construct the pointwise cov lam (for both test stat and c.v.), by combine the two parts (estimated and observed) Returns ------- lam: (Q-1)-len list of fo...
29,787
def cli(ctx, **kwargs): """A command-line tool for non-regression testing of RESTful APIs. Helps you get better REST! """ ctx.obj = ResortOptions(**kwargs) daiquiri.setup(program_name=constants.APP_NAME, level=ctx.obj.loglevel)
29,788
def func(x, kw=3.0): """[summary] Args: x ([type]): [description] Raises: Exception: [description] """
29,789
def read_training_data(rootpath): """ Function for reading the images for training. :param rootpath: path to the traffic sign data :return: list of images, list of corresponding image information: width, height, class, track """ images = [] # images img_info = [] # cor...
29,790
def initialize_all(y0, t0, t1, n): """ An initialization routine for the different ODE solving methods in the lab. This initializes Y, T, and h. """ if isinstance(y0, np.ndarray): Y = np.empty((n, y.size)).squeeze() else: Y = np.empty(n) # print y0 # print Y Y[0] = y0 T = np.li...
29,791
def _sequence_event(values, length, verb): """Returns sequence (finite product) event. Args: values: List of values to sample from. length: Length of the sequence to generate. verb: Verb in infinitive form. Returns: Instance of `probability.FiniteProductEvent`, together with a text descripti...
29,792
def ndarrayToQImage(img): """ convert numpy array image to QImage """ if img.dtype != 'uint8': raise ValueError('Only support 8U data') if img.dim == 3: t = QtGui.QImage.Format_RGB888 elif img.dim == 2: t = QtGui.QImage.Format_Grayscale8 else: raise ValueError('Only ...
29,793
def create_release_html(filename='index.html'): """ Create a html file with the links to the sphinx and doxygen documentations of the supported releases. Parameters: filename (str): The name the html file. """ page = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3....
29,794
def object_hook(dct, compile_re=False, ensure_tzinfo=True, encoding=None): """ Object hook used by hoplite_loads. This object hook can encode the dictionary in the right text format. For example, json.loads by default will decode '{'hey':'hey'}' into {u'hey':u'hey'} rather than {'hey':'hey'}. If en...
29,795
def grade_submissions(course_name, assignment_name): """Grade all submissions for a particular assignment. A .zip archive should be uploaded as part of the POST request to this endpoint. The archive should contain a single directory 'Submissions', which should contain a directory for each student's submission....
29,796
def print_costs(costs, start): """ Print costs of all but the unused zeroth vertex and the start vertex. Vertices that are unreachable have infinite cost, but we print -1 instead. """ print(*((-1 if cost is None else cost) for cost in costs[1:start] + costs[(start + 1):]))
29,797
def scrape_sp500_tickers(): """Scrape the wikipedia page for the latest list of sp500 companies Returns: [pickle]: [list of sp500 companies] """ #set get file to look at wikipedia's list of sp500 companies resp = requests.get('http://en.wikipedia.org/wiki/List_of_S%26P_500_companies') s...
29,798
def get_top_k_recs(user_reps, item_reps, k): """ For each user compute the `n` topmost-relevant items Args: user_reps (dict): representations for all `m` unique users item_reps (:obj:`np.array`): (n, d) `d` latent features for all `n` items k (int): no. of most relevant items R...
29,799