content
stringlengths
22
815k
id
int64
0
4.91M
def find_(a,n=None,d=None,nargout=1): """ function which returns a column vector or a tuple of column vectors (depending on the value of nargout) containing indices where a[indices] are true in the vector/matrix 'a' Argument 'n' tells us how many of those indices we want """ if d: r...
5,288,200
def __covid_brief() -> str: """ Generates a brief message about the latest covid19 data. """ try: ( is_latest_covid_data_available, _, new_cases, cumulative_cases, new_deaths, cumulative_deaths, ) = fetch_covid_data...
5,288,201
def correct_for_absorption(flux, ebv, band): """Corrects for MW dust absorption. Keyword arguments: flux -- Python list containing fluxes. ebv -- float, MW E(B-V). band -- photometric band in which correction has to be applied. Returns: Python list containing values of flux corrected by ab...
5,288,202
def flag_bad_words(transcriptions): """ :params transcriptions:transcriptions is the dictionary containing the text file that has been converted into an array :return: updated transcriptions dictionary This function checks to see if any words have been added to the flagged_list. """ if any(flag...
5,288,203
def draw_rivers_on_image(world, target, factor=1): """Draw only the rivers, it expect the background to be in place """ for y in range(world.height): for x in range(world.width): if world.is_land((x, y)) and (world.layers['river_map'].data[y, x] > 0.0): for dx in range(f...
5,288,204
def test_emphasis_446(): """ Test case 446: (part 2) Rule 11 """ # Arrange source_markdown = """foo *\\**""" expected_tokens = [ "[para(1,1):]", "[text(1,1):foo :]", "[emphasis(1,5):1:*]", "[text(1,6):\\\b*:]", "[end-emphasis(1,8)::]", "[end-para...
5,288,205
def update(id_: int, type_: str, object_: Dict[str,str], session: scoped_session, api_name:str) -> int: """Update an object properties based on the given object [PUT].""" # Keep the object as fail safe instance = get(id_=id_, type_=type_, session=session, api_name=api_name) instance.pop("@id") ...
5,288,206
def extend_cpp_with_app(args): """Extend CMAKE_PREFIX_PATH with AMENT_PREFIX_PATH.""" warnings.warn( 'colcon_ros.task.extend_cpp_with_app() will be removed in the future', DeprecationWarning, stacklevel=2) ament_prefix_path = os.environ.get('AMENT_PREFIX_PATH') if ament_prefix_path: ...
5,288,207
def method_resolve_vessel(cookie, in_stimuli): """ Auto-generated UCS XML API Method. """ method = ExternalMethod("MethodResolveVessel") method.cookie = cookie method.in_stimuli = in_stimuli xml_request = method.to_xml(option=WriteXmlOption.DIRTY) return xml_request
5,288,208
def get_month(): """Fetch the value of month entered by user""" # Creating a single item list for appending to global list of months all_filter = ['all'] while True: # Get user input for month (all, january, february, ... , june) month = str(input('\nSelect the month - january, febr...
5,288,209
def ZA( particle ) : """ Uses ZAInfo to compute the particle ZA. See ZAInfo for more detail """ return( ZAInfo( particle )[2] )
5,288,210
def get_category(category_id: TicketCategoryID) -> TicketCategory: """Return the category with that ID, or raise an exception not found.""" category = find_category(category_id) if category is None: raise ValueError(f'Unknown ticket category ID "{category_id}"') return category
5,288,211
def yarn_check(file_list): """ Checks if package.json was modified WITHOUT a corresponding change in the Yarn lockfile. This can happen if a user manually edited package.json without running Yarn. This is a user prompt right now because there ARE cases where you can touch package.json without a Yar...
5,288,212
def test_serializer(base_app): """Test the SecretLinkSerializer.""" with base_app.app_context(): serializer = SecretLinkSerializer() tkn_str = serializer.create_token( obj_id="someid", extra_data={"hello": "world"} ) tkn_str2 = serializer.create_token( obj...
5,288,213
def abbreviated_interface_name( interface: str, addl_name_map: Optional[Dict[str, str]] = None, addl_reverse_map: Optional[Dict[str, str]] = None, ) -> str: """Function to return an abbreviated representation of the interface name. :param interface: The interface you are attempting to abbreviate. ...
5,288,214
def edits1(word): """ Produces a list of all possible edits of a given word that can be produced by applying a single character modification. From Peter Norvig, see http://norvig.com/spell-correct.html. """ letters = 'abcdefghijklmnopqrstuvwxyz' splits = [(word[:i], word[i:]) for ...
5,288,215
def highway(input_, size, num_layers=1,scope='Highway'): """Highway Network (cf. http://arxiv.org/abs/1505.00387). t = sigmoid(Wy + b) z = t * g(Wy + b) + (1 - t) * y where g is nonlinearity, t is transform gate, and (1 - t) is carry gate. """ # return linear(input_, size) with tf.variabl...
5,288,216
def lst_mp_equality(lst1, lst2): """Wrapper function to check if two lists are identical when the lists contain MeasurementProcess objects.""" assert len(lst1) == len(lst2) lsts_same = True for index in range(len(lst1)): if not isinstance(lst1[index], type(lst2[index])): # if they are diff...
5,288,217
def end_scene(command): """ tests if the end scene command is running properly """ namespace = app.main(command) assert namespace.command == 'es' or namespace.command == "endscene" if "test" in command: assert namespace.name == "test"
5,288,218
def test_update_release_service(db, clients, user_group, allowed): """ Test the update mutation. """ client = clients.get(user_group) release_service = ReleaseServiceFactory(enabled=False) resp = client.post( "/graphql", data={ "query": UPDATE_RELEASE_SERVICE, ...
5,288,219
def asv_uncertain(unc, apf, fm): """Load Maribot Vane performance data.""" perf = np.genfromtxt(pyroute_path+"analysis/asv_transat/maribot_vane.csv", delimiter=",") tws = np.array([0, 4, 8, 12, 16, 20]) twa = np.array([0, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160]) return ...
5,288,220
def flow_resize(flow, out_size, is_scale=True, method=0): """ method: 0 mean bilinear, 1 means nearest, 2 bicubic and 3 area See: https://www.tensorflow.org/api_docs/python/tf/image/ResizeMethod """ flow_size = tf.to_float(tf.shape(flow)[-3:-1]) flow = tf.image.resize_images(flow, out_si...
5,288,221
def center_crop(img, dim): """Returns center cropped image Args:Image Scaling img: image to be center cropped dim: dimensions (width, height) to be cropped from center """ width, height = img.shape[1], img.shape[0] # process crop width and height for max available dimension crop_width =...
5,288,222
def ae_latent_softmax(latents_pred, latents_discrete, hparams): """Latent prediction and loss.""" vocab_size = hparams.v_size if hparams.bottleneck_kind == "semhash": vocab_size = 2**hparams.z_size if hparams.num_decode_blocks < 2: latents_logits = tf.layers.dense(latents_pred, vocab_size, ...
5,288,223
def test_updates(): """ """ # Check that your gradient is being calculated correctly # Check that your loss function is correct and that # you have reasonable losses at the end of training # load data with default settings X_train, X_val, y_train, y_val = utils.loadDataset(f...
5,288,224
def ellipse_axis_length( a ): """ Parameters ---------- a : fitted_ellipse_obj Returns ---------- ellipse radii """ b,c,d,f,g,a = a[1]/2, a[2], a[3]/2, a[4]/2, a[5], a[0] up = 2*(a*f*f+c*d*d+g*b*b-2*b*d*f-a*c*g) down1=(b*b-a*c)*( (c-a)*np.sqrt(1+4*b*b/((a-c)*(a-c)))-(c+a)) ...
5,288,225
def test_sheetname_type(): """Raise error if sheet name is the wrong type.""" with pytest.raises(TypeError, match="sheetnames should be one of .+"): io.xlsx_cells(filename, 5)
5,288,226
def percentage_float(x): """ Chech whether the float is a percentage. :param x: The value to check :return: The float reprentation of the argument. :raise: argparse.ArgumentTypeError if the argument is not in [0, 100]. """ x = float(x) if x < 0 or x > 100: raise argparse.Argumen...
5,288,227
async def convSingleLottieTransparentFrames( lottieFile: LottieFile, frameSkip: int = 0, scale: float = 1, ) -> dict[str, LottieFrames]: """Convert a single lottie file to a dictionary of LottieFile.path to LottieFrames (LottieFile.data and a list of PIL.Image.Image frames) with transparency. Args: lottieFile...
5,288,228
def test_cube_io(tmp_path): """Minimal test cube geometry io, uses tmp_path.""" cube = xtgeo.Cube(ncol=5, nrow=8, nlay=3, xinc=25, yinc=25, zinc=2, values=0.0) fmu.dataio.ExportData.cube_fformat = "segy" exp = fmu.dataio.ExportData( content="depth", name="testcube", runpath=tmp_path, config=CF...
5,288,229
def _unit_variance_scale(f: np.ndarray) -> np.ndarray: """Rescales a feature to have a unit variance.""" f_nan_max = np.nanmax(f) f_nan_min = np.nanmin(f) if np.isnan(f_nan_max) or np.isnan(f_nan_min): raise ValueError('Continuous feature all missing.') if f_nan_max == f_nan_min: ret = np.full_like(f,...
5,288,230
def randles_file_writer(high_freq, low_freq, decades, solution_resistance, parallel_resistance, alpha=1, sigma='none', constant_phase_element='none', alteration=None, save_image=None, save_location='simulation_data/'): """ Function that return...
5,288,231
def get_champions_name(_id): """ this functions takes an _id and returns the associate champions name :param _id: any integer from 1 to 555. if there is a champion, it will return the name. :return: champions name """ all_champion_id = { 1: "Annie", 2: "Olaf", 3: "Galio",...
5,288,232
def fix_ssl_monkeypatching(): """ eventlet works by monkey-patching core IO libraries (such as ssl) to be non-blocking. However, there's currently a bug: In the normal socket library it may throw a timeout error as a `socket.timeout` exception. However eventlet.green.ssl's patch raises an ssl.SSLError('...
5,288,233
async def on_voice_state_update(before: discord.Member, after: discord.Member): """ Handle joining and leaving channels. The bot will automatically join the server's voice channel when a member joins. """ server = before.server channel = get_server_channel(server) if channel is None: return ...
5,288,234
def get_resources_grouped_by_domain(tech): """ Given a tech slug, this function will return all the resources for that tech grouped by domains i/p: 'python' """ return_data = {} all_resources = Resources.objects.filter(technology__slug=tech) for resource in all_resources: domains...
5,288,235
def babel_fish_dispenser(matrix1, matrix2=None, step_size=None, axis=2): """Adds an input corresponding to the running average over a set number of time steps. This helps the neural network to ignore high frequency noise by passing in a uniform 1-D filter and stacking the arrays. Parameters ---------- ...
5,288,236
def isAVersionableResource(obj): """ True if an object is versionable. To qualify, the object must be persistent (have its own db record), and must not have an true attribute named '__non_versionable__'.""" if getattr(obj, '__non_versionable__', 0): return 0 return hasattr(obj, '_p_oid')
5,288,237
def fix_variable(problem, pivot, value): """ Return a new problem that is a copy of the one provided with the pivot variable set to value This function is used for branching, and prints the selection made. """ new_problem = problem.copy() new_problem['variables'] = problem['variables']....
5,288,238
def convert_reshape(node, params, layers, node_name, keras_name): """ Convert reshape. :param node: current operation node :param params: operation attributes :param layers: available keras layers :param node_name: internal converter name :param keras_name: resulting layer name :return: ...
5,288,239
def clean_db(days_to_retain=60): """ Clean up database otherwise it gets overwhelmed with StatusCheckResults. To loop over undeleted results, spawn new tasks to make sure db connection closed etc """ to_discard_results = models.StatusCheckResult.objects.filter( time__lte=timezone.now()...
5,288,240
def main(): """Calculate top TF-IDF for a corpus of documents.""" if len(sys.argv) != 2: sys.exit("Usage: python tfidf.py corpus") print("Loading data...") corpus = load_data(sys.argv[1]) # Get all words in corpus print("Extracting words from corpus...") words = set() for filen...
5,288,241
def test_progress(arg1, arg2, kwd1, kwd2, progress): """Simple test target for submit_progress.""" return arg1, arg2, kwd1, kwd2
5,288,242
async def stick_maker_static_phlogo( text: str, image_file: Image.Image, font_path: str, image_wight: int, image_height: int) -> Image.Image: """ ph表情包模板 """ def __handle() -> Image.Image: # 处理文本主体 test_sentences = text.strip().split(maxsplit=1) white_text = test_sentence...
5,288,243
def _apply_realpath(argv): """Run "realpath" on any path-related arguments. Paths passed into the tool will be prefixed with the contents of _PATH_PREFIX. If we find an argument with this prefix, we strip out the prefix and run "realpath". Args: argv: A list of command line arguments. """ for i, arg...
5,288,244
def edit_guild_todo(guild_id: int, index: int, description: str): """Edit a to-do item from a guild's to-do list.""" todo_data = get_raw_guild_todos(guild_id) new_todo = { 'desc': description, 'time': datetime.now().strftime('%d/%m/%Y %H:%M:%S'), 'author': todo_data[index]['author'] ...
5,288,245
def transform_dict_to_kv_list(options): """ {"key": None, "key2": None} becomes 'key, key2' {"key": "\"\"", "key2": "3.5in", tocbibind: None} becomes 'key="", key2=3.5in, tocbibind' """ assert isinstance(options, dict) return ", ".join(["{}={}".format(k,v) if v is not None else k for k,v in opti...
5,288,246
def Mat(m,n): """ Build an m x n matrix (using numpy) For example: >>> Mat(2,3) array([[ 0., 0., 0.], [ 0., 0., 0.]]) """ return numpy.zeros((m,n),'d')
5,288,247
def test_visual_runtime(runtime): """ Testing AutotoolsToolchain with the msvc compiler adjust the runtime """ # Issue: https://github.com/conan-io/conan/issues/10139 settings = MockSettings({"build_type": "Release", "compiler": "Visual Studio", ...
5,288,248
def create_recycled_content_datasets(data): """Create new datasets that consume the recyclable content from recycling or waste treatment activities in the cutoff system model. In the cutoff system model, no credit is given for the production of recyclable materials. Rather, consumers get these materials with n...
5,288,249
def retrieve_observation(obsid, suffix=['FLC'], archive=False,clobber=False): """Simple interface for retrieving an observation from the MAST archive If the input obsid is for an association, it will request all members with the specified suffixes. Parameters ----------- obsid : string ...
5,288,250
def get_or_abort(model, object_id, code=404): """Get an object with his given id or an abort error (404 is the default)""" result = model.query.get(object_id) return result or abort(code)
5,288,251
def _get_shape_name(array_name, shape_name = None): """Either get shape name or create from array_name.""" return shape_name if shape_name else f'{array_name}/shape'
5,288,252
def process_author(author): """Clean the author tag""" # Remove tabs and ensure a maximum length. new_author = strip_html( author[:MAX_AUTHOR_LEN] ) return new_author.replace('\t', ' ')
5,288,253
def playGame(wordList): """ Allow the user to play an arbitrary number of hands. 1) Asks the user to input 'n' or 'r' or 'e'. * If the user inputs 'e', immediately exit the game. * If the user inputs anything that's not 'n', 'r', or 'e', keep asking them again. 2) Asks the user to inp...
5,288,254
def corpora_get_props_from_anndata(adata): """ Get Corpora dataset properties from an AnnData """ versions = corpora_get_versions_from_anndata(adata) if versions is None: return None [corpora_schema_version, corpora_encoding_version] = versions version_is_supported = corpora_is_versi...
5,288,255
async def test_listen_invalid_message_data(mock_api, ws_message_event, ws_messages): """Test websocket message data that should raise on listen.""" client = WebsocketClient(mock_api) await client.async_connect() assert client.connected ws_message = create_ws_message(ws_message_event) ws_messag...
5,288,256
def svn_repos_fs_revision_proplist(*args): """svn_repos_fs_revision_proplist(svn_repos_t * repos, svn_revnum_t rev, svn_repos_authz_func_t authz_read_func, apr_pool_t pool) -> svn_error_t""" return _repos.svn_repos_fs_revision_proplist(*args)
5,288,257
def set_vpr_context(context: str): """ activates a certain mode of vpr by copying the specific executable to the expected location :param context: the mode to activate, one of "reference", "rnn", "cnn", "cnn_no_conv" :return: nothing, modifies file system """ try: os.remove("{}.exe".form...
5,288,258
def _PD_hamming(alignA, alignB, subst, bySite, withinA, ignoreGaps=True): """Computation for pairwise diversity using a vector optimized hamming distance. Optionally ignoreGaps treats gap comparisons as Nan""" L = len(alignA.iloc[0]) gapCode = AA2CODE['-'] """Convert alignments into integer arrays ...
5,288,259
def convert_to_number(roman_numerals: str) -> int: """ Convert Roman numerals to a number Roman numerals are written from left to right, and from highest to lowest (in terms of individual numeral value) :param roman_numerals: Roman numeral to convert :type roman_numerals: str :return: numb...
5,288,260
def ensure_loaded_agent(app: Sanic, require_core_is_ready=False): """Wraps a request handler ensuring there is a loaded and usable agent. Require the agent to have a loaded Core model if `require_core_is_ready` is `True`. """ def decorator(f): @wraps(f) def decorated(*args, **kwarg...
5,288,261
def test(): """Run unit tests.""" tests = subprocess.call(["python", "-c", "import tests; tests.run()"]) sys.exit(tests)
5,288,262
def _insert_temporary_wires( context: DefinitionContext, value: ValueLike, inline_wire_prefix: str): """ Insert a temporary Wire instance so the signal isn't inlined out. We have to do this for DefnRef because the coreir inline.cpp logic sometimes inserts temporary wires for Def...
5,288,263
def test_list_reverse_first( return_list, function_fixture, class_fixture, module_fixture, session_fixture, ): """ This test checks the reverse of the list. """ return_list.reverse() assert return_list == [7, 6, 5, 4, 3, 2, 1]
5,288,264
def test_can_upload_to_collection( can_upload_to_collection_permission, collection, request_data ): """ Test for CanUploadToCollection happy path """ request_data.request.method = "POST" request_data.request.data = {"collection": collection.hexkey} collection.owner = request_data.user co...
5,288,265
def getMinUnvisited(unvisited, dist): """ return the minimum distance vertex from the set of vertices not yet processed. Parameters: unvisited (set): the set containing all the vertex not yet processed dist (dict): a dictionary with vertex as ...
5,288,266
def update_signature_source(service, name, **_): """ Update a signature source by name for a given service Variables: service => Service to which we want to update the source name => Name of the source you want update Arguments: None Data Block: { ...
5,288,267
def __permutations_generator(dictionary, const): """ Function that creates all possible permutations of arguments based on const and dict it gets. For example: const = ['--algorithm', 'Jrip'] dictionary = {'--path': ['t1.txt', 't2.txt'], '--N-jrip': ['50', '70']} ...
5,288,268
def read_sentiment_data() -> pd.DataFrame: """Convert the sentiment file into a DataFrame object Returns a DataFrame of predicted_sentiment_all_processed.csv' Returns None if paths are not valid """ try: return pd.read_csv(os.path.join(PARENT_PATH, os.path.join('d...
5,288,269
def test_interaction(): """Ensure that the method picks up a trivial interaction term.""" np.random.seed(1) N = int(1e6) nbins = 3 # This needs to be an odd number to yield an even number of edges. b = np.linspace(0, 1, N) # Mirror a around b=0.5. a_comp = np.random.random(N // 2) * 2 ...
5,288,270
def load_MSTfit_eq(shot, frame): """ Load a reconstruction from my home directory. """ fname = os.path.join(mstfit_dir, 's{0:10d}/MST_s{0:10d}_f{1:02d}.csv'.format(shot, frame)) df = pd.read_csv(fname) eq = {} eq['x'] = df['R (m)'].to_numpy() - R0 eq['y'] = df['Z (m)'].to_numpy() eq...
5,288,271
def check_geo_granularity_DS_Cons1(): """ checks if DS_Cons1_Map has geographic granularity finer than balancing area """ DS_Cons1_Map = loaders.get_parameter("DS_Cons1_Map") cond = True g_values = tuple(constant.GEO_COLUMNS.keys()) for row in DS_Cons1_Map: DS, GGRAN, TGRAN = row[:3...
5,288,272
def get_delay_map(connectivity, default_delay=0, block_delay_func=lambda b:b.delay): """ Build map between the external output ports of `connectivity` and its input ports mapping the delay along each path between those ports. Checks that all paths have matching delays. connectivity: `Connectivity` object describ...
5,288,273
def test_rgb_single_channels(): """ Check assumptions about single channel R, G, and B images. """ tif_names = [color + ".tif" for color in ["red", "green", "blue"]] fnames = [eio.path_to_example(f) for f in tif_names] rgb_parts = list() for f in fnames: with rio.open(f) as src: ...
5,288,274
def nonlin_matter_power(cosmo, k, a): """The nonlinear matter power spectrum; Mpc^3. Args: cosmo (:obj:`Cosmology`): Cosmological parameters. k (float or array_like): Wavenumber; Mpc^-1. a (float): Scale factor. Returns: float or array_like: Nonlinear matter power spectrum;...
5,288,275
def make_thumbnails(path, filename, app): """ Generate thumbnail from original image file. :param path: target path :param filename: secure file name :param app: Falsk.app :return: None """ thumb_path = os.path.join(path, 'thumbnails') thumb_full_path = os.path.join(thumb_path, filen...
5,288,276
def generate_proposed_regions(img,limit_of_proposals= 2000): """ Generate proposed regions using selective search and limits number of rectangles returned """ selective_search = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation() selective_search.setBaseImage(img) selective_search....
5,288,277
def xiHelper(x, q, E): """Helper function to the rotationally-invariant, optimal shrinkage estimator of the true correlation matrix (implemented via function optimalShrinkage of the present module). Parameters ---------- x: type derived from numbers.Real Would typical...
5,288,278
def get_ckpt_old_to_new(target_dir): """Returns ckpt names from newest to oldest. Returns [] if nothing exists""" prev_ckpt_state = tf.train.get_checkpoint_state(target_dir) all_ckpts = [] if prev_ckpt_state: all_ckpts = sorted(prev_ckpt_state.all_model_checkpoint_paths, key=natural_keys, revers...
5,288,279
def test_printer(var, to_string, children=None, is_ptr=True): """ Tests the output of a pretty printer. For a variable called 'var', this tests whether its associated printer outputs the expected 'to_string' and children (if any). Args: var (string): The name of the variable we'll print. ...
5,288,280
def configure(conf): """ Find a F# compiler, set the variable FSC for the compiler and FS_NAME (mono or fsc) """ conf.find_program(['fsc.exe', 'fsharpc'], var='FSC') conf.env.FSC = conf.cmd_to_list(conf.env.FSC) conf.env.ASS_ST = '/r:%s' conf.env.RES_ST = '/resource:%s' conf.env.FS_NAME = 'fsc' if str(conf.en...
5,288,281
def dram_cacti( origin_config_file=None, target_config_file=None, result_file=None ): """ run the cacti with input configuration, work for DRAM (DRAM size is pre-specified) """ original = open(origin_config_file, 'r') target = open(target_config_file, 'w') for entry in original: ...
5,288,282
def bootstrap_curation(new_df, reference): """ Take in an uncurated list of prescriptions and bootstrap """ candidate_generic = [] candidate_category = [] for values in new_df["possible_generic"]: best_match = find_best_match(values, curated) candidate_generic.append(best_match[0...
5,288,283
def deploy(c): """ Deploy dist to github pages using git-directory-deploy https://github.com/X1011/git-directory-deploy https://help.github.com/en/articles/user-organization-and-project-pages """ print("Deploying to github.io...") cmd = c.commands['deploy'] c.run(cmd)
5,288,284
def euler77(): """Solves problem 77 from Project Euler.""" n = 1 while True: c = countPrimeCombinatinos(n) print("Num:", n, " Count:", c) if c >= 5000: break n += 1
5,288,285
def ListBuildChannels(): """Lists all build channels. Returns: a list of ndb_models.BuildChannelConfig objects. """ return [ BuildChannel(config) for config in ndb_models.BuildChannelConfig.query().fetch() ]
5,288,286
def _get_localzone(_root='/'): """Tries to find the local timezone configuration. This method prefers finding the timezone name and passing that to pytz, over passing in the localtime file, as in the later case the zoneinfo name is unknown. The parameter _root makes the function look for files like ...
5,288,287
def get_char_counts(corpus_reader: CorpusReader) -> Dict[str, int]: """ Get a frequency distribution of characters in a corpus. :param corpus_reader: :return: """ char_counter = Counter() # type: Dict[str, int] files = corpus_reader.fileids() for file in tqdm(files, total=len(files), un...
5,288,288
async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None: """Create wallbox sensor entities in HASS.""" coordinator: WallboxCoordinator = hass.data[DOMAIN][entry.entry_id] async_add_entities( [ WallboxSensor(coordinator,...
5,288,289
def str2size(str): """Accepts a string defining a size: 1337 - 1337 bytes 150K - 150 kilobytes 2M - 2 megabytes Returns a tuple (size,unit), where size is an integer and unit is 'B' (bytes) or 'T' (threads).""" if str[-1] in string.digits: #TODO: de-uglify return (int(str),'B') e...
5,288,290
def ParseAutoservDate(timestamp): """Autoserv log format timestamp to datetime parser. Args: timestamp: a string. Returns: a datetime. """ year = str(Now().year) naive_dt = dateutil.parser.parse(year + '/' + timestamp) dt = naive_dt.replace(tzinfo=naive_dt.tzinfo or dateu...
5,288,291
def to_triples_file( graph: BELGraph, path: Union[str, TextIO], *, use_tqdm: bool = False, sep='\t', raise_on_none: bool = False ) -> None: """Write the graph as a TSV. :param graph: A BEL graph :param path: A path or file-like :param use_tqdm: Should a progress bar be shown? ...
5,288,292
def heading_from_to(p1: Vector, p2: Vector) -> float: """ Returns the heading in degrees from point 1 to point 2 """ x1 = p1[0] y1 = p1[1] x2 = p2[0] y2 = p2[1] angle = math.atan2(y2-y1, x2-x1) * (180/math.pi) angle = (-angle) % 360 return abs(angle)
5,288,293
def _compute_power_transforms( Ys: Dict[str, List[float]] ) -> Dict[str, PowerTransformer]: """Compute power transforms.""" power_transforms = {} for k, ys in Ys.items(): y = np.array(ys)[:, None] # Need to unsqueeze the last dimension pt = PowerTransformer(method="yeo-johnson").fit(y) ...
5,288,294
def cni_scan(): """ Scan a French National Identity Card --- summary: scan a French National Identity Card tags: - cni consumes: - multipart/form-data parameters: - in: formData name: image type: file required: true description: a picture of ...
5,288,295
def _alloc_key(name): """Constructs allocation key based on app name/pattern.""" if '@' in name: key = name[name.find('@') + 1:name.find('.')] else: key = name[0:name.find('.')] return key
5,288,296
def play_tour(features, results): """ Callback to loop through best views. """ show_scenes_cb(features, results) loop_scenes()
5,288,297
def collect_ranged_items(lm, dies): """Collect items that have start/end ranges.""" results = [] # Ranges refs (stored as decimal offset) rlrefs = defaultdict(list) for off, lines in dies.items(): _, tag, attrs = expand_die(lines) # Does it have a PC range? lodec, hidec = get_pc_range(attrs) ...
5,288,298
def merge_intersection(*sorted_gens): """Yield non-duplicate entries in the intersection of pre-sorted generators Each sorted iterator will be iterated over in parallel, with values that cannot be in all iterators or duplicate values being skipped. Values that are in each passed sorted_gen will be yiel...
5,288,299