content
stringlengths
22
815k
id
int64
0
4.91M
def friend_invitation_by_email_verify_for_api( # friendInvitationByEmailVerify voter_device_id, invitation_secret_key, web_app_root_url=''): """ :param voter_device_id: :param invitation_secret_key: :param web_app_root_url: :return: """ status = "" success = False # If a v...
12,400
def preprocess_rinex(rinex_file, target_directory=None): """Read a RINEX Navigation Message file and reformat the data. Read a file with name "BRDC00IGS_R_yyyyddd0000_01D_MN.rnx" that was downloaded from https://cddis.nasa.gov/archive/gnss/data/daily/yyyy/brdc/ where yyyy is the year and ddd is the day...
12,401
def _load_image(fnames, dim=None, device=None, label=False): """Load a N-D image from disk""" dat, affine = _map_image(fnames, dim) if label: dtype = dat.dtype if isinstance(dtype, (list, tuple)): dtype = dtype[0] dtype = dtypes.as_torch(dtype, upcast=True) dat0 =...
12,402
def GetCurrentVersion(paths, platform): """Find the current component version by iterating gsbucket root folder. Args: paths: ([str]) a list of folder paths strings. platform: (str) the platform for which the component is being built Returns: str: current component version. str: gs path for curr...
12,403
def dtpool(name: str) -> Tuple[int, str, bool]: """ Return the data about a kernel pool variable. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dtpool_c.html :param name: Name of the variable whose value is to be returned. :return: Number of values returned for name, ...
12,404
def write_output(df, filename): """ Writes the given data frame to the given file. :param pd.DataFrame df :param str filename """ logging.info('Writing output') feather.write_dataframe(df, filename)
12,405
def add_similar_tracks(position_or_range = ":", howmany=5, relative_positions=True): """ Adds Up to the value of howmany tracks similar to each track on the current playlist. parameters: =========== # position_or_range: The position of the track to add similar tr...
12,406
def get_hot_article_tags(): """ 获取文章的所有标签 :return: 返回所有文章的标签 """ return Tag.objects.filter(is_hot=True)
12,407
def patch_user_interface_null() -> MockedUserInterfaceNull: """Patch player interface with no players.""" return patch("steam.api.interface", return_value=MockedUserInterfaceNull())
12,408
def setup_logging(loglevel): """Setup basic logging Args: loglevel (int): minimum loglevel for emitting messages """ logformat = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s" logging.basicConfig(level=loglevel, format=logformat, datefmt="%Y-%m-%d %H:%M:%S", handlers=[_handler])
12,409
def confirm(new_command, side_effect, settings): """Returns `True` when running of new command confirmed.""" if not settings.require_confirmation: logs.show_command(new_command, side_effect, settings) return True logs.confirm_command(new_command, side_effect, settings) try: sys....
12,410
def setup_log(level): """ Note that the log level may be changed by the cfg file """ logging.basicConfig(level=level, format='%(asctime)s %(levelname)s: %(message)s', datefmt='%Y/%m/%d %H:%M:%S') logger.debug("DEBUG")
12,411
def first_localmax_index(data): """Return index of first local maxima. If there is no local maxima (e.g. if all the values are zero), it will simply return zero. """ localmax_indexes = signal.argrelextrema(data, numpy.greater, mode='wrap') if localmax_indexes[0].size > 0: return loc...
12,412
def _rds_clone_ ( dataset , name = '' ) : """Clone dataset >>> dataset = ... >>> cloned = datatset.clone ( 'new_name') """ name = name if name else dsID () return ROOT.RooDataSet ( dataset , name )
12,413
def getFirstDateOfQuarter(date): """ Return: {Date} The start date of the quarter for the given date. """ # Bug if first date of the quarter is used, so add 1 if that's the case. if date.day == 1: date = date + timedelta(days=1) quarter_start = pd.to_datetime(date - pd.tseries.offsets.QuarterBegin(startingMo...
12,414
def abbink_onset_detector(signal=None, rest=None, sampling_rate=1000., size=None, alarm_size=None, threshold=None, transition_threshold=None): """Determine onsets of EMG pulses. Follows the approach by Abbink et al.. [Abb98]_. Parameters ---------- ...
12,415
def reparse(metadata): """Some things need to be parsed again after the build environment has been created and activated.""" metadata.final = False sys.path.insert(0, metadata.config.build_prefix) sys.path.insert(0, metadata.config.host_prefix) py_ver = '.'.join(metadata.config.variant['python']...
12,416
def _process_image(filename, coder): """Process a single image file. Args: filename: string, path to an image file e.g., '/path/to/example.JPG'. coder: instance of ImageCoder to provide TensorFlow image coding utils. Returns: image_buffer: string, JPEG encoding of RGB image. height: integer,...
12,417
def test_get_end_coords(): """ Tests the get_end_coords function :return: Asserts true if test cases pass, false if otherwise """ start = Coordinates(4, 5) end = Coordinates(9, 16) length = 7 out_ln = 3 in_ln = 2 angle = (math.pi/2) speed_limit = 10 test_coords = get_end...
12,418
def fork_processes_with_watchdog( num_processes, is_shutdown_callback, child_pids=None, stoploss_ratio=STOPLOSS_RATIO, timeout_period=TIMEOUT_PERIOD, sleep_period=SLEEP_PERIOD, grace_period=GRACE_PERIOD, max_rss=MAX_RSS, statsd=None, app_name='default'): """Starts multiple worker processes. If ...
12,419
def load_fonts(folder="fonts/latin"): """Load all fonts in the fonts directories """ fonts = [] if folder is not None: if os.path.isdir(folder): # the folder exists whether it is relative or absolute path for font in os.listdir(folder): if font.split(".")...
12,420
def main() -> None: """ Calculate and output the solutions based on the real puzzle input. """ data = aocd.get_data(year=2020, day=22) decks = read_decks(data) result = play_game(decks) print(f"Part 1: {sum(score(deck) for deck in result)}") decks2, _ = play_recursive_game(decks) p...
12,421
def float_feature(value): """Wrapper for inserting float features into Example proto. """ if not isinstance(value,list): value = [value] return tf.train.Feature(float_list=tf.train.FloatList(value=value))
12,422
def my_charts(request): """ define personal graphics page behavior """ data = [0, 0, 0, 0] if request.method == 'POST': month = request.POST.get('month') if month is not None: current_user_id = request.user.id_user if month == 'all': all_class...
12,423
def sort_test(): """Sort variations""" pos = [1, 10, 20] stop = [2, 11, 21] ref = ['A', 'C', 'T'] alt = ['AA', 'CAT', 'G'] p = [0.1, 0.5, 0.9] l = vr.VariantList(pos, stop, ref, alt, p) pos = [5, 15] stop = [6, 16] ref = ['T', 'G'] alt = ['A', 'GAT'] p = [0.1, 0.5] l.add(pos, stop, ref, alt, ...
12,424
def matrix2yzy_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Ry(k3) @ Rz(k2) @ Ry(k1) = [[c1c2c3-s1s3, -s2c3, s1c2c3+c1c3], [c1s2, c2, s1s2], [-c1c2s3, s2s3, -s1c2s3+c1c3]] """ rotation_matrices = rotation_matrices.reshape((-1...
12,425
def smallest_subarray_with_given_sum(arr, s): """Find the length of the smallest subarray whose sum is >= s. Time: O(n) Space: O(1) >>> smallest_subarray_with_given_sum([2, 1, 5, 2, 3, 2], 7) 2 >>> smallest_subarray_with_given_sum([2, 1, 5, 2, 8], 7) 1 >>> smallest_subarray_with_giv...
12,426
def create_lit_model( model: str, input_types: "OrderedDict[str, lit_types.LitType]", # noqa: F821 output_types: "OrderedDict[str, lit_types.LitType]", # noqa: F821 attribution_method: str = "sampled_shapley", ) -> lit_model.Model: """Creates a LIT Model object. Args: model: ...
12,427
def test_load_first(install_mockery, mock_fetch, mock_archive, mock_packages): """Test with and without the --first option""" install('mpileaks') # Only one version of mpileaks will work diff('mpileaks', 'mpileaks') # 2 specs are required for a diff with pytest.raises(spack.main.SpackCommandEr...
12,428
def show_lightning_round_zero_correct(database_connection: mysql.connector.connect ) -> List[Dict]: """Return list of shows in which a panelist answers zero Lightning Fill-in-the-Blank round questions correct""" cursor = database_connection.cursor(dictionary=True) q...
12,429
def get_webpage(page_url): """Get the OOTS index webpage and return the content.""" result = requests.get(page_url) if result.status_code == 200: return result.text else: _logger.error( colored( "Unable to read the OOTS data,please check your connection.", ...
12,430
def generate_config(context): """ Entry point for the deployment resources. """ properties = context.properties name = properties.get('name', context.env['name']) bastion_props = { 'zone': properties['zone'], 'network': properties['network'], 'machineType': properties['machineT...
12,431
def dump_args(func): """Decorator to print function call details - parameters names and effective values. """ def wrapper(*args, **kwargs): func_args = inspect.signature(func).bind(*args, **kwargs).arguments func_args_str = ', '.join('{} = {!r}'.format(*item) for item in func_args.items()) ...
12,432
def bigaussian( n_particles: int, mean: Tuple[float, float, float, float, float], geometric_emittance_h: float, geometric_emittance_v: float, sigma_p: float, ) -> np.array: """Generate a bigaussian distributed distribution. Args: n_particles: Number of particles. meam: Distr...
12,433
def test_affected_repr(): """Test repr() for the Affected class.""" affected = Affected.from_dict( {'name': 'my-package', 'version': [], 'fixedin': []}, ecosystem='python' ) assert repr(affected) == '<Affected(name=my-package)>'
12,434
def test_parser(): """ Tests PasswordHashParser implementation. """ PWD_LENGTH = 64 password = misc_utils.generate_random_string(PWD_LENGTH) wrong_password = misc_utils.generate_random_string(PWD_LENGTH) assert password != wrong_password # Test pbkdf2_sha256(md5(password)). md5_salt = auth_utils.gen...
12,435
def horizontal_tile(silhouette, reps = 2): """Places two silhouettes side-by-side with an empty line in the middle.""" silhouette = np.append(silhouette,np.zeros((silhouette.shape[0],1)),axis=1) return np.tile(silhouette,(1,reps))[:,:]
12,436
def grads_norm(parameters): """get grad norms of the parameters, useful for model inspection""" t = [p.grad for p in parameters if p.grad is not None] return many_l2_norm(*t)
12,437
def django_admin_add_object(request, context): """show add object""" if request and request.user.is_staff and (context.get('object', None) or context.get('model', None)): object_class = context.get('model', None) if not object_class: object_class = context['object'].__class__ ...
12,438
def test_bellmanford_sp(graph_sp): """Test the bellmanford algorithm returns shortest path.""" assert graph_sp.bellmanford('A', 'E') == 20
12,439
def get_config(): """Returns an instance of the configured config class. :return: Project's defined Adyen configuration. :rtype: :class:`AbstractAdyenConfig` By default, this function will return an instance of :class:`adyen.settings_config.FromSettingsConfig`. If :data:`ADYEN_CONFIG_CLASS` is...
12,440
def aperiodic(amp, samples): """an aperiodic oscillating signal Parameters ---------- amp : float values range over +-amp samples : int number of samples to generate Returns ------- ndarray """ periods = np.abs(sine(samples, samples, 1)) + samples / 10 seq ...
12,441
def kriging_interpolate(): """ Use Guassain Process Regression provided by Scikit-learn """ pass
12,442
def removeHs(ctab): """ Removes any hydrogens from the graph of a molecule. CTAB is urlsafe_base64 encoded string containing single molfile or concatenation of multiple molfiles. cURL examples: curl -X GET ${BEAKER_ROOT_URL}removeHs/$(cat removeHs.mol | base64 -w 0 | tr "+/" "-_") curl -X GET ${BEAKER_ROOT...
12,443
def judge_key(key: str, up: any): """判断key是否存在""" if dict == type(up): if key in up: return True else: for dict_key, dict_value in up.items(): if dict == type(dict_value) or list == type(dict_value): result = judge_key(key, dict_value) ...
12,444
def apply_changes(patch_obj_dic, file_dic): """ If all checks are passed, write the changes to the patch file. Note that the original file is overwritten :return: """ success = False error_title = None error_msg = None # Checks that mutually exclusive options have not been set together. ...
12,445
def test_filter_translate(tr_arg, tr_src, tr_dest): """Tests for translate argument. Translate characters from one to another """ args = parser.parse_args(["-tr", *tr_arg]) filters = renamer.initfilters(args) dest = renamer.get_renames(tr_src, filters, args.extension, args.raw) assert dest == tr_des...
12,446
def construct_1D_scan_fast(gate, swing, n_pt, t_step, biasT_corr, pulse_lib, digitizer, channels, dig_samplerate, dig_vmax=2.0, iq_mode=None, acquisition_delay_ns=None, enabled_markers=[], channel_map=None, pulse_gates={}, line_margin=0): """ 1D fast scan pa...
12,447
def main(): """ Running the word guessing game """ ans = random_word() run_game(ans, N_TURNS)
12,448
async def test_fan_direction(hass, hk_driver, events): """Test fan with direction.""" entity_id = "fan.demo" hass.states.async_set( entity_id, STATE_ON, {ATTR_SUPPORTED_FEATURES: SUPPORT_DIRECTION, ATTR_DIRECTION: DIRECTION_FORWARD}, ) await hass.async_block_till_done() ...
12,449
def assemble_f_local(ck, f_func, p1, p2, p3): """ Assemble the local contribution to the f_load_lv for the element Parameters ---------- ck : np.array basis function coef. matrix. f_func : function load function. p1 : np.array first vertex of the triangle element. ...
12,450
def test_from_percolator(perc_weights): """ Test the from_percolator() function. Verify that a model is correctly loaded from the Percolator weights output. """ path = os.path.join(perc_weights) loaded = xenith.from_percolator(path) # Correct answers for feat_mean and feat_stdev fe...
12,451
def take_turn(num_rolls, opponent_score, dice=six_sided): """Simulate a turn rolling NUM_ROLLS dice, which may be 0 (Free Bacon). Return the points scored for the turn by the current player. Also implements the Hogtimus Prime rule. num_rolls: The number of dice rolls that will be made. oppone...
12,452
def __sort_vertices(points): """Return vertices that are sorted by average center of all points.""" points = list(set(points)) if len(points) < 3: return None start_point = __find_average_center(points) start_vector = Vector3D.by_points(start_point, points[0]) return sorted(points, key=lambda point: ...
12,453
def is_arnold_usd_available(): """ Returns whether or not Arnold USD libraries and schemas are available in current session :return: bool """ raise NotImplementedError('is_arnold_usd_available function is not implemented!')
12,454
def create_feature( tokens: List[str], label_ids: List[int], words_map: List[Tuple[int, int, bool]], max_seq_length: int, tokenizer: PreTrainedTokenizer, cls_token_at_end=False, cls_token="[CLS]", cls_token_segment_id=1, sep_token="[SEP]", ...
12,455
def unified_genotyper(align_bams, items, ref_file, assoc_files, region=None, out_file=None): """Perform SNP genotyping on the given alignment file. """ if out_file is None: out_file = "%s-variants.vcf" % os.path.splitext(align_bams[0])[0] if not file_exists(out_file): ...
12,456
def test_add_finished_hashes(local_config): """Tests adding hashes that are finished and getting them with get_previous_hashes().""" manager = StateManager(local_config) manager.set_checkpoint('DEFGHIJK', 'default', 'DONE') manager.set_checkpoint('ABCDEFGH', 'default', 'DONE') manager.set_checkpoint...
12,457
def read_and_compress_table(parser, table, debug): """Read data from a FITS file and save it into a FITS binary table The data are read from the FITS file specified in the "table" section of the "parser" object (an instance of ConfigurationParser). If "debug" is true, save additional information (u...
12,458
def calculate_log_likelihood_and_derivative_at_parameter_point_with_mRNA(protein_at_observations,model_parameters,mean_protein,measurement_variance,mRNA_parameters): """ Calculates the log of the likelihood, and the derivative of the negative log likelihood wrt each parameter, of our data given the paramter...
12,459
def test_wheel_compiles_pyc( script: PipTestEnvironment, shared_data: TestData, tmpdir: Path ) -> None: """ Test installing from wheel with --compile on """ shutil.copy(shared_data.packages / "simple.dist-0.1-py2.py3-none-any.whl", tmpdir) script.pip( "install", "--compile", ...
12,460
def SEORedirectMiddleware(get_response): """ Intercepts 404 errors and checks the database for any defined redirecs that match the current request path. """ def middleware(request): response = get_response(request) if response.status_code != 404: return response ...
12,461
def b2s(src): """ Convert from bytes to string :param src: bytes :return: string """ return src.decode(encoding=UTF_ENCODING)
12,462
def get_finetune_lfo_type(header: bytes) -> AutomationLfoType: """Return finetune LFO type.""" assert isinstance(value := _unpack(header, "FINETUNE_LFO_TYPE"), int), type(value) return AutomationLfoType(value)
12,463
def main(): """Main module execution code path""" AzureRMManagedDiskFacts()
12,464
def locate(client: Client, structure: Structure) -> str: """Locates the respective structure.""" return client.run('locate', structure)
12,465
def teraflops_for_accelerator(accel): """ Stores the number of TFLOPs available to a few accelerators, including driver handicaps. Args: accel (str): A string descriptor of which accelerator to use. Must be either "3090" or "V100". Returns: accel_flops (int): an integer of how many TFL...
12,466
def reduced_supercell_vectors(ab, n): """ Returns all possible reduced in-plane lattice vectors and transition matrices for the given starting unit cell lattice vectors(ab) and the supercell size n Args: ab: a, b lattice vectors n: (int) supercell size """ uv_list = [] ...
12,467
def jsonify(*args, **kwargs): """Creates a `Response` with the JSON representation of the given arguments with an`application/json` mimetype. The arguments to this function are the same as to the `dict` constructor. Example usage: from cocopot import jsonify @app.route('/_get_curre...
12,468
def logged_in_profile(client): """Add a Profile and logged-in User""" user = UserFactory.create(username="george") client.force_login(user) return user.profile
12,469
def log(type, message, *args, **kwargs): """Log into archer logger. Only set up a default log handler if the end-user application didn't set anything up. """ if not logging.root.handlers and base_logger.level == logging.NOTSET: base_logger.setLevel(logging.INFO) handler = logging....
12,470
def plot_fini(): """ Plot the data, opens web browser with plot :return: None """ doc_layout.children.append(plot) doc_layout.children.append(plot_mahr) show(doc_layout)
12,471
def get_storage_backend(): """ Return the singleton instance of the storage backend in use. """ global _STORAGE_BACKEND if _STORAGE_BACKEND is None: module, klass = ClassLoader.split(str(config.STORAGE_BACKEND_CLASS)) cl = ClassLoader(module, klass, config.STORAGE_BACKEND_ARGS) ...
12,472
def _pr_compile(regex, cleanup=None): """Prepare a 2-tuple of compiled regex and callable.""" return (_re_compile(regex), cleanup)
12,473
def hydrate_detectify(event): """Hydrator for detectify events, enriching them with owner, a fingerprint and metadata. Args: event (comet_core.app.EventContainer): the incoming event to hydrate """ msg = event.message event.set_owner(get_owner_email_from_domain(msg['domain'])) event...
12,474
def config(): """ Configuration via config.json (introduced in Anki 2.1) """ try: getConfig = mw.addonManager.getConfig except AttributeError: return LEGACY_CONFIG return getConfig(__name__)
12,475
def test_provenance(): """ test provenance features """ ## create a new project project = create_project() ## create a data entity try: filename = utils.make_bogus_data_file() data_entity = create_data_entity(project['id']) data_entity = syn.uploadFile(data_entity...
12,476
def ping(request): """ This view returns a dummy json. It is meant to be used to check whether the server is alive or not """ return Json(None)
12,477
def copy_ffn(model): """Copy feed forward network model. Args: model: A previously created ffn model Returns: A copy of the model """ import numpy as np import copy #init model as list holding data for each layer start with input layer newmodel = [] newmodel.append(...
12,478
def nlp_progress() -> TaskDB: """Parse a the whole nlp progress repo or a single markdown file. Checkouts the nlp progress git repository and parses all the markdown files in it. Returns: TaskDB: Populated task database. """ tdb = TaskDB() with tempfile.TemporaryDirectory() as tmp...
12,479
def is_big(label: str) -> bool: """Returns whether or not a cave is large based on its label""" return label.isupper()
12,480
def fast_mult_polynoms(a, b): """Fast multiply of two polynoms in GF(2^8) using the log table NB. This is NOT constant-time and leaks secret values in timing differences. DO NOT USE THIS CODE TO IMPLEMENT SECURE APPLICATIONS """ if a == 0 or b == 0: return 0 return POWER_X1_TABLE[(LOG_...
12,481
def get_page_for_group(user_groups, slug): """ Returns a page associated with user_groups given a slug. """ try: page = get_pages_for_group(user_groups).get( slug = slug) except Page.DoesNotExist: page = None return page
12,482
def create(ctx, asset_a, asset_b, share_asset, taker_fee, withdrawal_fee, account): """ Create a new Liquidity Pool. ASSET_A, ASSET_B: These are the assets to be traded in the pool. Can be symbols or ids. Note that ASSET_A should be the one that has the lowest-numbered asset id. SHARE_ASSET: This ...
12,483
def read_gps(gps_path): """Read GPS feed in CSV. Expects GPS structured as: vehicle_id: str Internal system identification of the vehicle. Should be unique per vehicle, and is used for tracking the vehicle as it proceeds through the system. route_id: str ...
12,484
def _ureduce(a, func, **kwargs): """ Internal Function. Call `func` with `a` as first argument swapping the axes to use extended axis on functions that don't support it natively. Returns result and a.shape with axis dims set to 1. Parameters ---------- a : array_like Input tens...
12,485
def compute_autocorrelation_local(x, Fs, N, H, norm_sum=True): """Compute local autocorrelation [FMP, Section 6.2.3] Notebook: C6/C6S2_TempogramAutocorrelation.ipynb Args: x: Input signal Fs: Sampling rate N: Window length H: Hop size norm_sum: Normalizes by the num...
12,486
def euclid_dist(vector_p1, vector_p2): """ calculated the euclidean distance between 2 points """ distances = vector_p1 - vector_p2 return cp.hypot(distances[:, :, 0], distances[:, :, 1])
12,487
def _name_cleaner(agent_name): """Renames agent_name to prettier string for plots.""" rename_dict = {'correct_ts': 'Correct TS', 'kl_ucb': 'KL UCB', 'misspecified_ts': 'Misspecified TS', 'ucb1': 'UCB1', 'ucb-best': 'UCB-best', 'non...
12,488
def add_training_args(parser): """Training arguments.""" group = parser.add_argument_group('train', 'training configurations') group.add_argument('--experiment-name', type=str, default="gpt-345M", help="The experiment name for summary and checkpoint") group.add_argument('--batch...
12,489
def _multi_class_confusion_matrix_plot( thresholds: Optional[List[float]] = None, num_thresholds: Optional[int] = None, name: Text = MULTI_CLASS_CONFUSION_MATRIX_PLOT_NAME, eval_config: Optional[config.EvalConfig] = None, model_name: Text = '', output_name: Text = '', ) -> metric_types.MetricCom...
12,490
def innerL(i, os): """ Parameters ---------- i os:OptStruct Returns ------- """ ei = cal_ek(os, i) if (os.labels[i] * ei < -os.tol and os.alphas[i] < os.C) or ( os.labels[i] * ei > os.tol and os.alphas[i] > 0 ): j, ej = select_j(i, os, ei) alphaIol...
12,491
def verify_manifest_by_spath(extrepo, session_path): """This function will load the given manifest and then verify the checksum of every file specified within. If the manifest file has a md5 checksum in its filename, the manifest file itself will be verified against that checksum.""" print("Verifyi...
12,492
def create_client(ctx: click.Context, opts: ProxyContext) -> CumulocityClient: """Create Cumulocity client and prompt for missing credentials if necessary. Args: ctx (click.Context): Click context opts (ProxyContext): Proxy options Returns: CumulocityClient: Configured Cumuloci...
12,493
def rename_worksheet(sheet, wrk_sheet, sheet_name): """ REF: https://github.com/burnash/gspread I reuse the gspread function to make this API request. """ body = { "requests": [ { "updateSheetProperties": { "properties": {"shee...
12,494
def get_float(data, index): """get a float value from data array""" return struct.unpack('f', "".join(map(chr, data[4*index:(index+1)*4])))[0]
12,495
def gelu(tensor): """ Gaussian Error Linear Unit - https://arxiv.org/abs/1606.08415 """ return 0.5 * tensor * (1 + tf.tanh(tf.sqrt(2 / np.pi) * (tensor + 0.044715 * tf.pow(tensor, 3))))
12,496
def make_links_in_program(): """ Make the talk titles in the program link to description pages, as far as we can, anyway. The rest should be done by hand by making use of the descriptions.index.md. Beware, this is ugly, and makes all kinds of assumptions about how the program table is formatted...
12,497
def _uniqueElements(an_iterable): """ :param iterable an_iterable: :param int idx: :return list: has only one occurrence of each element """ used = [] unique = [x for x in an_iterable if x not in used and (used.append(x) or True)] return unique
12,498
def guestbook_key(guestbook_name=None): """Constructs a Datastore key for a Guestbook entity with name.""" return ndb.Key('Guestbook', guestbook_name or 'default_guestbook')
12,499