content
stringlengths
22
815k
id
int64
0
4.91M
def _expand_and_tile(tensor, multiple, dim=0, name=None): """Slice `tensor` shape in 2, then tile along the sliced dimension. A new dimension is inserted in shape of `tensor` before `dim`, then values are tiled `multiple` times along the new dimension. Args: tensor: Input `Tensor` or `SparseTensor`. m...
11,600
def eval_model(opt, print_parser=None): """Evaluates a model. :param opt: tells the evaluation function how to run :param bool print_parser: if provided, prints the options that are set within the model after loading the model :return: the final result of calling report() """ random.see...
11,601
def login(request): """ Login with Dummy Test Account. """ if 'user' in request.environ['beaker.session']: return app.redirect('index') users.store_to_session(request, users.create()) return app.redirect('index')
11,602
def safe_plus(x,y): """ Handle "x + y" where x and y could be some combination of ints and strs. """ # Handle Excel Cell objects. Grrr. if excel.is_cell_dict(x): x = x["value"] if excel.is_cell_dict(y): y = y["value"] # Handle NULLs. if (x == "NULL"): x = 0 ...
11,603
def full_like(a, fill_value, dtype=types.float32, split=None, device=None, comm=None, order="C"): """ Return a full array with the same shape and type as a given array. Parameters ---------- a : object The shape and data-type of 'a' define these same attributes of the returned array. fi...
11,604
def test_autoimport_list_empty(mocker, credentials): """Test user has no jobs.""" runner = CliRunner() mocked_list_s3_autoimport_jobs = mocker.patch.object( APIClient, "list_s3_autoimport_jobs", return_value=S3ProjectImport(results=[], meta=dict(next=None)), ) res = runner.in...
11,605
def safedelete(file_path): """os.remove wrapped in minimal exception handling.""" try: os.remove(file_path) except Exception as ex: print('Exception: ' + str(sys.exc_info()[0])) print(ex)
11,606
def gather_pulled_downloads(input_dir, output_dir): """ Gather MPEG stream files from input_dir into a single MP4 file in output_dir """ dash_globstr = f"{input_dir.absolute() / '*.dash'}" dash_glob = glob(dash_globstr) if len(dash_glob) < 1: raise ValueError(f"No dash file found in {inp...
11,607
def Parallelize(ListIn, f, procs = -1, **kwargs): """This function packages the "starmap" function in multiprocessing, to allow multiple iterable inputs for the parallelized function. Parameters ---------- ListIn: list each item in the list is a tuple of non-keyworded arguments for f...
11,608
def s3_bucket_with_data(s3_client): """ Dummy s3 buckets with objects. """ bucket_name = 'test-orphan-project-objects' bucket_tag = { 'Key': 'Project', 'Value': 'test-objects' }, # Create bucket s3_client.create_bucket( Bucket=bucket_name, CreateBucketConf...
11,609
def run_game(game): """Brain Games Engine. Executing game process Args: game (function): create game question and answer """ print('Welcome to the Brain Games!\n{}\n'.format(game.GAME_DESCRIPTION)) user_name = prompt.string('May I have your name? ') print('Hello, {}!\n'.format(user...
11,610
def to_terminal(series: Union[pd.Series, List[pd.Series]], title: str = 'resource usage', pu: str = 'cpu', labels: Optional[list] = None): """ Plot a datetime series (or a list of them) to terminal Parameters ------- series: A datetime series or a list of ser...
11,611
def main(): """ The main function of the puzzle """ print("The total number of trees on the first trip: %s" % count_trees(map_data)) print("The total number of trees on the second trip: %s" % multi_path(map_data))
11,612
def method_not_found(e): """ Custom response for methods not allowed for the requested URLs :param e: Exception :return: """ return response('failed', 'The method is not allowed for the requested URL', 405)
11,613
def get_total_trainsets(df_anual_data, segments): """ # Fill the training_sets dict :param df_anual_data: :return: """ rows_per_day = int(((60 / 15) * 24)) training_sets = {'ID_SEGMENT': [], 'MES': [], 'COD_LABORALIDAD': [], 'TRAINING_SET': []} for seg_id in segments: # 1) Particionar ...
11,614
def uni2diff(u): """Convert speed and angular rate to wheel speeds.""" v = u[0] omega = u[1] v_L = v - ELL / 2 * omega v_R = v + ELL / 2 * omega return np.array([v_L, v_R])
11,615
def extract_service_and_module(repo_url): """Extract service and module from repository url. :param str repo_url: repository url :return (service, module) :rtype (str, str) """ m = re.match(r'.+[/@]([^\.]+\.[^\.]+)[:/]([^/]+/[^/]+)\.git/?$', repo_url) if not m: m = re.match(r'.+[/@...
11,616
def triangular(left, mode, right, size=None): """Triangular distribution. Draw samples from the triangular distribution over the interval [left, right]. For full documentation refer to :obj:`numpy.random.triangular`. Limitations ----------- Parameter ``left``, ``mode`` and ``right`` are s...
11,617
def format_hexa(value: str) -> ColorBytes: """ Examples: "bda" => (187, 221, 170, 255) "4fcd" => (68, 255, 204, 221) "60B0C4" => (96, 176, 196, 255) "2BEA40D0" => (43, 234, 64, 208) """ if len(value) in {3, 4}: expanded_color = ''.join(s * 2 for s in value) else: ...
11,618
def normalize_community_features(features): """ This performs TF-IDF-like normalization of community embedding features. Introduced in: Tang, L., Wang, X., Liu, H., & Wang, L. (2010, July). A multi-resolution approach to learning with overlapping communities. In Procee...
11,619
def __extend_prefixed(pu): """ :param pu: :return: """ parts = pu.split(':') if len(parts) == 1: parts = ('', parts[0]) try: return URIRef(_prefixes[parts[0]] + parts[1]) except KeyError: return BNode(pu)
11,620
def update_plugins_json(plugin_name, plugin_version, assets): """ Update the plugins JSON in s3 with the new URLs for assets. :param plugin_name: The plugin name :param plugin_version: The plugin version. :param assets: A list of local paths that will be changed to new URLs. :return: """ ...
11,621
async def test_browse_media( hass, hass_ws_client, mock_plex_server, requests_mock, hubs, hubs_music_library, ): """Test getting Plex clients from plex.tv.""" websocket_client = await hass_ws_client(hass) media_players = hass.states.async_entity_ids("media_player") msg_id = 1 ...
11,622
def angle(u: Vec, v: Vec) -> float: """ Returns the cosine (angle) between two vectors u and v :param u: (Vec) vector u :param v: (Vec) vector v :return: The scaled dot product, cosine of u and v's angle """ if u.is_zero or v.is_zero: raise ValueError("Angle with lower dimensional 0 ...
11,623
def find_most_similar(top_k, probs, cache_dict, num=10): """返回最相似的num张照片的文件名,如果找到相似的, 则返回一个包括匹配元组的列表,否则返回一个空列表 top_k : 包含最佳分类的索引的列表 probs : 包含最佳分类索引对应的概率 cache_dict: 缓存中的索引和概率 num : 返回最近匹配的数目 """ similar = [] for filename in cache_dict: score = 0 count =...
11,624
def load(url_or_handle, allow_unsafe_formats=False, cache=None, **kwargs): """Load a file. File format is inferred from url. File retrieval strategy is inferred from URL. Returned object type is inferred from url extension. Args: url_or_handle: a (reachable) URL, or an already open file handle ...
11,625
def evaluate_full_batch(model, minibatch, mode='val'): """ Full batch evaluation: for validation and test sets only. When calculating the F1 score, we will mask the relevant root nodes. """ time_s = time.time() loss, preds, labels = model.eval_step(*minibatch.one_batch(mode=mode)) torch.cuda...
11,626
def berlekamp_massey(s): """Given a sequence of LFSR outputs, find the coefficients of the LFSR.""" C, B, L, m, b = [1], [1], 0, 1, 1 for n in range(len(s)): d = s[n] for i in range(1, L + 1): d ^= mul(C[i], s[n - i]) if d == 0: m += 1 else: ...
11,627
def vocab_from_file(vocabfile): """ Generates vocabulary from a vocabulary file in JSON Outputs vocabulary and inverted vocabulary """ with smart_open(vocabfile, 'r') as f: inv_vocab = json.loads(f.read()) vocabulary = {} for no, word in enumerate(inv_vocab): vocabulary[word...
11,628
def verify_pool_type(pooltype): """ :type pooltype: str :param pooltype: Pool type :raises: ValueError: Invalid Pool type """ valid_pool_types = ['Transactional', 'Repository', 'Archival', 'Iops-Optimized', 'Balanced', 'Throughput-Optimized', 'Depot'] if pooltype not...
11,629
def sample(image: type_alias.TensorLike, warp: type_alias.TensorLike, resampling_type: ResamplingType = ResamplingType.BILINEAR, border_type: BorderType = BorderType.ZERO, pixel_type: PixelType = PixelType.HALF_INTEGER, name: Optional[str] = None) -> tf.Tensor: "...
11,630
def show_record(record, show_logs=True, truncate_logs=None, truncate_result=10000, header_width=100, show_result ='deep', hang=True): """ Show the results of an experiment record. :param record: :param show_logs: :param truncate_logs: :param truncate_result: :param header_width: :param s...
11,631
def normalize_parameter(kv): """ Translate a parameter into standard form. """ (k, v) = kv if k[0] == 'requiressl' and v in ('1', True): k[0] = 'sslmode' v = 'require' elif k[0] == 'dbname': k[0] = 'database' elif k[0] == 'sslmode': v = v.lower() return (tuple(k),v)
11,632
def pulse_broadening(DM, f_ctr): """ pulse_broadening(DM, f_ctr): Return the approximate pulse broadening (tau) in ms due to scattering based on the rough relation in Cordes' 'Pulsar Observations I' paper. 'f_ctr' should be in MHz. The approximate error is 0.65 in log(tau). """ ...
11,633
def generate_wavefunction_coefficients(dir_name: str): """ Generate wavefunction.h5 file using amset. Parameters ---------- dir_name : str Directory containing WAVECAR and vasprun.xml files (can be gzipped). Returns ------- dict A dictionary with the keys: - "d...
11,634
def logged_in_student(browser, override_allowed_hosts, base_test_data): """ Fixture for a logged-in student user Returns: User: User object """ return LoginPage(browser).log_in_via_admin(base_test_data.student_user, DEFAULT_PASSWORD)
11,635
def test_encoding_and_decoding(): """Tests the encoding and decoding of components.""" test_components: Dict[ValidatorName, List[Validator]] = { ValidatorName.SCRIPT: [ ScriptValidator(script="black", args=["-l", "100"]), ScriptValidator( script="black", args=["-...
11,636
def test_model(data_set=None, langider=None, lang_to_idx=None, ) -> np.ndarray: """ Tests a given langid.py model on the given data set. :param data_set: data set to test on :param langider: model to test :param lang_to_idx: mapping of languages to ids """ import numpy as np langs = data...
11,637
def test_copy_axis(): """Sometimes we remove an axis. So when we copy it, we need to make sure that the new dataset doesn't have the removed axis. """ # remove one axis data = create_data() data = math(data, axis='chan', operator_name='mean') assert len(data.axis) == 1 output = data._co...
11,638
def mapquest_search(text): """ Search on Mapquest (https://www.mapquest.com) Parameters ----------- text:- The query which you want to search about (str) """ mapquest=f"https://www.mapquest.com/search/results?query={text}" open(mapquest)
11,639
def search(querry, lim=5): """Search the querry in youtube and return lim number of results. Querry is the keyword, i:e name of the song lim is the number of songs that will be added to video array and returned """ # Replace all the spaces with + querry = querry.replace(' ', '+') url = "ht...
11,640
def calculate_center_of_mass(symbols, coordinates): """Calculate the center of mass of a molecule. The center of mass is weighted by each atom's weight. Parameters ---------- symbols : list A list of elements for the molecule coordinates : np.ndarray The coordinates of ...
11,641
def test_tool_exec_command_dash_help_reverse(help_option): """Execute a command (that needs no params) asking for help.""" cmd = create_command('somecommand', 'This command does that.') command_groups = COMMAND_GROUPS + [('group', 'help text', [cmd])] dispatcher = Dispatcher([help_option, 'somecommand'...
11,642
def __iadd__(self, other): """Pythonic use of concat Example: xs += ys Returns self.concat(self, other)""" return self.concat(self, other)
11,643
def AddSqlServerAuditBucketPath(parser): """Adds the `--audit-bucket-path` flag to the parser.""" parser.add_argument( '--audit-bucket-path', required=False, hidden=True, help=('Path in Google Cloud Storage to upload generated audit files. ' 'The URI is in the form gs://bucketNam...
11,644
def remove_stopwords(texts, stop_words): """ Define functions for stopwords :param texts: Processed texts from main module :return: Texts that already removed a stopwords """ return [[word for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts]
11,645
def patch_aggregated_metadata(context): """ Patches context in aggregated pages """ for metadata in context["posts"]: metadata.body = patch_links( metadata.body, metadata.link[:11], # first 11 characters is path (YYYY/MM/DD/) metadata.link[11:], # following ...
11,646
def dumps(obj): """Output json with formatting edits + object handling.""" return json.dumps(obj, indent=4, sort_keys=True, cls=CustomEncoder)
11,647
def find_asg_using_amis(ami_ids): """ take a list of ami ids and return a dictionary of launch configs that use them """ # ref: return = { ami_id : "lc_arns":[]} ami_ids = listify(ami_ids) result = {id: [] for id in ami_ids} client_asg = boto3.client('autoscaling') lc = client_asg.d...
11,648
def tokenize_nmt(text, num_examples=None): """Tokenize the English-French dataset.""" source, target = [], [] for i, line in enumerate(text.split('\n')): if num_examples and i > num_examples: break parts = line.split('\t') if len(parts) == 2: source.append(par...
11,649
def op_habit(queryUserId): """ 節目操作習慣推薦模組 """ print("****** Start processing op_habit Module! ******\n", file=sys.stderr) tmpStr = "" tmpCount = [] playLog = PlayLog.query.filter_by(user=queryUserId).all() # Find the playlog list of `user` = 1 for i in range(len(playLog)): # Traverse al...
11,650
def setup_snicar(input_file): """Builds impurity array and instances of all classes according to config in yaml file. Args: None Returns: ice: instance of Ice class illumination: instance of Illumination class rt_config: instance of RTConfig class model_config: inst...
11,651
def plot_history(history, figsize=(8, 5)): """Plot metric values through training Args: history: object returned by model.fit(, callbacks=[History(), ...]) metric: metric name from model.metrics_names """ # Setup the figure object figsize=(figsize[0]*len(history.model.metrics_names)...
11,652
async def list_model_config(model_name: str): """ Lists all the model's configuration. :param model_name: Model name :return: List of model's configuration """ try: return ApiResponse(data=dl_service.get_config(model_name)) except ApplicationError as e: raise e except Exception: raise ApplicationError('un...
11,653
def _save_video(f, filename, directory): """ The uploaded video file is saved. """ destination_file = open(os.path.join(directory, filename), 'wb+') for chunk in f.chunks(): destination_file.write(chunk) destination_file.close()
11,654
def signup_post(request): """Получаем данные пользователя с формы и заносим их в базу проверяя, если удачно то предоставляем вход в базу потом дополнительные идентификац""" mess = "login please" data = get_post( request ) mail = data.POST['mail'] name = data.POST['name'] captcha = data.POST['captcha'] hash = da...
11,655
def make_onehot(label, num_classes, axis=-1): """ Create one hot tensor based on the input tensor Args: label: input tensor, the value must be positive integer and less than num_class num_classes: the number of class in one hot tensor axis: The axis to fill (default: -1, a new inner-...
11,656
def test_random_fourier_feature_layer_compute_covariance_of_inducing_variables( basis_func_cls, batch_size ): """ Ensure that the random fourier feature map can be used to approximate the covariance matrix between the inducing point vectors of a sparse GP, with the condition that the number of latent ...
11,657
def kohn_sham_iteration( state, num_electrons, xc_energy_density_fn, interaction_fn, enforce_reflection_symmetry): """One iteration of Kohn-Sham calculation. Note xc_energy_density_fn must be wrapped by jax.tree_util.Partial so this function can take a callable. When the arguments of this cal...
11,658
def calculate_reliability(data): """ Calculates the reliability rating of the smartcab during testing. """ success_ratio = data['success'].sum() * 1.0 / len(data) if success_ratio == 1: # Always meets deadline return ("A+", "green") else: if success_ratio >= 0.90: return ("A", "green") elif success_ratio...
11,659
def sort_and_index(file_name, sorted_prefix=None): """ Sorts and indexes the bam file given by file_name. """ if sorted_prefix is None: sorted_prefix = file_name.replace('.bam', '') + '_sorted' sorted_name = sorted_prefix + '.bam' log_subprocess.check_call(['samtools','sort', '-o', sorted_n...
11,660
def cache_mat_calc(dra, ddc, dra_err, ddc_err, ra_rad, dc_rad, ra_dc_cor=None, l_max=1, fit_type="full", num_iter=None): """Calculate cache matrix for future use Parameters ---------- dra/ddc : array of float R.A.(*cos(Dec.))/Dec. differences dra_err/ddc_err : array of fl...
11,661
def get_android_replacements(): """Gets a dictionary of all android-specific replacements to be made.""" replacements = {} compileSdk = 'compileSdkVersion {}'.format(COMPILE_SDK_VERSION) targetSdk = 'targetSdkVersion {}'.format(TARGET_SDK_VERSION) buildToolsVersion = 'buildToolsVersion \'{}\''.form...
11,662
def process_long_term_idle_users( slack_data_dir: str, users: List[ZerverFieldsT], slack_user_id_to_zulip_user_id: SlackToZulipUserIDT, added_channels: AddedChannelsT, added_mpims: AddedMPIMsT, dm_members: DMMembersT, zerver_userprofile: List[ZerverFieldsT], ) -> Set[int]: """Algorithmic...
11,663
def tb_view(model, logdir=None, cmd=None): """Visualises a :model: in TensorBoard. (That is, everything in the model's Graph, which may actually be much larger than the model itself.) TensorBoard should automatically open; it is inconsistent whether the browser will automatically come to the front thou...
11,664
def clear_cache(): """ Clears internal cache. Returns something that can be given back to restore_cache. """ global FS_CACHE old = FS_CACHE FS_CACHE = {} return old
11,665
def extend_gdf(gdf_disjoint, id_col): """ Add duplicates of intersecting geometries to be able to add the constants. This function adds rows with duplicate geometries and creates the new `id` column for each of the new rows. This function is called by another function `complete_disjoint_geoms`. ...
11,666
def schedule_news_updates(update_interval:int, update_name:str)->dict: """ Functionality: --------------- Schedules a new news data update Parameters: --------------- update_interval: int The time until the scheduler should update the...
11,667
def test_basic_greetings(): """The bot should respond sensibly to common greeting words""" sent = "hello" resp = broback(sent) assert resp == GREETING_RESPONSES[1]
11,668
def ValidateResponse(data): """Validate a JSON-RPC response object. Args: data: The JSON-RPC object (dict). Raises: ProtocolError: if the object format is not correct. """ ValidateBasicJSONRPCData(data) if 'response' not in data: raise ProtocolError('JSON is not a valid response')
11,669
def get_digits(text): """ Returns all numeric characters (digits) in string *text* in a new (concatenated) **string**. Example: >>> get_digits('Test123') '123' >>> int(get_digits('The answer is 42')) 42 :param text: The string to search. :type text: str, uni...
11,670
def make(): """ генератор 1 расстановки = 1 горизонтали""" # ставим 1 слона to = random.choice((1, 3, 5, 7)) f1[to-1] = "B" fp.remove(to) # ставим 2 слона to = random.choice((2, 4, 6, 8)) f1[to-1] = "B" fp.remove(to) # ставим ферзя to = random.choice(fp) f1[to-1] = "Q"...
11,671
def test_all(args): """ Measure FPS of all configurations. """ agent_types = [ "Baxter_ik", "Baxter_impedance", "Sawyer_ik", "Sawyer_impedance", "Cursor_ik", ] rendering_qualities = ["no_200", "low_200", "high_200", "low_500", "high_500"] furniture_id...
11,672
def embed_tiles_in_json_sprite(tile_list, as_bytes=True, out_file=None): """Make a big rectangle containing the images for a brainsprite. Parameters: ----------- tile_list : list List of 2d square numpy arrays to stick in a mosaic Returns: -------- mosaic : np.ndarray ...
11,673
def test_compare_eq3(): """ not not (two == 2), 20x """ n = 20 while n: not not (two == 2) n -= 1
11,674
def removeUnicode(text): """ Removes unicode strings like "\u002c" and "x96" """ text = re.sub(r'(\\u[0-9A-Fa-f]+)',r'', text) text = re.sub(r'[^\x00-\x7f]',r'',text) return text
11,675
def mark_word(page, text): """ Underline each word that contains 'text'. """ wlist = page.getText("words") # make the word list for w in wlist: # scan through all words on page if text in w[4]: # w[4] is the word's string r = fitz.Rect(w[:4]) # make rect fro...
11,676
def mfcc(tf, n_mfcc, fs, fmin=0.0, fmax=None): """ Extract MFCC vectors Args: tf : single-channel time-frequency domain signal, indexed by 'tf' n_mfcc : number of coefficients fs : sample rate fmin : (default 0) minimal frequency in Hz fmax : (defa...
11,677
def transform(fname, metadata=False): """ This function reads a Mission Analysis Orbit file and performs a matrix transformation on it. Currently only from the Mercury Equatorial frame to the Earth Equatorial frame. :param fname: The path to the orbit file. :type fname: str. :param metadata...
11,678
def query_repository(repo_name, index_uuid, token, display_results=False): """ Display the ids ('subjects') of all items indexed in a repository. :param repo_name: Textual name of repository to query, corresponds to 'name' field in conf file. :param index_name: Name of index, mapped by us to a UUID. ...
11,679
def clean_weight_func(value, kpi, scorecard): """ ensure that the total weight values are not more than 100% """ if scorecard: try: scorecard_kpis = ScorecardKPI.objects.filter(scorecard=scorecard) except ScorecardKPI.DoesNotExist: pass else: i...
11,680
def power(x1, x2, out=None, where=True, dtype=None): """ First array elements raised to powers from second array, element-wise. Raises each base in `x1` to the positionally-corresponding power in `x2`. Note: Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are ...
11,681
def _str2bool(s): """文字列からboolへの変換""" return s.lower() in ["true", "t", "yes", "1"]
11,682
def _generate_nonce(length=42): """ Generate an alpha numeric string that is unique for each request. Twitter used a 42 character alpha-numeric (case-sensitive) string in the API documentation. However, they note "any approach which produces a relatively random alphanumeric string should be OK here...
11,683
def env_vars_delete(env_var_id, deployment_name, version_name, assume_yes, quiet): """ Delete an environment variable. \b - When deployment_name and version_name are provided: the environment variable will be deleted on deployment version level. - When a deployment name is provided, but not a v...
11,684
def is_expired(image_id: str) -> bool: """ Check whether entry is expired (based on timestamp encoded in the image_id) """ ts = expiration(image_id) now = datetime.now(timezone.utc) if ts is None: log.debug("Invalid cache entry ID: %s", image_id) return True log.debug("entry...
11,685
def int_(value): """Validate that the config option is an integer. Automatically also converts strings to ints. """ check_not_templatable(value) if isinstance(value, int): return value if isinstance(value, float): if int(value) == value: return int(value) rai...
11,686
def explode(screen): """Convert a string representing a screen display into a list of lists.""" return [list(row) for row in screen.split('\n')]
11,687
def covert_to_bin(): """ save dataset with bin format :return: no return """ dataset = lstm_create_dataset(config.preprocess_path, config.batch_size, training=False) img_path = os.path.join(config.result_path, "00_data") os.makedirs(img_path) label_list = [] for i, data in enumerate(...
11,688
def merge_csv_files(directory, out): """\ Merges the CSV files in the provided `directory` into one CSV file. :param str directory: Path where to find the CSV files :param str out: Resulting file name. """ f = open(out, 'w', encoding='utf-8') writer = csv.writer(f) writerow = writer.wri...
11,689
def test_get_system_service_sdp(sros_parser, parsed_system_sdp): """ Test extracting system SDPs """ result = sros_parser.get_system_service_sdp() assert result, parsed_system_sdp
11,690
def basic_info(user, keys): """Prints a table of basic user information""" table = formatting.KeyValueTable(['Title', 'Basic Information']) table.align['Title'] = 'r' table.align['Basic Information'] = 'l' table.add_row(['Id', user.get('id', '-')]) table.add_row(['Username', user.get('username...
11,691
def iobes_iob(tags): """ IOBES -> IOB """ new_tags = [] for i, tag in enumerate(tags): if tag == 'rel': new_tags.append(tag) elif tag.split('-')[0] == 'B': new_tags.append(tag) elif tag.split('-')[0] == 'I': new_tags.append(tag) eli...
11,692
def draw_handler(canvas): """ Event handler that is responsible for all drawing. It receives "canvas" object and draws the "Pong" table, the "moving" ball and the scores of each "Player". It is also responsible for testing whether the ball touches/collides with the "gutters" or the "paddles". ...
11,693
def tf_idf(df, vocab): """[summary] https://towardsdatascience.com/natural-language-processing-feature-engineering-using-tf-idf-e8b9d00e7e76 Args: docs ([type]): [description] """ docs = [] for text in df['text'].tolist(): docs += [text] vectorizer = TfidfVectorizer(tokeniz...
11,694
def runtest_teardown(item: IPyNbFile, nextitem: typing.Optional[IPyNbFile]) -> None: """Propagate cell failure.""" # Do the normal teardown item.teardown() # Inform next cell of the notebook of failure of any previous cells if hasattr(item, "_force_skip"): if nextitem is not None and nextite...
11,695
def test_tree_2_nodes_left_unbalanced(one_t): """Tree with 2 nodes and left sided should return balance of 1.""" one_t.insert(9) assert one_t.balance() == 1
11,696
def setup_checkpoint_dir(cfg, args, phase): """Create checkpoint directory # ROUND2-TODO: let's make this checkpoint director way more involved. Specific to user, to model, to config name, etc. """ root_dir = os.path.join( cfg["checkpoints_dir"], cfg["model"]["name"], args.config_name ) ...
11,697
def get_activation_func(activation): """Turns a string activation function name into a function. """ if isinstance(activation, string_types): # Get the activation function. activation = activation.lower() if activation == "tanh": activation_func = tanh elif activa...
11,698
def number_of_cores(): """ number_of_cores() Detect the number of cores in this system. """ # Linux, Unix and MacOS: if hasattr(os, "sysconf"): if "SC_NPROCESSORS_ONLN" in os.sysconf_names: # Linux & Unix: ncpus = os.sysconf("SC_NPROCESSORS_ONLN") if ...
11,699