content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
async def async_get_entry_scenes(entry: ConfigEntry, api): """Get the scenes within an integration.""" try: return await api.scenes(location_id=entry.data[CONF_LOCATION_ID]) except ClientResponseError as ex: if ex.status == HTTP_FORBIDDEN: _LOGGER.exception( "Unab...
ef97e7c181cefe13ea1b71393d81e13d4d5f8b2f
40,300
import logging def _get_areas(params, feature_names): """Returns mapping between areas and constituent feature types.""" areas = {} for feature_id in range(len(params)): feature_info = params[feature_id] feature = feature_info["ID"] area = feature_info["Area"] if area not in areas: areas[a...
937797d7634ac6cd73af941c783f26d5a8028b4d
40,301
def rbf_spectrum_dc(w: np.ndarray, c: np.ndarray, d: np.ndarray) -> np.ndarray: """Evaluate the RBF spectrum derivative w.r.t. c. Args: w: The (dimensionless) frequencies at which to evaluate the power spectrum, of shape (n, ). c: An unconstrained parameter representing ...
8486d4dff592b093a520824d4f361745ad60b435
40,302
def render_colors(vertices, triangles, colors, width, height, channels=3, bg=None): """ Adds color to 3D face vertices. See https://github.com/YadiraF/face3d. """ if bg is None: img = np.zeros((height, width, channels), dtype = np.float32) else: assert bg.shape[0] == height and b...
670222fc1f5886698db3dca7f0179a4b5f78fdb6
40,303
def acceptanswer(request): """ 采纳问题 :param request: :return: """ answer_id = request.POST.get('answer_id') answer = Answer.objects.filter(id=answer_id).first() if request.user != answer.question.user and request.user != answer.user: # 保证采纳人一定是问题的提问者,而且不能自己采纳自己 return JsonRespons...
eedf5fcb45fd06c45ec323bbb0eaebba5b9386bc
40,304
import numpy def calc_m_sq_cos_sq_para(tensor_sigma, flag_tensor_sigma: bool = False): """Calculate the term P2 for paramagnetic sublattice. For details see documentation "Integrated intensity from powder diffraction". """ sigma_13 = tensor_sigma[2] sigma_23 = tensor_sigma[5] p_2 = numpy....
910087c34ffc5ec43376fbdbc6368761fb4580ee
40,305
import time import resource def main(samples, chunksize=1, num_workers=None): """Main application """ len_samples = len(samples) time_start = time.perf_counter() firstPerson = FirstPersonMR(num_workers, chunksize) freq = firstPerson.frequency(samples) time_elapsed = (time.perf_counter()...
c75f34ea058deab86998bfdb1e51a5746f24d70c
40,306
import mpmath def cdf(x, loc=0, scale=1): """ CDF of the logistic distribution. """ with mpmath.extradps(5): x = mpmath.mpf(x) loc = mpmath.mpf(loc) scale = mpmath.mpf(scale) z = (x - loc) / scale p = (1 + mpmath.tanh(z/2)) / 2 return p
395b33c9364fb279504088d0f515900c70c5ad4f
40,307
def as_observer(self): """Hides the identity of an observer. Returns an observer that hides the identity of the specified observer. """ return AnonymousObserver(self.on_next, self.on_error, self.on_completed)
54e0493ebf4b885c831dd36b475b061c355e4708
40,308
def main(kw=False): """ main method to build ast tree and call subseq functions Top level check license info scan for class - class check scan for function - function check """ try: f = open(sys.argv[1]) except IOError: print "Can't find {}".format(sys.arg...
543e44a462c17bd1cd7bc7191e72e9dfb9fe47d8
40,309
def swarmbox(df, parameter, stat_table, hue=None): """ Graph boxplot of a category, with each individual point :return: matplotlib figure """ fig, ax = plt.subplots() sns.swarmplot(x='Arm', y="Difference of "+parameter, data=df, ax=ax, palette=sns.crayon_palette(['Vivid Violet'...
02373a500ae48b71a4839c7e64717d2d7069e817
40,310
import os def get_files(asset="images", url=False): """Returns list of files in the uploads/images directory""" path = f"{current_app.config['UPLOADS_DEFAULT_DEST']}/{asset}" if not os.path.exists(path): os.makedirs(path) files_list = os.listdir(path) try: files_list.remove("data")...
2dc8f3d79b63d2f1f4ab32f606173f0ddcae9c69
40,311
def create_qrcode(id_list, ctime, qrtype, pay_id): """ :param bid:表示书籍的唯一id,用isbn号码 :param ctime: 创建时间,一分钟后过期 :param type: 二维码类型 :return: """ qr = qrcode.QRCode( version =1, error_correction = qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) ...
051872c8103ed371da69221a7ef5f254e2606375
40,312
def load(file): """ Load an ontology from a .obo file. """ return OBOOntology(file)
383cff1a4e1b93e0726c2bfb43413fa2f6c0b3e5
40,313
def transform_seed_objects(objects): """Map seed objects to state format.""" return {obj['instance_id']: { 'initial_player_number': obj['player_number'], 'initial_object_id': obj['object_id'], 'initial_class_id': obj['class_id'], 'created': 0, 'created_x': obj['x'], ...
685c0c5b22fdff108311338354bb42fb53fd07f6
40,314
def _eigh_work( H, V=None, precision=lax.Precision.HIGHEST, termination_size=128): """ The main work loop performing the symmetric eigendecomposition of H. Each step recursively computes a projector into the space of eigenvalues above jnp.mean(jnp.diag(H)). The result of the projections into and out of that...
fcf54c43c652a6c04b8313bbab79ffdce429a3be
40,315
def get_cost_center(vehicle): """ this is used to return cost center """ cost_center = frappe.get_value("Vehicle Details", vehicle, "vehicle_cost_center") if cost_center: return cost_center
ff090b203e6cbc670de97eb923e7cb0320dae7e2
40,316
import numpy def sample_mog(prob, mean, var, rng): """Sample from independent mixture of gaussian (MoG) distributions Each batch is an independent MoG distribution. Parameters ---------- prob : numpy.ndarray mixture probability of each gaussian. Shape --> (batch_num, center_num) mean :...
cfd6f5e843a2d92b90d87038413a78da1be1fb40
40,317
def get_weather(location): # location can be IP address, city, or ZIP """This function takes the location and outputs the current weather.""" url = f"https://api.weatherapi.com/v1/current.json?" \ f"key={weatherapi_key}&" \ f"q={location}" stats = {"temp_f": 0, "wind_mph": 0, "wind_dir"...
ad5e5bfbc81ebe0576e5afea3b8e1b522115e112
40,318
def progress_bar(t): """ from https://gist.github.com/leimao/37ff6e990b3226c2c9670a2cd1e4a6f5 Wraps tqdm instance. Don't forget to close() or __exit__() the tqdm instance once you're done (easiest using `with` syntax). """ last_b = [0] def update_to(b=1, bsize=1, tsize=None): """ ...
45b13a01ec1a55f8e2c9f8929235aec735974658
40,319
def remove_digits(text): """ Remove all digits from the text document take string input and return a clean text without numbers. Use regex to discard the numbers. """ result = ''.join(i for i in text if not i.isdigit()).lower() return ' '.join(result.split())
d9604c31391e48ab826089d39201577bdf83c2fa
40,320
async def async_setup_entry(hass, entry, async_add_entities): """Set up an Mila sensor entity based on a config entry.""" entry = hass.data[DOMAIN][entry.entry_id] conf_devices = entry[CONF_DEVICES] coordinator = entry[DATA_COORDINATOR] def get_entities(): """Get the Mila sensor entities.""...
18f5c12eeff741097b255812e1dd139fb71f904e
40,321
import os import subprocess import sqlite3 def create_local_db(path_to_db=DEFAULT_PATH_TO_DB, create_script=make_create_script()): """ Create our SQLite database ex nihilo. """ if os.path.exists(path_to_db): response = input("Overwrite dump at "+path_to_db+"? (y/n)\n") if r...
bb3a8e7fcec548f399f8deca06fb8226a11d08bd
40,322
def _ipaddr(*args, **kwargs): """Fake ipaddr filter""" return "ipaddr"
8550ebc305442620e57d9b164d6751c1a16b4ef6
40,323
def hlab_to_xyz(hlab: Vector, white: VectorLike) -> Vector: """Convert Hunter Lab to XYZ.""" xn, yn, zn = alg.multiply(util.xy_to_xyz(white), 100, dims=alg.D1_SC) ka = CKA * alg.nth_root(xn / CXN, 2) kb = CKB * alg.nth_root(zn / CZN, 2) l, a, b = hlab l /= 100 y = (l ** 2) * yn x = (((a...
e4747b034bc7cae858ed38b0671292c6990c97be
40,324
import os def which(cmd, mode=os.F_OK | os.X_OK, path=None): """Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result of os.environ.get("PATH"), o...
db1cbd2a299f42cc20ccaaad91b6a71f32112a01
40,325
from pathlib import Path def get_cache_path() -> Path: """Returns data root folder.""" return get_data_path() / Path('cache')
461765d615827917124a201968f68430821daa02
40,326
def create_temporary_file( file_contents: str, suffix: str = '.txt' ) -> NamedTemporaryFile: """Create a temporary file with an explicit name from a given string.""" file = NamedTemporaryFile(suffix=suffix) file_contents_bytes = str.encode(file_contents) file.write(file_contents_bytes) file....
dd9d3fb68054aa01d1dd6520b326df52a6dbeeaa
40,327
import pickle def load_CIFAR_batch(filename): """ load single batch of cifar """ with open(filename, 'rb') as f: datadict = pickle.load(f, encoding='latin1') X = datadict['data'] Y = datadict['labels'] X = X.reshape(10000, 3, 32, 32).astype('float32') Y = np.array(Y) ...
f78f29e53aaebf6b25f3d2c84710e7ee9d0d1ebb
40,328
def one_minus_exp(x): """Returns 1-exp(x). Useful for probability calculations.""" if abs(x) < log_epsilon: return -x else: return 1 - exp(x)
6b62d053dcb034ccbdd466a59bbe2c31a05174fc
40,329
from typing import List from typing import Tuple def get_diff_text(text1: List[str], text2: List[str]) -> List[Tuple[int, str]]: """ Take the alignment between two lists and get the difference. """ orig_words = '\n'.join(text1.split()) + '\n' pred_words = '\n'.join(text2.split()) + '\n' diff ...
272c108cd97dbb73b637077ee6991bade8d209a4
40,330
def get_client(service_name, sandbox=False): """ Return a client for a given service. The `sandbox` argument should only be necessary if a the client will be used to make a request. If it will only be used to serialize objects, it is irrelevant. A caller can avoid the overhead of determining the sa...
62575d4aebfa049a5dae2a4c9cbd8ec9755a1616
40,331
import os import requests import json def submit_project_to_runbiosimulations(name, filename_or_url, simulator, simulator_version='latest', cpus=1, memory=8, max_time=20, env_vars=None, email=None, ...
a673312ebc1590aeba6ffa6ae45f4ba6fedb5637
40,332
def encrypt(key, text): """ Encrypt a message using the public key, for decryption with the private key """ retval = b"" i = 0 txtl = len(text) ks = int(key.key_size / 8) - 64 # bits -> bytes, room for padding # Process data in chunks no larger than the key, leave some room for padding. whil...
90f97851a508fdf6c60b66ba9d40a8b4efd8975d
40,333
def _DecoderBlock(positions, d_model, d_ff, n_heads, dropout, mode): """Returns a layer sequence representing a Transformer decoder. (acts, pos) --> (acts', pos') Args: positions: random vectors for positions d_mod...
09e6fb07e406127b57edb00c8d17668b0ffbaffe
40,334
def accumulate_spectra(n_trajectories, n_states=10, suffix='flu', n_restarts=0): """ Create the spectra_flu.input file using the nasqm_flu_*.out files """ create_spectra_inputs(suffix, n_trajectories, n_restarts, n_states) omegas_and_strengths = [open("{}_spectra/traj_{}.out".format(suffix, traj), '...
a446c1b67a224be18d16a896fd5b9d32374b5997
40,335
import os def delete_domain(name: str): """ Deletes the configuration file of the corresponding domain. :param name: The domain name that corresponds to the name of the file. :type name: str :return: Returns a status about the success or failure of the action. """ config_path = flask.cur...
04a3508ab1a5190262329485b62ee9f61d1d865a
40,336
def QueryEncode(q: dict): """ :param q: :return: """ return "?" + "&".join(["=".join(entry) for entry in q.items()])
b92aaf02b3322b3c35b8fe8d528e2e4bc6f91813
40,337
from sys import flags def _Args(parser, support_global_access, support_l7_internal_load_balancing, support_gfe3, support_l7_rxlb, support_psc_google_apis, support_all_protocol, support_target_service_attachment, support_l3_default, support_source_ip_range): """Add the flags to create a...
cefd97a94cb7fd9b4d0861841efdadde63814dee
40,338
import re def _fast_suggest(term): """Return [] of suggestions derived from term. This list is generated by removing punctuation and some stopwords. """ suggest = [term] def valid(subterm): """Ensure subterm is valid.""" # poor man stopwords collection stopwords = ['and',...
f4790e22abae7b33ee5585ea4a21189d7954cf40
40,339
def urlparse(urlstring, scheme='', allow_fragments=True, *args, **kwargs): """A wrapper for :py:func:`urlparse.urlparse` with the following differences: * Handles buckets in S3 URIs correctly. (:py:func:`~urlparse.urlparse` does this correctly sometime after 2.6.1; this is just a patch for older ...
fdf057450105724dafe7255486af07bf32576878
40,340
def ind2ij(a,index): """ returns a[j,i] for a.ravel()[index] """ n,m = shape(lon) j = ceil(index/m).astype(int) i = remainder(index,m) return i,j
5aa4606466db3a62727e39f741d6454a4df6c3e3
40,341
import torch def recording(matrix, v1, v2, v3, v4, v5, NC=None): """ recording matrix with row [fx, gx, oracle-calls, time, step-size, direction-type] and iteration as columns """ v = torch.tensor([v1, v2, v3, v4, v5], device = matrix.device) if NC is not None: if NC == 'NC': ...
2a4271865db212c7deae1fa49700915d59a2da2d
40,342
def build_res_u_net(n_input=1, n_output=2, size=256, arch="resnet18", pretrained=True): """First pretraining step for generator -> Use a pretrained U-Net Args: n_input: Image input dimension n_output: Image output dimension size: arch: pretrained: Returns: (...
2ddab2e6a9e40c6c982c0f10f07b61fbf769ccb9
40,343
def get_mig_identification(system: System) -> str: """ Returns string of GPU & subsequent MIG instance identification. Also checks if MIG is enabled and the MIG configuration is homogeneous. Return string omits how many MIG instances are populated. Args: system (System): The sys...
93a1393409187ec5e07808b87d3bb56e8d010fe0
40,344
def get_unmasked_indices(nc): """Make boolean array for converting to lat/lon pairs. Geographic data in gridded dataset often contains many datapoints over oceans that are not of current interest. Therefore it can be useful instead of dealing with a 2D grid of lat/lon values to instead use a 1D lis...
9383f9062db89c3fd04743de01bc69a32d4b6894
40,345
def normalize(text): """ Lemmatize tokens and remove them if they are stop words """ text = nlp(text.lower()) lemmatized = list() for word in text: lemma = word.lemma_.strip() if (lemma and lemma not in SW ): lemmatized.append(lemma) return lemmatized
a02185995b9bedb804cef7586372a9f4d65d84f1
40,346
def instance_digital_object(ref: str) -> dict: """ ``` { 'instance_type': 'digital_object', 'digital_object': {'ref': ref} } ``` """ return { 'instance_type': 'digital_object', 'digital_object': _ref(ref) }
be4b6d559972e6d828266035d853d1cb88bf2d80
40,347
import os def download_gradle_files( repo_name: str, github: GradleFileSearcher, outdir: str) -> bool: """Download gradle files from repository. All files will end up in subdirectories of the following template: <outdir>/<repo_name>/<path_in_repo>/build.gradle :param str repo_name: I...
929004b2c6302f4a9d06d552deef33f7a3737c04
40,348
def _transform_track(track): """Transform result into a format that more closely matches our unified API. """ large_artwork = None medium_artwork = None small_artwork = None if track['artwork_url']: large_artwork = (track['artwork_url']).replace('large', 't500x500') medium_a...
d27920b535f43f04c01afe5d7e5aa4337afb6682
40,349
def fwhm(t_r, hrf): # pragma: no cover """Return the full width at half maximum of the HRF. Parameters ---------- t : array, shape (n_times_atom, ), the time hrf : array, shape (n_times_atom, ), HRF Return ------ s : float, the full width at half maximum of the HRF """ peaks_i...
bed3b9e23507852bc7f20e63eca21a57524b0383
40,350
def subtoken_cnn_encoder(*, namespace, inputs, padding_size, subtoken_vocab_size, token_lengths, num_filters=30, kernel_size=3, subtoken_embedding_size=256, padding='same', activation='tanh', strides=1): """ Helper m...
93544892f67cf9fb01eeea84d74243726a94158b
40,351
import copy def brute_permutation(A, B): """ Re-orders the input atom list and xyz coordinates using the brute force method of permuting all rows of the input coordinates Parameters ---------- A : array (N,D) matrix, where N is points and D is dimension B : array (N,D) mat...
58d36f0cc33ed8b7f690b17349359401fdf8ee84
40,352
async def vector_bsgn_2(x): """Compute bsgn_2(a) for all elements a of x in parallel.""" stype = type(x[0]) n = len(x) await mpc.returnType(stype, n) Zp = stype.field p = Zp.modulus legendre_p = lambda a: gmpy2.legendre(a.value, p) s = mpc.random_bits(Zp, 6*n, signed=True) # 6n random ...
3c619c75e5cb6ca9b8897477cd08ecd39a4876bf
40,353
def barlamdel_to_kappal(q, barlaml, ell): """ $\kappa^{A,B}_\ell(\bar{\lambda}_\ell)$ Assume $q=M_A/M_B>=1$ """ XA = q/(1.+q); XB = 1. - XA; blamfact = factorial2(2*ell-1) * barlaml; p = 2*ell + 1; kappaAl = blamfact * XA**p / q; kappaBl = blamfact * XB**p * q; return kapp...
c446c9c51141df9eded3505191bc0875ac6ddc0f
40,354
def index(): """index""" return "Hello HBNB!"
0f71803268e47ec64aa358ef71fc89d4beb04e49
40,355
def remove_duplicates(objects, equiv=None, tol=1e-12): """Remove duplicate objects from a list of objects. Parameters ---------- objects : list of objects A list of objects, with possible duplicates. equiv : function, optional A function for checking equality of...
712f7e71acab2564ea7652e899ae28ec671dd3e1
40,356
def upload_blueprint(archive, blueprint_id, blueprint_file): """execute cfy blueprints upload create :param archive: the URL or path to a blueprint :param blueprint_id: the blueprint ID :param blueprint_file: the filename of the blueprint YAML :type archive: string :type blueprint_id: string ...
f6a8a12f32d0852556c7cb575b271647a6fee415
40,357
def yolo_head(feats, anchors, num_classes): """Convert final layer features to bounding box parameters""" num_anchors = len(anchors) # reshape to batch, height, width, num_anchors, box_params anchors_tensor = K.reshape(K.variable(anchors), [1, 1, 1, num_anchors, 2]) # dynamic implementation of conv ...
69834f8fbaf4c34187cc9e33dbbc889902efcc20
40,358
def _extract_neighbors (command): """return a list of neighbor definition : the neighbor definition is a list of string which are in the neighbor indexing string""" # This function returns a list and a string # The first list contains parsed neighbor to match against our defined peers # The string is the command to...
c1ea91cc1dbdbcaad608e59d3f176eb4623b8714
40,359
def intrinsic_to_opengl_projection(intrinsic_mat, left, right, top, bottom, near, far): """ Converts intrinsic matrix to OpenGL format. :param intrinsic_mat: Intrinsic matrix in row-major order. :return: OpenGL perspective mat (including NDC matrix) in column-major ...
27e2390d67e522545bbf2694888cdf8a4689bff9
40,360
def makeNullRow(df, null=np.nan): """ Creates a row of null values to the dataframe. :param object null: value in row :return dict: row """ row = {} for column in df.columns.tolist(): row[column] = null return row
d3b07278338551c83fc1c0c19902a2687c01d6e1
40,361
def character_embedding_network(char_placeholder: tf.Tensor, n_characters: int = None, emb_mat: np.array = None, char_embedding_dim: int = None, filter_widths=(3, 4, 5, 7), ...
51dc28ee085be66714eae1aa55d13deaea595db9
40,362
def instrument_altitude_to_model_pressure(inst, model, inst_name, mod_name, mod_datetime_name, mod_time_name, mod_units, inst_alt, mod_alt, mod_alt_units, scale=100., ...
770f93ee64dc327e8009dfea36fbcd728581acb5
40,363
def _cast_list_by_data_type(field_type, list_values): """ 将list结构的python数据转换为java能识别的数据类型 :param field_type: 字段类型,小写字符 :param list_values: list数据 :return: java能识别的数据类型构成的数组 """ if isinstance(list_values, list): return [_cast_value_by_data_type(field_type, value) for value in list_val...
a89aefb748b41ceecdd7a9b8820b84cdc7c2432d
40,364
def fixture_perform_migrations_at_unlock(): """Perform data migrations as normal during user unlock""" return False
a8a8ae9118b2de4f0cdbb7ba3e39fdd7a552f77b
40,365
def svn_repos_fs_begin_txn_for_update(*args): """svn_repos_fs_begin_txn_for_update(svn_repos_t * repos, svn_revnum_t rev, char const * author, apr_pool_t pool) -> svn_error_t""" return _repos.svn_repos_fs_begin_txn_for_update(*args)
5b75795deb05894c8cf9bc51fa59901df6592165
40,366
import torch def generate_rays_th(pixel_coords, pix2cam, cam2world): """Generate camera rays from pixel coordinates and poses. Args: pixel_coords: [width, height, 2] pixel-space coordinates. pix2cam: [*batch, 3, 3] batched inverse intrinsic matrix. cam2world: [*batch, 3+, 4] batc...
132f87095b2258bdf812d8dfb6487d019383f7c8
40,367
def translate_push(x): """Converts list.push(v1, v2, ....) to __ee_extra_push(list, v1, v2, ...) Args: x (str): JavaScript code to translate. Returns: str: Translated JavaScript code. Examples: >>> from ee_extra import translate_push >>> text = '["Banana", "Orange", "A...
12aa97d7ab018021002d220b8fe8048cd7bf4290
40,368
def _check_and_fix(span_token_tup, span_drange, pred_field, complementary_field2ents): """ check if span_token_tup is in complementary_field2ents and fix result Returns: bool: if span_token_tup is in complementary ents span_token_tup: fixed result span_drange: fixed drange """ ...
b3a8d0b75675f15c7dd857d2fb28e8713da330fe
40,369
def perp( vector ): """ returns a vector perpendicular to the input. the vector will lie in the x=y plane. """ perpvector = np.array([1,1,-(vector[0] + vector[1])/vector[2]]) return perpvector/np.sqrt(np.sum(perpvector**2))
7d79be3bb167364b079cc2d6a7c1afa9fd99a561
40,370
def worker_history(request): """ 跳转到工作经验证明的页面 :param request: :return: """ return report.worker_history(request)
aff9249e908168742914aca90dbddb023c5db908
40,371
def generate_post_id() -> int: """This function creats a new directoy inside posts with post id and returns it. :rtype: int """ max_post_id = 0 for i in get_post_ids(): if i > max_post_id: max_post_id = i post_id = max_post_id + 1 post_path = get_post_path(post_id)...
ffb638af40a815c1a5950d2c12f0ea9b76f6ff75
40,372
from pathlib import Path def getFileAbsolutePath(rel_path): """ Retorna o caminho absoluto de um arquivo a partir de seu caminho relativo no projeto :param rel_path: :return: absolute_path """ data_folder = Path("PythoWebScraper/src") file_to_open = data_folder / rel_path return file_...
b39baaa26e3c8a7c7a8c41dbb4fafceb7ca78c70
40,373
import re import warnings def plot( df_in, x=None, y=None, kind="line", figsize=None, use_index=True, title="", grid=None, # TODO: legend="top_right", logx=False, logy=False, xlabel=None, ylabel=None, xticks=None, yticks=None, xlim=None, ylim=None, ...
1223e79850d8880a5eee06624cc89707d4b6b30c
40,374
def _make_section_data(section, unique_sequences): """ Return a (CourseSectionData, List[ContentDataError]) from a SectionBlock. Can return None for CourseSectionData if it's not really a SectionBlock that was passed in. This method does a lot of the work to convert modulestore fields to an input ...
a62e03222f8b3f04e6f8cc10d4c7531662b321ad
40,375
from typing import Optional from typing import Mapping def get_connection(id: Optional[str] = None, tags: Optional[Mapping[str, str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetConnectionResult: """ This data source can be used to fetch informatio...
69087603bd5b58e97f8370299f63516863610af3
40,376
def prepend_token(x_BxLxE, embed_VxE, token_id): """Prepend token_id embedding to a batch of sequence tensors. Args: x_BxLxE: sequence tensor embed_VxE: embedding matrix token_id: token to prepend Returns: x_Bx(L+1)xD tensor """ first_1xE = tf.nn.embedding_lookup(embed_VxE, [token_id]) fir...
f1fa10ed877deeab6880a1583fdf070f95e39f51
40,377
def residual_block(inputs, num_blocks): """ Applies several residual connections. Args: inputs (tf.Tensor): 4D (N,H,W,C) input tensor num_blocks (int): Number of residual blocks Returns: tf.Tensor: 4D (N,H,W,C) output Tensor """ _, _, _, filters = inputs.shape x = i...
f42544a2c38151206cfd771b952a6491273b4a1c
40,378
def make_links(existings, versions): """ With the maping file-url<->existing-version create a mapping file-url<-> Other-Url if exist, other url is replaced by index.html if said page does not exits. """ links = defaultdict(lambda: {}) for k, ve in existings.items(): for v in versions...
8cdda077bdd5419b976c9b45ad3d267b7c8c9b5a
40,379
def _add_update_associate_key( node, weight_key: Account, key: Account, weight: int, contract: str ): """ Handles both add and update calls due to commonality """ session_args = ABI.args( [ABI.account(bytes.fromhex(key.public_key_hex)), ABI.u32(weight)] ) return node.deploy_and_propose( ...
ab20cb4215b126278f60fb735fee2902d6702aae
40,380
def get_unacked_triggers(config): """Retrieves the unacked triggers from Zabbix. :param config: config for zapi :type config: dict :return: list of triggers """ zapi = init(config) all_triggers = zapi.trigger.get(only_true=1, skipDependent=1, ...
e02391b3622bdaad30d64799743be30a9311833b
40,381
def passwd_hash(p): """Hashing password and convert it to hex number password in range from 6 to 40 char's""" return sha256(p.encode('utf-8')).hexdigest()
5ed22f70405e716b69333947e05b93b320aa864d
40,382
import requests def generate_text(query, genre): """ Функция отправляет POST-запрос к Балабобе, и получает ответ в виде словаря. Параметры POST-запроса: query: ключевая фраза genre: id жанра, в котором Балабоба должен сгенерировать текст """ text_url = 'https://zeapi.yandex.net/lab/api...
467c40145db532f912ba2d17ad3ba588273fa682
40,383
def read_batch(filename, batch_size, random=False): """ Read single batch. """ context_features = { "lcl": tf.FixedLenFeature([], dtype=tf.int64), "rcl": tf.FixedLenFeature([], dtype=tf.int64), "eml": tf.FixedLenFeature([], dtype=tf.int64), "uid": tf.FixedLenFeature([], d...
4e4c73f4ff86d46e8ffb21dc8c18145512a33fc3
40,384
import json def delete_flowentry(fields, ip=DEV_VM_URL): """ Deletes a flowentry by using OVS REST API, flowentry is matched based on the information in `fields` """ url = "http://%s:%d/stats/flowentry/delete_strict" % (ip, OF_REST_PORT) data = json.dumps(fields) return _ovs_api_request('...
5e6f421b757e99d12b07025cc687d4633ede792c
40,385
from typing import Dict import os import re def all_snippets_from_file(sample_file: str) -> Dict[str, str]: """Reads in a sample file and parse out all contained snippets. Args: sample_file (str): Sample file to parse. Returns: Dictionary of snippet name to snippet code. """ if n...
d970df8e36bff538e2a820b2f57bfecad83312b0
40,386
def directive_exists(name, line): """ Checks if directive exists in the line, but it is not commented out. :param str name: name of directive :param str line: line of file """ return line.lstrip().startswith(name)
eb69044de8860b1779ce58ef107859028b8c98cf
40,387
import timeit def search_set(n): """Search for an element in a set. """ my_set = set(range(n)) start = timeit.default_timer() n in my_set # pylint: disable=pointless-statement return timeit.default_timer() - start
f0d8ba45df45130cc81d70e2d391825ed46dc93e
40,388
def get_state(address): """Getting the server state directly from remote queue""" c = Client(address=address) try: return c.request('get_state', {}) except Exception: logger.warn('error getting state', exc_info=True)
7dbdf5538c704062a1c3c9d3db2a235f3e5408c9
40,389
from sphinx.io import SphinxStandaloneReader def setup(app): # type: (Sphinx) -> dict """Initialize Sphinx extension. Notes ----- TODO better latex output but not really interested in this as it would be duplication of effort, and if much better todo ipynb -> tex, rather than ipynb -> r...
5b80bf6c3cce88edbd072a0122d23329fd6c047a
40,390
import os def sweepnumber_fromfile(fname): """Returns the sweep number of a polar file based on its name""" return int(os.path.basename(fname).split('.')[1])
4648bfcf10ea0645266109a5c0ab1a7e41ffe46d
40,391
import time def format_time(): """Return a time in YYYY-mm-dd HH:MM:SS formatting.""" return time.strftime("%Y-%m-%d %H:%M:%S")
46788fdfb6221829bccfb817603a59992ea0f1c4
40,392
import os import subprocess import traceback import re import telnetlib def get_devices(): """Gets a list of devices currently attached. Querys `adb` from `get_sdk_dir()` for all emulator/device instances. Returns: A tuple of lists. The first value is a list of device ids suitable for us...
f8fa79f3055e836d44c5969220c6a707279f4568
40,393
from typing import Optional from typing import Callable def apply2( ff: Optional[Callable[[A_in, B_in], C_out]], fa: Optional[A_in], fb: Optional[B_in] ) -> Optional[C_out]: """ Given two values and a function in the :class:`Optional` context, applies the function to the values. ...
136f7da8162e41d6d200000035e2bfeb5336d061
40,394
def show_graph(graph: GraphDict, size: str = None, simplified: bool = False): """ Show graphical representation of a graph as required by :py:func:`transform_coords` Requires `python-graphviz` package. :param graph: Transformation graph to show. :param size: Size forwarded to graphviz, must be...
4e7c851deb0c76e6872aae09645b816bf7d02b57
40,395
import os import subprocess def add(printer_name, uri, ppd, location, description): """ Add a new printer to the system with the given parameters. """ try: if ppd[:4] == 'drv:': type = '-m' else: type = '-P' with open(os.devnull, "w") as fnull: ...
8066f5ba76fc039efd5dc4a3f53fa84c28b825c7
40,396
import trace from functools import reduce def build_prediction(tracefile_lines, src, dst): """ Provided tracefile data in nstrace format, predict if dst node will fall out of range from src. """ tcp_packet_size = 1000 prediction = {} throughput_history = [] avg_throughput_history = 0 ...
ab78c2e0cd6dc54db9438b3d0421c1c92ef0cdbd
40,397
def unitSpacing2MM(unit): """ Converts KLE unit spacing into wxPoint spacing. Used in placing KiCAD components """ unitSpacing = 19.050000 wxConversionFactor = 1000000 return unit*unitSpacing
2cc137b7db7a8b1871a7329fa482351fd52ed544
40,398
def test_conformer(species, conf, natom, atom, mult, charge, ts = 0, ring = 0): """ Test whether a conformer has the same bond matrix as the original structure. Returns the conformer object and -1 if not yet finished, 0 if same, and 1 if not. """ r = '' if ring: r = 'r' if ts: j...
a6303a60d8286fd5fe81af722b20d7c6c3fdb20e
40,399