content
stringlengths
22
815k
id
int64
0
4.91M
def test_delayed_command_order(): """ delayed commands should be sorted by delay time """ null = lambda: None delays = [random.randint(0, 99) for x in range(5)] cmds = sorted([ schedule.DelayedCommand.after(delay, null) for delay in delays ]) assert [c.delay.seconds for c in cmds] == sorted(delays)
21,300
def get_gdb(chip_name=None, gdb_path=None, log_level=None, log_stream_handler=None, log_file_handler=None, log_gdb_proc_file=None, remote_target=None, remote_address=None, remote_port=None, **kwargs): """ set to != N...
21,301
def parse_source_gpx_file(inp_path, source): """Parse a GPX file having the following structure: <gpx xmlns="http://www.topografix.com/GPX/1/1" xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" creator="Suunto app" version="1.1" xsi:sch...
21,302
def check(func: Callable[..., Awaitable[Callable[[CommandContext], Awaitable[bool]]]]) -> Check: """ A decorator which creates a check from a function. """ return Check(func)
21,303
def service_c(request): """ Renders the service chair page with service submissions """ events = ServiceEvent.objects.filter(semester=get_semester()) submissions_pending = ServiceSubmission.objects.filter(semester=get_semester(), status='0').order_by("date") submissions_submitted = ServiceSubmission.ob...
21,304
def get_tank_history(request, tankid): """ Returns a response listing the device history for each tank. """ # Sanitize tankid tankid = int(tankid) # This query is too complex to be worth constructing in ORM, so just use raw SQL. cursor = connection.cursor() cursor.execute("""\ SE...
21,305
def get_absolute_module(obj): """ Get the abolulte path to the module for the given object. e.g. assert get_absolute_module(get_absolute_module) == 'artemis.general.should_be_builtins' :param obj: A python module, class, method, function, traceback, frame, or code object :return: A string repr...
21,306
def parse_c45(file_base, rootdir='.'): """ Returns an ExampleSet from the C4.5 formatted data """ schema_name = file_base + NAMES_EXT data_name = file_base + DATA_EXT schema_file = find_file(schema_name, rootdir) if schema_file is None: raise ValueError('Schema file not found') ...
21,307
def to_numpy(tensor: torch.Tensor): """ Convert a PyTorch Tensor to a Numpy Array. """ if tensor is None: return tensor if tensor.is_quantized: tensor = tensor.dequantize() return tensor.cpu().detach().contiguous().numpy()
21,308
def initialize_flask_sqlathanor(db): """Initialize **SQLAthanor** contents on a `Flask-SQLAlchemy`_ instance. :param db: The :class:`flask_sqlalchemy.SQLAlchemy <flask_sqlalchemy:flask_sqlalchemy.SQLAlchemy>` instance. :type db: :class:`flask_sqlalchemy.SQLAlchemy <flask_sqlalchemy:flask_sqlalc...
21,309
def add_vcf_header( vcf_reader ): """ Function to add a new field to the vcf header Input: A vcf reader object Return: The vcf reader object with new headers added """ # Metadata vcf_reader.metadata['SMuRFCmd'] = [get_command_line()] # Formats vcf_reader.formats['VAF'] = pyvcf.parse...
21,310
def get_seats_percent(election_data): """ This function takes a lists of lists as and argument, with each list representing a party's election results, and returns a tuple with the percentage of Bundestag seats won by various political affiliations. Parameters: election_data (list): A list of l...
21,311
def write(filename, data): """ Pickles a file and writes it to the cache. Keyword Arguments: - filename: name of the file to write to - data: object to cache """ if _log_actions: cprint('Writing to cache: "{}"'.format(filename), 'green') joblib.dump(data, join(_cache_path, filen...
21,312
def get_player_gamelog(player_id, season, season_type='Regular Season', timeout=30): """ Coleta de histórico departidas de um determinado jogador em uma determinada temporada, considerando ainda um tipo específico de temporada (pré-season, temporada regular ou playoffs). Parâmetros --------...
21,313
def unbound_text_to_html5(text, language=None): """ Converts the provided text to HTML5 custom data attributes. Usage: {{text|unbound_text_to_html5:"Greek"}} """ # If the language is English, then don't bother doing anything if language is not None and language.lower() == ...
21,314
def sort_points(points): """Sorts points first by argument, then by modulus. Parameters ---------- points : array_like (n_points, 3) The points to be sorted: (x, y, intensity) Returns ------- points_sorted : :class:`numpy.ndarray` (n_points, 3) The sorted po...
21,315
def get_pairs(scores): """ Returns pairs of indexes where the first value in the pair has a higher score than the second value in the pair. Parameters ---------- scores : list of int Contain a list of numbers Returns ------- query_pair : list of pairs This contains a list of pairs of indexes in ...
21,316
def make(): """Make a new migration. Returns: Response: json status message """ response = None try: with capture_print(escape=True) as content: current_app.config.get('container').make('migrator').make(request.form['name']) response = {'message': content.get_te...
21,317
def find_files(args, client): """ Get a list of all the objects to process""" objects = [] continuation_token = 'UNSET' while continuation_token: if continuation_token == 'UNSET': object_list = client.list_objects_v2(Bucket=args['bucket'],Prefix=args['prefix']) else: ...
21,318
def are_dirs_equal( dir1: Union[str, os.PathLike], dir2: Union[str, os.PathLike], ignore: Optional[List[str]] = None, ) -> bool: """ Compare the content of two directories, recursively. :param dir1: the left operand. :param dir2: the right operand. :param ignore: is a list of names to i...
21,319
def writeCSV(info, resultFile): """ Write info line to CSV :param info: :return: """ try: with codecs.open(resultFile, 'a', encoding='utf8') as fh_results: # Print every field from the field list to the output file for field_pretty in CSV_FIELD_ORDER: ...
21,320
def generate_hmac(str_to_sign, secret): """Signs the specified string using the specified secret. Args: str_to_sign : string, the string to sign secret : string, the secret used to sign Returns: signed_message : string, the signed str_to_sign """ message = str_to_sign....
21,321
def interpolate_scores(coords: np.array, scores: np.array, coord_range: tuple, step: float = 0.001) -> np.array: """ Given a coord_range and values for specific coords - interpolate to the rest of the grid Args: coords: array of lons and lats of points that their values are known scores: arr...
21,322
def remove_blank_from_dict(data): """Optimise data from default outputted dictionary""" if isinstance(data, dict): return dict( (key, remove_blank_from_dict(value)) for key, value in data.items() if is_not_blank(value) and is_not_blank(remove_blank_from_dict(value)) ...
21,323
def upload_to_database( database_secrets_manager_arn: str, user_mapping: List[Dict] ) -> str: """Uploads data from disk to an RDS postgres instance. Uses the provided user_mapping to replace the user subs of data in the local file with the user subs of the newly created users in cognito.""" with ope...
21,324
def new_client( dockerd_url=None, tls=False, tls_verify=False, cert_path=None, timeout=None, ): """ Return a newly configured Docker client. """ _dockerd_url = dockerd_url if not _dockerd_url: _dockerd_url = os.getenv('DOCKER_HOST', DOCKER_DEFAULT_DOCK...
21,325
def merge_mosaic_images(mosaic_dict, mosaic_images, orig_images, Y_orig=None): """ Merge the list of mosaic images with all original images. Args: mosaic_dict: Dictionary specifying how mosaic images were created, returned from make_mosaic mosaic_images: List of all mosaic images returned from ...
21,326
def plot_representation_size_time( representation_size_results, include_cis=True): """Plot the cross-validation time values from the output of `representation_size_experiments`""" kwargs = { 'metric_name': 'Cross-validation time (in secs.)', 'metric_mean_name': 'Mean cross-validation...
21,327
def show2D(dd, impixel=None, im=None, fig=101, verbose=1, dy=None, sigma=None, colorbar=False, title=None, midx=2, units=None): """ Show result of a 2D scan Args: dd (DataSet) impixel (array or None) im (array or None) """ if dd is None: return None extent, g0, g1,...
21,328
def get_job(api_key, jq_id): """ Fetch a job and its status :param api_key: user id of the client :param jq_id: job queue id :return: job queue id """ if Auth.verify_auth_key(api_key): if Auth.verify_job(api_key, jq_id): return trigger.get_job(jq_id) return abort(400)
21,329
def show_dnp_properties(radical, mwFrequency, dnpNucleus): """Calculate DNP Properties Currently only implemented for liquid state experiments Args: radical: Radical name, see mrProperties.py mwFrequency: Microwave frequency in (Hz) dnpNucleus: Nucleus for DNP-NMR exp...
21,330
async def test_options(hass): """Test updating options.""" entry = MockConfigEntry( domain=transmission.DOMAIN, title=CONF_NAME, data=MOCK_ENTRY, options={CONF_SCAN_INTERVAL: DEFAULT_SCAN_INTERVAL}, ) flow = init_config_flow(hass) options_flow = flow.async_get_options...
21,331
def test_auth_check_returns_user_stt(api_client, user): """If user is authenticated auth_check should return user data.""" api_client.login(username=user.username, password="test_password") serializer = UserProfileSerializer(user) response = api_client.get(reverse("authorization-check")) assert resp...
21,332
def contour_to_valid(cnt, image_shape): """Convert rect to xys, i.e., eight points The `image_shape` is used to to make sure all points return are valid, i.e., within image area """ # rect = cv2.minAreaRect(cnt) if len(cnt.shape) != 3: assert 1 < 0 rect = cnt.reshape([cnt.shape[0], cnt.s...
21,333
def test_verify_date(): """Verify date works and also an invalid case is tested.""" valid_dates = "2022-01-12" invalid_dates = "2022-13-32" assert verify_date(valid_dates) == valid_dates with pytest.raises(InvalidDateError) as excinfo: verify_date(invalid_dates) assert "YYYY-MM-DD" in st...
21,334
def search(datafile, query, bool_operator): """ Queries on a set of documents. :param datafile: The location of the datafile as a pathlib.Path :param query: the query text :param bool_operator: the operator. Must be one of [OR, AND] :return: the list of indexes matching the search criteria ...
21,335
def recurse_structures( structure: Component, ignore_components_prefix: Optional[List[str]] = None, ignore_functions_prefix: Optional[List[str]] = None, ) -> DictConfig: """Recurse over structures""" ignore_functions_prefix = ignore_functions_prefix or [] ignore_components_prefix = ignore_compo...
21,336
def compute_dti(fname_in, fname_bvals, fname_bvecs, prefix, method, evecs, file_mask): """ Compute DTI. :param fname_in: input 4d file. :param bvals: bvals txt file :param bvecs: bvecs txt file :param prefix: output prefix. Example: "dti_" :param method: algo for computing dti :param eve...
21,337
def solve( netlist=None, parameter_values=None, experiment=None, I_init=1.0, htc=None, initial_soc=0.5, nproc=12, output_variables=None, ): """ Solves a pack simulation Parameters ---------- netlist : pandas.DataFrame A netlist of circuit elements with format...
21,338
def global_node_entropy(data, dx=3, dy=1, taux=1, tauy=1, overlapping=True, connections="all", tie_precision=None): """ Calculates global node entropy\\ [#pessa2019]_\\ :sup:`,`\\ [#McCullough]_ for an ordinal network obtained from data. (Assumes directed and weighted edges). Parameters ---------- ...
21,339
def get_cert(certificate): """ Return the data of the certificate :returns: the certificate file contents """ cert_file = "{}/certs/{}".format(snapdata_path, certificate) with open(cert_file) as fp: cert = fp.read() return cert
21,340
def model(data, ix_to_char, char_to_ix, num_iterations = 35000, n_a = 50, dino_names = 7, vocab_size = 27): """ Trains the model and generates dinosaur names. Arguments: data -- text corpus ix_to_char -- dictionary that maps the index to a character char_to_ix -- dictionary that maps a characte...
21,341
def random_choice(gene): """ Randomly select a object, such as strings, from a list. Gene must have defined `choices` list. Args: gene (Gene): A gene with a set `choices` list. Returns: object: Selected choice. """ if not 'choices' in gene.__dict__: raise KeyError("'cho...
21,342
def get_actor(payload: PayloadJSON, actor_id: int) -> ResourceJSON: """Return an actor by actor_id""" actor = ActorModel.find_by_id(actor_id) if actor is None: abort(404) return jsonify({"success": True, "actor": actor.json()},)
21,343
def check_if_punctuations(word: str) -> bool: """Returns ``True`` if ``word`` is just a sequence of punctuations.""" for c in word: if c not in string.punctuation: return False return True
21,344
def calculate_sigma_points(states, flat_covs, scaling_factor, out, square_root_filters): """Calculate the array of sigma_points for the unscented transform. Args: states (np.ndarray): numpy array of (nind, nemf, nfac) flat_covs (np.ndarray): numpy array of (nind * nem...
21,345
def normalize_text(string, remove_stopwords=False, stem_words=False): """ Remove punctuation, parentheses, question marks, etc. """ strip_special_chars = re.compile("[^A-Za-z0-9 ]+") string = string.lower() string = string.replace("<br />", " ") string = string.replace(r"(\().*(\))|([^a-zA-Z...
21,346
def get_new_codes(): """ Return New Codes and Refresh DB""" db = dataset.connect(database_url) new_codes = get_code() table = db['promo'] """ Get New Codes""" new = {} for key, value in new_codes.items(): if table.find_one(promo=key) is None: new[key] = [new_codes[key...
21,347
def process_bulk_add_ip(request, formdict): """ Performs the bulk add of ips by parsing the request data. Batches some data into a cache object for performance by reducing large amounts of single database queries. :param request: Django request. :type request: :class:`django.http.HttpRequest` ...
21,348
def test_list_zones_no_search_first_page(list_zone_context, shared_zone_test_context): """ Test that the first page of listing zones returns correctly when no name filter is provided """ result = shared_zone_test_context.list_zones_client.list_zones(name_filter=f"*{shared_zone_test_context.partition_id}...
21,349
def gen_public_e(lambda_: int) -> int: """ Generates decrecingly smaller sequence of bytes and converts them to integer until one satisfies > lambda Continues with half the ammount of necesary bytes decreasing by one integer until gcd(candidate, lambda) == 1. """ bytes_ = 1028 + 1 candidat...
21,350
def lazy(maybe_callable: Union[T, Callable[[], T]]) -> T: """ Call and return a value if callable else return it. >>> lazy(42) 42 >>> lazy(lambda: 42) 42 """ if callable(maybe_callable): return maybe_callable() return maybe_callable
21,351
def basic_demo(): """基础示例""" tree = ET.ElementTree(file="./menu.xml") root = tree.getroot() # Element有标签和属性字典 print(root.tag) print(root.attrib) # 迭代根节点得到子节点 for child in root: print(child.tag, child.attrib) # 访问嵌套的子级 print(root[0][1].text)
21,352
def _git_diff(staged_or_modified: bool, extension: str) -> List[str]: """ Args: extension: the extension of files considered, such as "py" or "ml" staged_or_modified (bool) Whether to consider staged files (True) or modified ones (False) Returns: A list of r...
21,353
def shuffle_list(*ls): """ shuffle multiple list at the same time :param ls: :return: """ from random import shuffle l = list(zip(*ls)) shuffle(l) return zip(*l)
21,354
def cancer_variants(institute_id, case_name): """Show cancer variants overview.""" data = controllers.cancer_variants(store, request.args, institute_id, case_name) return data
21,355
def test_anything_call(b): """Mathing anything should always return True.""" result = anything(b) assert result is True
21,356
def _get_ec2_on_demand_prices(region_name: str) -> Iterable[CloudInstanceType]: """ Returns a dataframe with columns instance_type, memory_gb, logical_cpu, and price where price is the on-demand price """ # All comments about the pricing API are based on # https://www.sentiatechblog.com/using-t...
21,357
def EnumerateInputs(inputs): """Emumerates binary files in the provided paths.""" for current_input in inputs: components = current_input.split(':', 2) entry = components[0] pattern = re.compile(components[1]) if os.path.isdir(entry): for root, unused_subdirs, files in os.walk(entry): ...
21,358
def nodes(G): """Returns an iterator over the graph nodes.""" return G.nodes()
21,359
def import_all(directory): """ Execute 'from (directory) import (all files except "all.py")'. """ try: exec('import ' + directory) import_files = eval(directory + ".__all__") for import_file in import_files: if import_file != "all": exec('import ' + d...
21,360
def cyclePosition(image: np.ndarray, startPosition: position) -> Union[position, bool]: """ :param image: numpy image array :param startPosition: from where to go to Tuple (x,y) :return: newPosition (x,y), or false if new coords would fall out of bounds """ if not imageWrapper.boundsChecker(imag...
21,361
def get_image(file_name): """retrieves an image from a file and returns it as an np array of pixels""" image_array = [] file_name = os.path.abspath(file_name) img = Image.open(file_name) img = img.convert("RGB") img = img.resize((image_size, image_size)) in_data = np.asarray(img) image_a...
21,362
def context_to_ingestion_params(context): """extract the ingestion task params from job/serving context""" featureset_uri = context.get_param("featureset") featureset = context.get_store_resource(featureset_uri) infer_options = context.get_param("infer_options", InferOptions.Null) source = context...
21,363
def bining_for_calibration(pSigma_cal_ordered_, minL_sigma, maxL_sigma, Er_vect_cal_orderedSigma_, bins, coverage_percentile): """ Bin the values of the standard deviations observed during inference and estimate a specified coverage percentile in...
21,364
def add_user(request): """注册用户""" info = {} tpl_name = 'user/add_user.html' if request.method == 'POST': # 保存用户提交数据 nickname = request.POST.get('nickname') if User.objects.filter(nickname__exact=nickname).exists(): # "昵称" 存在 info = {'error':'"昵称"存在'} ...
21,365
def process_input(input_string, max_depth): """ Clean up the input, convert it to an array and compute the longest array, per feature type. """ # remove the quotes and extra spaces from the input string input_string = input_string.replace('"', '').replace(', ', ',').strip() # convert the s...
21,366
def generate_new_shape() -> tuple[int, list[int], list[int]]: """Generate new shape #0: hot_cell_y = [0,1,2,3] hot_cell_x = [5,5,5,5] X X X X #1: hot_cell_y = [0,0,0,0] hot_cell_x = [3,4,5,6] XXXX #2: hot_ce...
21,367
def get_process_list(process): """Analyse the process description and return the Actinia process chain and the name of the processing result :param process: The process description :return: (output_names, actinia_process_list) """ input_names, process_list = analyse_process_graph(process) outp...
21,368
def createAES(key, IV, implList=None): """Create a new AES object. :type key: str :param key: A 16, 24, or 32 byte string. :type IV: str :param IV: A 16 byte string :rtype: tlslite.utils.AES :returns: An AES object. """ if implList is None: implList = ["openssl", "pycrypto...
21,369
def periodic(interval: int, action, actionargs=()) -> None: """Fucntion that periodicaly calls anoter function""" # Keep calling a function on a periodic basis being the interval s.enter(interval, 1, periodic, (interval, action, actionargs)) action(*actionargs) s.run()
21,370
def command_info(opts): """Display general information from a .zs file's header. Usage: zs info [--metadata-only] [--] <zs_file> zs info --help Arguments: <zs_file> Path or URL pointing to a .zs file. An argument beginning with the four characters "http" will be treated as a URL. Options: -...
21,371
def main(): """ This is called from main.py and will enter the NSApp main loop """ assert NSThread.isMainThread() global app app = NSApplication.sharedApplication() setup() print "entering GUI main loop" app.run() sys.exit()
21,372
def load_triple(cdict, label2words, extend=True): """ Loading triples of color modifiers Parameters ---------- cdict : dict Color dictionary maps a string to list of rgb tuples. label2words : dict Dictionary mapping color labels to color names. Returns ------- dict:...
21,373
def update_status_issue(issue, status_id, notes): """Request to change the status of a problem in a redmine project. 'issue': A hash of the issue is bound to a redmine project. 'status_id': Id status used by redmine the project. 'notes': Comments about the update. Return value: 0 - on succe...
21,374
def update_count_activities(): """Armazena na variável de sessão o número de atividades que estejam pendentes, com os seguintes status: 0 - Criado 1 - Atrasado 2 - Pendente de Parceiro 3 - Pendente de Cliente """ count_activities = 0 if session.get('user_role') == 2: ...
21,375
def _get_avgiver_epost(root: ET.Element, ns: dict) -> Optional[str]: """ Sought: the email of the submitter Can be found in a child element (<mets:note>) of an <mets:agent> with ROLE="OTHER", OTHERROLE="SUBMITTER", TYPE="INDIVIDUAL" """ try: agent = [ agent for agent in _get_...
21,376
def clean(dir_): """Filters the dir_ directory (splits into dir_cleaned and dir_junk).""" dir_cleaned = join(DATA_DIR, dir_ + '_cleaned_final') _make_labeled_dir_structure(dir_cleaned) dir_junk = join(DATA_DIR, dir_ + '_junk_final') _make_labeled_dir_structure(dir_junk) black_list = read_lines(...
21,377
def xavier_init(fan_in, fan_out, constant=1): """ Xavier initialization of network weights\ """ low = -constant * np.sqrt(6.0 / (fan_in + fan_out)) high = constant * np.sqrt(6.0 / (fan_in + fan_out)) return tf.random_uniform((fan_in, fan_out), minval=low, maxval=high...
21,378
def _module_errors_to_junit_test_case(module_error, suit_xml_section): """ Given ModuleError writes a test_case section section to a suit_xml section :param module_error: :type module_error: ModuleErrors :param suit_xml_section: xml context element :type suit_xml_section: ET.Element """ ...
21,379
def test_github_actions_ci(options_baked): """The generated ci.yml file should pass a sanity check.""" ci_text = Path(".github/workflows/ci.yml").read_text() assert 'pip install -r requirements/ci.txt' in ci_text
21,380
def strToMat3(dbstr): """ convert a string like e00, e01, e02, ... into Mat3 :param str: :return: panda Mat4 """ exx = dbstr.split(',') exxdecimal = map(float, exx) assert(len(exxdecimal) is 16) return Mat3(exxdecimal[0], exxdecimal[1], exxdecimal[2], exxdecimal[4...
21,381
def map2(func, *matrix): """ Maps a function onto the elements of a matrix Also accepts multiple matrices. Thus matrix addition is map2(add, matrix1, matrix2) """ matrix2 = [] for i in xrange(len(matrix[0])): row2 = [] matrix2.append(row2) for j in xrange(len(ma...
21,382
def register_libtype(cls): """Registry of library types we may come across when parsing XML. This allows us to define a few helper functions to dynamically convery the XML into objects. See buildItem() below for an example. """ LIBRARY_TYPES[cls.TYPE] = cls return cls
21,383
def construct_tablepath(fmdict, prefix=''): """ Construct a suitable pathname for a CASA table made from fmdict, starting with prefix. prefix can contain a /. If prefix is not given, it will be set to "ephem_JPL-Horizons_%s" % fmdict['NAME'] """ if not prefix: prefix = "ephem_JPL-H...
21,384
def _grad_mulAux(kern,x,y,yerr,original_kernel): """ __grad_mulAux() its necesary when we are dealing with multiple terms of sums and multiplications, example: ES*ESS + ES*ESS*WN + RQ*ES*WN and not having everything breaking apart Parameters kern = kernel in use x = range of values...
21,385
def get_unbiased_p_hat(number_candidates, c1, c2, p): """Get the p_hat to unbias miracle. Args: number_candidates: The number of candidates to be sampled. c1: The factor that the conditional density of z given x is proportional to if the inner product between x and z is more than gamma. c2: The fac...
21,386
def test_send_message_with_an_invalid_recaptcha_response_400_error(client, subtests): """Test 400 error returned when reCAPTCHA response is invalid.""" for recaptcha_response in ['some_invalid_token', 'another_invalid_token']: with subte...
21,387
def mkdir(path): """ Make a directory if it doesn't exist. :param path: directory path """ if not os.path.exists(path): os.makedirs(path)
21,388
def prox_gradf(xy, step): """Gradient step""" return xy-step*grad_f(xy)
21,389
def CBND(x, y, rho): """ A function for computing bivariate normal probabilities. :: Alan Genz Department of Mathematics Washington State University Pullman, WA 99164-3113 Email : alangenz@wsu.edu This function is based on the method described ...
21,390
def prune(root: Node, copy: bool = True) -> Node: """ Prune (or simplify) the given SPN to a minimal and equivalent SPN. :param root: The root of the SPN. :param copy: Whether to copy the SPN before pruning it. :return: A minimal and equivalent SPN. :raises ValueError: If the SPN structure is n...
21,391
def verify_sacct(csv_str): """ Ensure that native format is vaguely valid (treat it as a |-separated csv) """ data = pandas.read_csv(io.StringIO(csv_str), sep="|") assert len(data) > 0
21,392
def GetRevisionAndLogs(slave_location, build_num): """Get a revision number and log locations. Args: slave_location: A URL or a path to the build slave data. build_num: A build number. Returns: A pair of the revision number and a list of strings that contain locations of logs. (False, []) in ca...
21,393
def get_json(url, **kwargs): """Downloads json data and converts it to a dict""" raw = get(url, **kwargs) if raw == None: return None return json.loads(raw.decode('utf8'))
21,394
def get_text(im): """ 得到图像中的文本部分 """ return im[3:24, 116:288]
21,395
def homepage(): """Display tweets""" tweet_to_db() output = [a for a in Tweet.query.order_by(desc('time_created')).all()] # to display as hyper links for tweet in output: tweet.handle = linkyfy(tweet.handle, is_name=True) tweet.text = linkyfy(tweet.text) return render_template...
21,396
def watch_list_main_get(): """ Render watch list page. Author: Jérémie Dierickx """ watchlist = env.get_template('watchlists.html') return header("Watch List") + watchlist.render(user_name=current_user.pseudo) + footer()
21,397
def input_file(inp_str): """ Parse the input string """ # Parse the sections of the input into keyword-val dictionaries train_block = ioformat.ptt.symb_block(inp_str, '$', 'training_data') fform_block = ioformat.ptt.symb_block(inp_str, '$', 'functional_form') exec_block = ioformat.ptt.symb_bloc...
21,398
def exit_on_error(number, *args): """Output on error.""" sys.stderr.write("sine_finder_version=%s\n" % __version_no__) if args: error_txt = __errorcodes__[number] % tuple(args) else: error_txt = __errorcodes__[number] sys.stderr.write(__error_msg__ % (number, error_txt)) sys.ex...
21,399