content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Any def get_node_data(workspace: str, graph: str, table: str, node: str) -> Any: """Return the attributes associated with a node.""" return Workspace(workspace).graph(graph).node_attributes(table, node)
0ac48d715fd31876b62d837d5b18b2ee75c791dd
3,800
def siso_optional(fn, h_opt, scope=None, name=None): """Substitution module that determines to include or not the search space returned by `fn`. The hyperparameter takes boolean values (or equivalent integer zero and one values). If the hyperparameter takes the value ``False``, the input is simply ...
187a292c8dba59d5d4d7f67d54cdd087ee2b6582
3,801
def saconv3x3_block(in_channels, out_channels, stride=1, pad=1, **kwargs): """ 3x3 version of the Split-Attention convolution block. Parameters: ---------- in_channels : int Number of input channels. out_cha...
bda938d53bbb56a7035ae50125743e4eb9aa709b
3,802
def add_hook(**_kwargs): """Creates and adds the import hook in sys.meta_path""" hook = import_hook.create_hook( transform_source=transform_source, hook_name=__name__, extensions=[".pyfr"], ) return hook
20c7e37aead055e32bfcb520a579b66069a3e26c
3,803
def mul(n1, n2): """ multiply two numbers """ return n1 * n2
c137432dd2e5c6d4dbded08546e3d54b98fe03df
3,804
import torch def pytorch_normalze(img): """ https://github.com/pytorch/vision/issues/223 return appr -1~1 RGB """ normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) img = normalize(torch.from_numpy(img)) return img.numpy(...
7667d6fa3da69d89973bb804ad08a139ae7f3564
3,805
def get_nic_capacity(driver_info, ilo_fw): """Gets the FRU data to see if it is NIC data Gets the FRU data in loop from 0-255 FRU Ids and check if the returned data is NIC data. Couldn't find any easy way to detect if it is NIC data. We should't be hardcoding the FRU Id. :param driver_info: Co...
cc20e1b35a47bec1242ed5dba60da8473527ca4f
3,806
import re def isValidInifileKeyName(key): """ Check that this key name is valid to be used in inifiles, and to be used as a python property name on a q or i object """ return re.match("^[\w_]+$", key)
9e68b987d6ac9af3c40e053c2347b01f737f0665
3,807
def installed_pkgs(): """ Return the list of installed packages on the machine Returns: list: List of installed packages CLI Example: .. code-block:: bash salt '*' macpackage.installed_pkgs """ cmd = "pkgutil --pkgs" return __salt__["cmd.run"](cmd).split("\n")
b9a66600327ea8eb0ec63745cacd8509a0f757d9
3,808
import math def extract_feature(audio, sr=44100): """ extract feature like below: sig: rmse: silence: harmonic: pitch: audio: audio file or audio list return feature_list: np of [n_samples, n_features] """ feature_list = [] y = [] if isinstance(audio, str): ...
d4eca914605bc87c57dbaf846a9a01d79a953c56
3,809
import time def run_with_config(sync, config): """ Execute the cartography.sync.Sync.run method with parameters built from the given configuration object. This function will create a Neo4j driver object from the given Neo4j configuration options (URI, auth, etc.) and will choose a sensible update tag...
b5659863ed31f1a39a0d8c95b33eb02d5ea8d77d
3,810
from typing import OrderedDict import six def BuildPartialUpdate(clear, remove_keys, set_entries, field_mask_prefix, entry_cls, env_builder): """Builds the field mask and patch environment for an environment update. Follows the environments update semantic which applies operations in an ...
320c589cd45dcec9a3ebba4b295075e23ef805ed
3,811
import io import json import sys def readJSON( json_path: FilePath, file_text: str = "", conf_file_name: str = "" ) -> object: """Reads the JSON from the given file and saves it to a class object with the JSON elements as attributes. If an error occurs, the program is exited with an error message! ...
5c1fba7e9967592f9a61eb0cbefedb1db5384276
3,812
def create_schema_usb(): """Create schema usb.""" return vol.Schema(CONFIG_SCHEMA_USB)
e543a5950788ad629ed3986cc7a6c5a58931a478
3,813
def _build_field_queries(filters): """ Builds field queries. Same as _build_field_query but expects a dict of field/values and returns a list of queries. """ return [ _build_field_query(field, value) for field, value in filters.items() ]
9b1241cce6c421a79cd5ea26dd134d5fd93d6fde
3,814
def bycode(ent, group): """ Get the data with the given group code from an entity. Arguments: ent: An iterable of (group, data) tuples. group: Group code that you want to retrieve. Returns: The data for the given group code. Can be a list of items if the group code occu...
c5b92f2bbd1cd5bc383a1102ccf54031222d82c3
3,815
import numbers import os def subtract_bg(inputs, out_names=None, x_order=None, y_order=None, reprocess=None): """ Model the instrumental background or scattered light level as a function of position in the input files (based on the counts within specified nominally-unilluminated region...
81a3c4bf73fe9361538312a767cea353091b6a1a
3,816
from typing import List from typing import Tuple def get_midi_programs(midi: MidiFile) -> List[Tuple[int, bool]]: """ Returns the list of programs of the tracks of a MIDI, deeping the same order. It returns it as a list of tuples (program, is_drum). :param midi: the MIDI object to extract tracks programs...
7249baa46b80b8b42400068edacf5ce9e829c71f
3,817
def is_depth_wise_conv(module): """Determine Conv2d.""" if hasattr(module, "groups"): return module.groups != 1 and module.in_channels == module.out_channels elif hasattr(module, "group"): return module.group != 1 and module.in_channels == module.out_channels
27127f54edbf8d0653cab6c7dbfb1448f33ecab4
3,818
def list_all_routed(): """ List all the notifications that have been routed to any repository, limited by the parameters supplied in the URL. See the API documentation for more details. :return: a list of notifications appropriate to the parameters """ return _list_request()
d67141d6fa5908d99292d898a5a77df3e80d47aa
3,819
import os def read(file_name): """Read in the supplied file name from the root directory. Args: file_name (str): the name of the file Returns: the content of the file """ this_dir = os.path.dirname(__file__) file_path = os.path.join(this_dir, file_name) with open(file_path) as f: ...
252b9d70febf6bbf36987b1e435501bcf8ce1ce8
3,820
from typing import Dict from typing import Any from typing import Optional def prepare_stdin( method: str, basis: str, keywords: Dict[str, Any], charge: int, mult: int, geoopt: Optional[str] = "" ) -> str: """Prepares a str that can be sent to define to produce the desired input for Turbomole.""" # L...
a4c70cfa97530108c2e969f424fa0f02c32fd927
3,821
def Lstart(gridname='BLANK', tag='BLANK', ex_name='BLANK'): """ This adds more run-specific entries to Ldir. """ # put top level information from input into a dict Ldir['gridname'] = gridname Ldir['tag'] = tag Ldir['ex_name'] = ex_name # and add a few more things Ldir['gtag'] = gridn...
92d992c3a7eba7bbba9146018060bca7844d4a78
3,822
def rfe_w2(x, y, p, classifier): """RFE algorithm, where the ranking criteria is w^2, described in [Guyon02]_. `classifier` must be an linear classifier with learn() and w() methods. .. [Guyon02] I Guyon, J Weston, S Barnhill and V Vapnik. Gene Selection for Cancer Classification using Support...
9176ee36c1180ab862b23be9d9a09584abea50ca
3,823
from typing import List def compress_timeline(timeline: List, salt: bytes) -> List: """ Compress the verbose Twitter feed into a small one. Just keep the useful elements. The images are downloaded per-request. Args: timeline (List): The Twitter timeline. salt (bytes): The salt to appl...
aff1364714d7e83685ab2257167fcd8bc7e10436
3,824
def createFinalCompactedData(compacted_data,elevations): """ This function creates a dataframe that combines the RGB data and the elevations data into a dataframe that can be used for analysis Parameters ---------- compacted_data : list of compacted data returned from condensePixels. elevat...
0d8b6a5e10504c32988e05e7450ebcf077305949
3,825
def get_sorted_nodes_edges(bpmn_graph): """ Assure an ordering as-constant-as-possible Parameters -------------- bpmn_graph BPMN graph Returns -------------- nodes List of nodes of the BPMN graph edges List of edges of the BPMN graph """ graph = bpmn...
879d7e8e3e5e4e9a8db3fc01622b96dde2b7af25
3,826
from typing import Optional from typing import Dict from typing import Any def list_commits( access_key: str, url: str, owner: str, dataset: str, *, revision: Optional[str] = None, offset: Optional[int] = None, limit: Optional[int] = None, ) -> Dict[str, Any]: """Execute the OpenAP...
be3899be0b77de069c7d32ca39aaec2039fe89e4
3,827
import heapq def dijkstra(graph, start, end=None): """ Find shortest paths from the start vertex to all vertices nearer than or equal to the end. The input graph G is assumed to have the following representation: A vertex can be any object that can be used as an index into a dictionary. G is...
b2a1ee983534c0a4af36ae7e3490c3b66949609b
3,828
import sys import pwd import os def get_owner_from_path(path): """Get the username of the owner of the given file""" if "pwd" in sys.modules: # On unix return pwd.getpwuid(os.stat(path).st_uid).pw_name # On Windows f = win32security.GetFileSecurity(path, win32security.OWNER_SECURITY_...
df038aff54d44654403beee0af63ac0aed9385a4
3,829
def tournament_selection(pop, size): """ tournament selection individual eliminate one another until desired breeding size is reached """ participants = [ind for ind in pop.population] breeding = [] # could implement different rounds here # but I think that's almost the same as calling tour...
78bebc2de25d0744f3f8dabd67f70136d5f020b5
3,830
import math def bond_number(r_max, sigma, rho_l, g): """ calculates the Bond number for the largest droplet according to Cha, H.; Vahabi, H.; Wu, A.; Chavan, S.; Kim, M.-K.; Sett, S.; Bosch, S. A.; Wang, W.; Kota, A. K.; Miljkovic, N. Dropwise Condensation on Solid Hydrophilic Surfaces. Science Advances 2...
2098a762dd7c2e80ff4a570304acf7cfbdbba2e5
3,831
def spatial_conv(inputs, conv_type, kernel, filters, stride, is_training, activation_fn='relu', data_format='channels_last'): """Performs 1x1 conv followed by 2d or depthwise conv. Args: input...
e87820eaa5b8ed13157fe0790c4e09b1bc546a0d
3,832
async def timeron(websocket, battleID): """Start the timer on a Metronome Battle. """ return await websocket.send(f'{battleID}|/timer on')
f1601694e2c37d41adcc3983aa535347dc13db71
3,833
import numpy def to_unit_vector(this_vector): """ Convert a numpy vector to a unit vector Arguments: this_vector: a (3,) numpy array Returns: new_vector: a (3,) array with the same direction but unit length """ norm = numpy.linalg.norm(this_vector) assert norm > 0.0, "vector ...
ae46bf536b8a67a1be1e98ae051eebf1f8696e37
3,834
import base64 def decode(msg): """ Convert data per pubsub protocol / data format Args: msg: The msg from Google Cloud Returns: data: The msg data as a string """ if 'data' in msg: data = base64.b64decode(msg['data']).decode('utf-8') return data
32e85b3f0c18f3d15ecb0779825941024da75909
3,835
def pivot_longer_by_humidity_and_temperature(df: pd.DataFrame) -> pd.DataFrame: """ Reshapes the dataframe by collapsing all of the temperature and humidity columns into an temperature, humidity, and location column Parameters ---------- df : pd.DataFrame The cleaned and renamed datafra...
d60b92b523c31b3f7db799f58a42bd9ca810d258
3,836
def add_counter_text(img, box_shape, people_in): """ Add person counter text on the image Args: img (np.array): Image box_shape (tuple): (width, height) of the counter box people_in (int): Number representing the amount of people inside the space Returns: (n...
ca182338a7dc11596b8375d788036d5de50381e2
3,837
def create_override(override): """Takes override arguments as dictionary and applies them to copy of current context""" override_context = bpy.context.copy() for key, value in override.items(): override_context[key] = value return override_context
25ecb761d8e9225081752fef10d2a6a885ba14d2
3,838
import os import mimetypes def get_result_file(request): """Return the content of the transformed code. """ resdir = get_resultdir(request) workdir = os.path.basename(request.session['workdir']) # sanitized name = os.path.basename(request.matchdict.get('name', 'result-%s.txt' % workdir)) e...
83b418f0ce0ce99fcba337db6fe0122e5a38606c
3,839
import json def load_or_make_json(file, *, default=None): """Loads a JSON file, or makes it if it does not exist.""" if default is None: default = {} return __load_or_make(file, default, json.load, json.dump)
3045cf141d26313fe8ffe60d6e74ff7af18ddce2
3,840
import warnings def plot_predictions(image, df, color=None, thickness=1): """Plot a set of boxes on an image By default this function does not show, but only plots an axis Label column must be numeric! Image must be BGR color order! Args: image: a numpy array in *BGR* color order! Channel ...
c666b1a92eefbc04abc7da1c3a4bc6cccde93769
3,841
from sympy import solveset, diff from re import S def stationary_points(f, symbol, domain=S.Reals): """ Returns the stationary points of a function (where derivative of the function is 0) in the given domain. Parameters ========== f : Expr The concerned function. symbol : Symbol ...
21011d7925c136de43f962a56edd5ffcc09c144f
3,842
def _create_table(data_list, headers): """ Create a table for given data list and headers. Args: data_list(list): list of dicts, which keys have to cover headers headers(list): list of headers for the table Returns: new_table(tabulate): created table, ready to p...
d072857776c16128808b7e2b4b64075cc4894199
3,843
def _validate_attribute_id(this_attributes, this_id, xml_ids, enforce_consistency, name): """ Validate attribute id. """ # the given id is None and we don't have setup attributes # -> increase current max id for the attribute by 1 if this_id is None and this_attributes is None: this_id = ma...
e85201c85b790576f7c63f57fcf282a985c22347
3,844
def Arrows2D(startPoints, endPoints=None, shaftLength=0.8, shaftWidth=0.09, headLength=None, headWidth=0.2, fill=True, c=None, cmap=None, alpha=1): """ Build 2D arrows between two lists of points `startPoints...
d2276def355c56c6fe494c29bab04cd6f1e28221
3,845
def filter_characters(results: list) -> str: """Filters unwanted and duplicate characters. Args: results: List of top 1 results from inference. Returns: Final output string to present to user. """ text = "" for i in range(len(results)): if results[i] == "$": ...
6b2ca1446450751258e37b70f2c9cbe5110a4ddd
3,846
def seq_alignment_files(file1, file2, outputfile=""): """This command takes 2 fasta files as input, each file contains a single sequence. It reads the 2 sequences from files and get all their alignments along with the score. The -o is an optional parameter if we need the output to be written on a file inste...
b225d97e29040040755cc3f2260b60f90c390bce
3,847
def main(Block: type[_Block], n: int, difficulty: int) -> list[tuple[float, int]]: """Test can hash a block""" times_and_tries = [] for i in range(n): block = Block(rand_block_hash(), [t], difficulty=difficulty) # print(f"starting {i}... ", end="", flush=True) with time_it() as timer...
27c729604b3f3441e1ceb5f6d6d28f47d64fdb13
3,848
from typing import Union from typing import SupportsFloat def is_castable_to_float(value: Union[SupportsFloat, str, bytes, bytearray]) -> bool: """ prüft ob das objekt in float umgewandelt werden kann Argumente : o_object : der Wert der zu prüfen ist Returns : True|False Exceptions : keine...
e3882c0e64da79dc9a0b74b4c2414c7bf29dd6c9
3,849
from operator import itemgetter def list_unique(hasDupes): """Return the sorted unique values from a list""" # order preserving d = dict((x, i) for i, x in enumerate(hasDupes)) return [k for k, _ in sorted(d.items(), key=itemgetter(1))]
0ba0fcb216400806aca4a11d5397531dc19482f6
3,850
def filter_by_networks(object_list, networks): """Returns a copy of object_list with all objects that are not in the network removed. Parameters ---------- object_list: list List of datamodel objects. networks: string or list Network or list of networks to check for. Return...
9ffb2cedd1508e5924f3a2894a2f842bc5673440
3,851
def get_all_data(year=year, expiry=1, fielding=False, chadwick=False): """Grab all data and write core files.""" """Options for fielding data and bio data for rookies/master.""" name_url_pairs = url_maker(year=year, fielding=fielding) # if debugging warn about the webviews if module_log.isEnabledFor...
2bd4be520941dab31fc1c0b410fedad25c08fea9
3,852
def score_per_year_by_country(country): """Returns the Global Terrorism Index (GTI) per year of the given country.""" cur = get_db().execute('''SELECT iyear, ( 1*COUNT(*) + 3*SUM(nkill) + 0.5*SUM(nwound) + 2*SUM(case propextent when 1.0 then 1 else 0 end) + 2*SUM(case propextent when 2.0 the...
ac8992a0bd2227b7b9f5622b9395e4c7933af35a
3,853
def build(options, is_training): """Builds a model based on the options. Args: options: A model_pb2.Model instance. Returns: A model instance. Raises: ValueError: If the model proto is invalid or cannot find a registered entry. """ if not isinstance(options, model_pb2.Model): raise ValueE...
99fc2f283075091254743a9d70ecab3d7a65066d
3,854
def string_to_rdkit(frmt: str, string: str, **kwargs) -> RDKitMol: """ Convert string representation of molecule to RDKitMol. Args: frmt: Format of string. string: String representation of molecule. **kwargs: Other keyword arguments for conversion function. Returns: RDK...
34803a46d5228644bb3db614aca5580bcb286655
3,855
from datetime import datetime def clean_datetime_remove_ms(atime): """ 将时间对象的 毫秒 全部清零 :param atime: :return: """ return datetime(atime.year, atime.month, atime.day, atime.hour, atime.minute, atime.second)
94a47ad8802b3eb4d58d332d71bb3d3e0c67d947
3,856
def perDay(modified): """Auxiliary in provenance filtering: chunk the trails into daily bits.""" chunks = {} for m in modified: chunks.setdefault(dt.date(m[1]), []).append(m) return [chunks[date] for date in sorted(chunks)]
ce9fe31c39c9c6c5e0753aa2dc6dc5113fb199e4
3,857
import argparse def parse_args(): """Parse input arguments.""" parser = argparse.ArgumentParser(description='Faster R-CNN demo') parser.add_argument('im', help="Input image", default= '000456.jpg') parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', def...
40764cbb9987560e18e22e3bec9d4ce993e8b789
3,858
def login(): """The screen to log the user into the system.""" # call create_all to create database tables if this is the first run db.create_all() # If there are no users, create a default admin and non-admin if len(User.query.all()) == 0: create_default_users() # Redirect the user if a...
0912dca53b40677da9a9443c4500badf05fff8a8
3,859
def freight_sep_2014(): """Find the number of freight of the month""" for i in fetch_data_2014(): if i[1] == "Freight" and i[4] == "September": num_0 = i[6] return int(num_0)
b7f770362f7a85ffc92591a48660d01d7f784dc1
3,860
from typing import Union import os from typing import Any from typing import Optional from typing import List from pathlib import Path def convexhull( input_path: Union[str, "os.PathLike[Any]"], output_path: Union[str, "os.PathLike[Any]"], input_layer: Optional[str] = None, output_layer: Optional[str]...
958b482e7faf13f4fc63193e784ec8c20959e295
3,861
def piotroski_f(df_cy,df_py,df_py2): """function to calculate f score of each stock and output information as dataframe""" f_score = {} tickers = df_cy.columns for ticker in tickers: ROA_FS = int(df_cy.loc["NetIncome",ticker]/((df_cy.loc["TotAssets",ticker]+df_py.loc["TotAssets",ticker])/2) > 0)...
119a3dd426fbe5e8b5106cbebebf4b000799a839
3,862
from typing import Dict def evaluate_circuit( instances: Dict[str, SType], connections: Dict[str, str], ports: Dict[str, str], ) -> SDict: """evaluate a circuit for the given sdicts.""" # it's actually easier working w reverse: reversed_ports = {v: k for k, v in ports.items()} block_diag...
7dd6d019845dbf7f69c6324143d88d4d48af9dea
3,863
def canonical_smiles_from_smiles(smiles, sanitize = True): """ Apply canonicalisation with rdkit Parameters ------------ smiles : str sanitize : bool Wether to apply rdkit sanitisation, default yes. Returns --------- canonical_smiles : str Returns None if canonicali...
0c4dc4583d9a12439b915412cab8458e380a4e6c
3,864
def get_ref(struct, ref, leaf=False): """ Figure out if a reference (e.g., "#/foo/bar") exists within a given structure and return it. """ if not isinstance(struct, dict): return None parts = ref_parts(ref) result = {} result_current = result struct_current = struct ...
61ebb2561c2c79c58c297c91ac266e9e786a5b7f
3,865
import os def delete_files(dpath: str, label: str='') -> str: """ Delete all files except the files that have names matched with label If the directory path doesn't exist return 'The path doesn't exist' else return the string with the count of all files in the directory and the count of deleted ...
c8b95d9b14d698145667383bbfe88045330e5cb0
3,866
def edit_maker_app( operator, app_maker_code, app_name="", app_url="", developer="", app_tag="", introduction="", add_user="", company_code="", ): """ @summary: 修改 maker app @param operator:操作者英文id @param app_maker_code: maker app编码 @param app_name:app名称,可选参数,为空则不...
abb2d57235e6c231b96182f989606060f8ebb4ab
3,867
def fifo(): """ Returns a callable instance of the first-in-first-out (FIFO) prioritization algorithm that sorts ASDPs by timestamp Returns ------- prioritize: callable a function that takes an ASDP type name and a dict of per-type ASDPDB metadata, as returned by `asdpdb.load_as...
8f0d24c43a15467c9e6b9f195d12978664867bd3
3,868
def super(d, t): """Pressure p and internal energy u of supercritical water/steam as a function of density d and temperature t (deg C).""" tk = t + tc_k tau = tstar3 / tk delta = d / dstar3 taupow = power_array(tau, tc3) delpow = power_array(delta, dc3) phidelta = nr3[0] * delpow[-1] +...
937d58264b94b041aafa63b88d5fd4498d4acb8e
3,869
import tty import logging import json def ls(query=None, quiet=False): """List and count files matching the query and compute total file size. Parameters ---------- query : dict, optional (default: None) quiet : bool, optional Whether to suppress console output. """ tty.sc...
acbf576170f34cfc09e4a3a8d64c1c313a7d3b51
3,870
def _create_full_gp_model(): """ GP Regression """ full_gp_model = gpflow.models.GPR( (Datum.X, Datum.Y), kernel=gpflow.kernels.SquaredExponential(), mean_function=gpflow.mean_functions.Constant(), ) opt = gpflow.optimizers.Scipy() opt.minimize( full_gp_model...
bebe02e89e4ad17c5832cfced8f7cd1dce9a3b11
3,871
def read_file_header(fd, endian): """Read mat 5 file header of the file fd. Returns a dict with header values. """ fields = [ ('description', 's', 116), ('subsystem_offset', 's', 8), ('version', 'H', 2), ('endian_test', 's', 2) ] hdict = {} for name, fmt, num_...
d994f74a889cedd7e1524102ffd1c62bb3764a0f
3,872
def shape_padleft(t, n_ones=1): """Reshape `t` by left-padding the shape with `n_ones` 1s. See Also -------- shape_padaxis shape_padright Dimshuffle """ _t = aet.as_tensor_variable(t) pattern = ["x"] * n_ones + [i for i in range(_t.type.ndim)] return _t.dimshuffle(pattern)
44e68fed0ea7497ba244ad83fbd4ff53cec22f24
3,873
def zad1(x): """ Функция выбирает все элементы, идущие за нулём. Если таких нет, возвращает None. Если такие есть, то возвращает их максимум. """ zeros = (x[:-1] == 0) if np.sum(zeros): elements_to_compare = x[1:][zeros] return np.max(elements_to_compare) return None
e54f99949432998bf852afb8f7591af0af0b8b59
3,874
def skopt_space(hyper_to_opt): """Create space of hyperparameters for the gaussian processes optimizer. This function creates the space of hyperparameter following skopt syntax. Parameters: hyper_to_opt (dict): dictionary containing the configuration of the hyperparameters to optimize....
bdfbc685b5fd51f8f28cb9b308d3962179d15c7e
3,875
import argparse import sys def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Train a R2CNN network') parser.add_argument('--img_dir', dest='img_dir', help='images path', default='/mnt/USBB/gx/DOTA/DOTA_clip...
c0ca3c7aadd82e61cb6ff2f078d3b308822206ba
3,876
import torch def process_text_embedding(text_match, text_diff): """ Process text embedding based on embedding type during training and evaluation Args: text_match (List[str]/Tensor): For matching caption, list of captions for USE embedding and Tensor for glove/fasttext embeddings ...
6f052cc29186f8bcc1598780bf7f437098774498
3,877
import requests import json import base64 def x5u_vulnerability(jwt=None, url=None, crt=None, pem=None, file=None): """ Check jku Vulnerability. Parameters ---------- jwt: str your jwt. url: str your url. crt: str crt path file pem: str pem file name ...
0424072951e99d0281a696b94889538c1d17ed81
3,878
from typing import List import os from typing import Dict def from_kitti( data_dir: str, data_type: str, ) -> List[Frame]: """Function converting kitti data to Scalabel format.""" if data_type == "detection": return from_kitti_det(data_dir, data_type) frames = [] img_dir = osp.join(d...
805224b4166238150f6f56c3d14220563a931a64
3,879
def get_all_interactions(L, index_1=False): """ Returns a list of all epistatic interactions for a given sequence length. This sets of the order used for beta coefficients throughout the code. If index_1=True, then returns epistatic interactions corresponding to 1-indexing. """ if index_1: ...
f8a151e5d44f2e139820b3d06af3995f60945dd2
3,880
import xml import math def convertSVG(streamOrPath, name, defaultFont): """ Loads an SVG and converts it to a DeepSea vector image FlatBuffer format. streamOrPath: the stream or path for the SVG file. name: the name of the vector image used to decorate material names. defaultFont: the default font to use. The ...
f71b22af076a466f951815e73f83ea989f920cdf
3,881
def to_accumulo(df, config: dict, meta: dict, compute=True, scheduler=None): """ Paralell write of Dask DataFrame to Accumulo Table Parameters ---------- df : Dataframe The dask.Dataframe to write to Accumulo config : dict Accumulo configuration to use to connect to accumulo ...
016ee1cc516b8fd6c055902002a196b30ceb0e07
3,882
def compute_euclidean_distance(x, y): """ Computes the euclidean distance between two tensorflow variables """ d = tf.reduce_sum(tf.square(x-y),axis=1,keep_dims=True) return d
26171d3a0c719d0744ab163b33590f4bb1f92480
3,883
def vpn_ping(address, port, timeout=0.05, session_id=None): """Sends a vpn negotiation packet and returns the server session. Returns False on a failure. Basic packet structure is below. Client packet (14 bytes):: 0 1 8 9 13 +-+--------+-----+ |x| cli_id |?????| +-+--------+-----+ ...
dcc4d8cf347486b0f10f1dd51d230bd6fb625551
3,884
def is_admin(): """Checks if author is a server administrator, or has the correct permission tags.""" async def predicate(ctx): return ( # User is a server administrator. ctx.message.channel.permissions_for(ctx.message.author).administrator # User is a developer. ...
70a87d8ae4970b05aa39339fec2aa1ade43d238a
3,885
def send_message(chat_id): """Send a message to a chat If a media file is found, send_media is called, else a simple text message is sent """ files = request.files if files: res = send_media(chat_id, request) else: message = request.form.get("message", default="Empty Message"...
df77e115497cfc975b9fad6f9a3b43648349133e
3,886
def get_neighbours(sudoku, row, col): """Funkcja zwraca 3 listy sasiadow danego pola, czyli np. wiersz tego pola, ale bez samego pola""" row_neighbours = [sudoku[row][y] for y in range(9) if y != col] col_neighbours = [sudoku[x][col] for x in range(9) if x != row] sqr_neighbours = [sudoku[x][y] for x in...
b10766fc8925b54d887925e1a684e368c0f3b550
3,887
import torch import PIL def to_ndarray(image): """ Convert torch.Tensor or PIL.Image.Image to ndarray. :param image: (torch.Tensor or PIL.Image.Image) image to convert to ndarray :rtype (ndarray): image as ndarray """ if isinstance(image, torch.Tensor): return image.numpy() if is...
f12444779e2d2eb78e3823821c8c6acec7c601a6
3,888
def make_map_exposure_true_energy(pointing, livetime, aeff, ref_geom, offset_max): """Compute exposure WcsNDMap in true energy (i.e. not convolved by Edisp). Parameters ---------- pointing : `~astropy.coordinates.SkyCoord` Pointing direction livetime : `~astropy.units.Quantity` Live...
fa3def16e0509f50a21936aef0784bca91a84d07
3,889
def calc_random_piv_error(particle_image_diameter): """ Caclulate the random error amplitude which is proportional to the diameter of the displacement correlation peak. (Westerweel et al., 2009) """ c = 0.1 error = c*np.sqrt(2)*particle_image_diameter/np.sqrt(2) return error
91b02b658c0c6476739695017925c44c92bf67c8
3,890
def resolve(name, module=None): """Resolve ``name`` to a Python object via imports / attribute lookups. If ``module`` is None, ``name`` must be "absolute" (no leading dots). If ``module`` is not None, and ``name`` is "relative" (has leading dots), the object will be found by navigating relative to ``mod...
d778ff9e4ea821be6795cc9007552e6c0afeb565
3,891
def fibonacci(n:int) -> int: """Return the `n` th Fibonacci number, for positive `n`.""" if 0 <= n <= 1: return n n_minus1, n_minus2 = 1,0 result = None for f in range(n - 1): result = n_minus2 + n_minus1 n_minus2 = n_minus1 n_minus1 = result return result
4be929f69dc9c35679af580767bfe047fc1963e9
3,892
import select def get_budget(product_name, sdate): """ Budget for a product, limited to data available at the database :param product_name: :param sdate: starting date :return: pandas series """ db = DB('forecast') table = db.table('budget') sql = select([table.c.budget]).where(ta...
a17ae7db2734c2c877a41eb0986016a4f0241f07
3,893
def _residual_block_basic(filters, kernel_size=3, strides=1, use_bias=False, name='res_basic', kernel_initializer='he_normal', kernel_regularizer=regulizers.l2(1e-4)): """ Return a basic residual layer block. :param filters: Number of filters. :param kernel_size...
87c041f58de71d7bd2d3fcbe97ec35b8fa057468
3,894
def console_script(tmpdir): """Python script to use in tests.""" script = tmpdir.join('script.py') script.write('#!/usr/bin/env python\nprint("foo")') return script
be6a38bec8bb4f53de83b3c632ff3d26d88ef1c7
3,895
def parse_tpl_file(tpl_file): """ parse a PEST-style template file to get the parameter names Args: tpl_file (`str`): path and name of a template file Returns: [`str`] : list of parameter names found in `tpl_file` Example:: par_names = pyemu.pst_utils.parse_tpl_file("my.tpl") ...
01ed281f4ee9f1c51032d4f3655bd3e17b73bbb2
3,896
from datetime import datetime def _save_downscaled( item: Item, image: Image, ext: str, target_type: str, target_width: int, target_height: int, ) -> Media: """Common downscale function.""" if ext != 'jpg': image = image.convert('RGB') # TODO - thes...
4200aa5812372d780fc1a4a6e4fa9752f4ab7993
3,897
def get_single_image_results(pred_boxes, gt_boxes, iou_thr): """Calculates number of true_pos, false_pos, false_neg from single batch of boxes. Args: gt_boxes (list of list of floats): list of locations of ground truth objects as [xmin, ymin, xmax, ymax] pred_boxes (d...
3f3bc93641e2f7d04a21fed9a8d0c40fcbc9eacc
3,898
def get_list(caller_id): """ @cmview_user @response{list(dict)} PublicIP.dict property for each caller's PublicIP """ user = User.get(caller_id) ips = PublicIP.objects.filter(user=user).all() return [ip.dict for ip in ips]
41f7855eb258df444b29dc85860e5e85ae6de441
3,899