content
stringlengths
22
815k
id
int64
0
4.91M
def format_hostname(domain_parts, uid): """Formats hostname for a docker based on domain parts and uid. NOTE: Hostnames are also used as docker names! domain_parts - a single or a list of consecutive domain parts that constitute a unique name within environment e.g.: ['worker1', 'prov1'], ['ccm1', 'prov...
5,320,100
def mapmaker(image, mapdet): """Function to Build some maps""" plt.rcParams.update({'figure.subplot.right' : 0.85 }) plt.rcParams.update({'figure.subplot.left' : 0.05 }) fig, ax = plt.subplots(1, 1, figsize=(18,9), subplot_kw={'projection': ccrs.PlateCarree()}, num=("Map of %s" % mapdet.var)) # re...
5,320,101
def get_aspect_ratio(width_first=True): """ Returns the aspect ratio of the game window, or the window's width / the window's height. If width_first is True (default), then it will return the window's height / the window's width. :param width_first: Bool - Whether to divide the height by the width. ...
5,320,102
def upload_to_blob(file_path, client, container): """ Upload a file to Azure Blob storage. Args: file_path (str): Path of the file to upload. client (`azure.storage.blob.BlockBlobService`): Blob service container (str): Name for the container Returns: (`azure.batch.mode...
5,320,103
def _environ_cols_wrapper(): # pragma: no cover """ Return a function which returns console width. Supported: linux, osx, windows, cygwin. """ warn("Use `_screen_shape_wrapper()(file)[0]` instead of" " `_environ_cols_wrapper()(file)`", DeprecationWarning, stacklevel=2) shape = _...
5,320,104
def encode(content, encoding: Optional[str] = "json") -> Response: """Encode content in given encoding. Warning: Not all encodings supports all types of content. :param content: Content to encode :param encoding: - `json` (default) - `bin`: nD array/scalars in bytes - `csv`: nD...
5,320,105
def yesNoDialog(parent, msg, title): """ Convenience function to display a Yes/No dialog Returns: bool: return True if yes button press. No otherwise """ m = QMessageBox(parent) m.setText(msg) m.setIcon(QMessageBox.Question) yesButton = m.addButton(_(Text.txt0082), QMessageBox....
5,320,106
def setup_logging(global_bootstrap_options: OptionValueContainer, stderr_logging: bool) -> None: """Sets up logging for a Pants run. This is called in two contexts: 1) PantsRunner, 2) DaemonPantsRunner. In the latter case, the loggers are saved and restored around this call, so in both cases it runs with n...
5,320,107
def import_all_references(except_namespaces = []): """ 导入所有reference文件 """ done = False while (done == False or (len(pm.listReferences()) != 0)): refs = pm.listReferences() #get rel refs pro = [] if except_namespaces: for ref in refs: if ref.n...
5,320,108
def get_annotations(element): """ returns a dictionary of all the annotation features of an element, e.g. tiger.pos = ART or coref.type = anaphoric. """ from labels import get_annotation annotations = {} for label in element.getchildren(): if get_xsi_type(label) == 'saltCore:SAnnotat...
5,320,109
def _prefAdj(coupling, leg): """Prefactor for the creation of an adjoint Only implemented for regular three-legged tensors with an (in, in, out) flow and their adjoints at the moment. """ if len(coupling) != 1: raise NotImplementedError("Only for three-legged tensors") flow = tuple(c[1...
5,320,110
def recon_traj_with_preds(dataset, preds, seq_id=0, **kwargs): """ Reconstruct trajectory with predicted global velocities. """ ts = dataset.ts[seq_id] ind = np.array([i[1] for i in dataset.index_map if i[0] == seq_id], dtype=int) dts = np.mean(ts[ind[1:]] - ts[ind[:-1]]) # pos = np.zeros([p...
5,320,111
def log_compilation( tool_name, main_infile ): """ Call this when recompiling, before compilation (so that it is logged before it starts compiling). :param tool_name: Name of the tool that processes the file, string. :param main_infile: One of the input files, string. """ print( tool_name + " " + helpers._r...
5,320,112
def fitfunPowerLaw(fitparamStart, fixedparam, fitInfo, x, y): """ Power law fit function y = A * B^x + C ========== =============================================================== Input Meaning ---------- --------------------------------------------------------------- fitparamStart ...
5,320,113
def make_2d_histogram(x, y, n_bins, xlabel, ylabel, cbar_label, figsize=(12, 4)): """ Generate a rainbow-colored 2D histogram. :param x: X-axis values, i.e. barcode group indices :param y: Y-axis values corresponding to x :param n_bins: (x,y) bin sizes; x should usually be 1 ...
5,320,114
def ingest_cop(years, month): """ Args: years: list month: str Returns: list """ cop_data = [] for year in years: directory = 'data\\raw\\copernicus\\' wrf_file_name = year + month + '-C3S-L4_OZONE-O3_PRODUCTS-MSR-ASSIM-ALG-MONTHLY-v0021.nc' nc = netcd...
5,320,115
def update_mags_table(filename, mags, dry_run=False, create=False): """ Update the 'mags' table of the AGASC supplement. :param filename: AGASC supplement filename :param mags: list of dict or table.Table list entries are dictionaries like:: {'agasc_id': 1, 'ma...
5,320,116
def utils_files_count(directory): """Get number of files by searching directory recursively""" if not os.path.exists(directory): return 0 cnt = 0 for r, dirs, files in os.walk(directory): for dr in dirs: cnt += len(glob.glob(os.path.join(r, dr + "/*"))) return cnt
5,320,117
def readwav(filename): """Read a WAV file and returns the data and sample rate :: from spectrum.io import readwav readwav() """ from scipy.io.wavfile import read as readwav samplerate, signal = readwav(filename) return signal, samplerate
5,320,118
def get_connections_from_file(parent, filename): """load connections from connection file""" error = 0 try: doc = etree.parse(filename).getroot() if doc.tag != 'qgsCSWConnections': error = 1 msg = parent.tr('Invalid CSW connections XML.') except etree.ParseError ...
5,320,119
def extract_provenance_chain(credential: Credential) -> List[Credential]: """ Extract the chain into an ordered list of credentials. Root credential will be at the start of the returned list """ def decode(credential: Credential, acc: List[Credential]): if credential.provenance: ...
5,320,120
def make_induces(x, y): """return [ [(0,0), (0,1),...,(0,y-1)], [(1,0),...], [(x-1, 0), (x-1, 1), ..., (x-1, y-1)] """ index_x = tf.expand_dims(tf.range(0, x), 1) index_y = tf.expand_dims(tf.range(0, y), 0) index_x = tf.tile(index_x, [1, y]) index_y = tf.tile(index_y, [x, 1]) induces = tf.stack([index_x, ...
5,320,121
def unused_argument(editor, item): """ Pylint unused-argument method """ line_no = item.line_no error_text = editor.lines[line_no] LOGGER.info("unused argument: {0}".format(error_text)) return (line_no, 0)
5,320,122
def enable_nova_compute_services(compute_api, *hosts): """ Disable nova-compute services on hosts listed in *hosts before decorated function will execute and disable previously enabled services after. :param compute_api: :param hosts: :return: """ LOG.debug("Enabling %s nova-compute serv...
5,320,123
def fitjordan(f, B, losses, Bo, fo): """fit coeffs of losses(f,B)=(ch*(f/fo)**alpha + ch*(f/fo)**beta)*(B/Bo)**gamma returns (ch, alpha, cw, beta, gamma) """ pfe = np.asarray(losses).T z = [] for i, fx in enumerate(f): if fx: if isinstance(B[0], float): z ...
5,320,124
def count_temporal_motif(G, sequence, delta, get_count_dict=False): """Count all temporal motifs. Parameters ---------- G : the graph to count temporal motif from. This function only supports ImpulseDiGraph sequence: a sequence of edges specifying the order of the motif. For example ((1,2), (2,3),...
5,320,125
def calc_expiry_time(minutes_valid): """Return specific time an auth_hash will expire.""" return ( timezone.now() + datetime.timedelta(minutes=minutes_valid + 1) ).replace(second=0, microsecond=0)
5,320,126
def parse(s): """ Parse an XML tree from the given string, removing all of the included namespace strings. """ ns = re.compile(r'^{.*?}') et = etree.fromstring(s) for elem in et.iter(): elem.tag = ns.sub('', elem.tag) return et
5,320,127
def findRef(pattern, haystack): """Return a reference to the matching subexpression within the original structure (for in-place modifications) or None if there is no match.""" x = searchFirst(pattern, haystack) if x is None: return None else: return get(haystack, x[0])
5,320,128
def parse_record(filename): """ This function parses house related data into a dictionary """ # Initialize content content = {} # Parse all lines with open(filename) as f: # Read all lines at once all_lines = f.readlines() # Skip the first three lines ...
5,320,129
def get_hostname(): """ :return: safely return the hostname """ hostname = "<Host Undetermined>" try: hostname = socket.gethostname() except Exception as e: logging.error(f"Could not get hostname.\nException: {e}") return hostname
5,320,130
def dict_get(d, key, default=None): """:yaql:get Returns value of a dictionary by given key or default if there is no such key. :signature: dict.get(key, default => null) :receiverArg dict: input dictionary :argType dict: dictionary :arg key: key :argType key: keyword :arg default:...
5,320,131
def set_render(obj, val): """ Sets whether object is to be rendered or not """ obj.hide_render = not val
5,320,132
def perform_task(commands): """ use a procces to perform commands """ for dir in re.split(':', os.environ['PATH']): program = f'{dir}/{commands[0]}' try: os.execve(program, commands, os.environ) except OSError: pass
5,320,133
def expect_keys_middleware(f): """ Returns a 400 error to the client if the route function tries to get a key from an object and cause a KeyError :param f: function :return: function """ def handle(*args, **kwargs): try: result = f(*args, **kwargs) except KeyError: ...
5,320,134
def set_pose(limb, kin, jointname, end_point, rpy,elbow, rl,mode): """ Controls the joints of this limb to the specified positions by using the end effector pose and elbow angle. :param limb: (str:Limb) Interface class for a limb on the Baxter robot :param kin: (str:Limb) baxter kinematics class :p...
5,320,135
def test_vote_challenge_voting( # type: ignore user_fixture, # pylint: disable=unused-argument submission_vote_fixture, # pylint: disable=unused-argument ) -> None: """Check vote when challenge on voting.""" method, endpoint, data, expected_status = ( "POST", "/api/votes/", ...
5,320,136
def _Request(endpoint, params): """Sends a request to an endpoint and returns JSON data.""" assert datastore_hooks.IsUnalteredQueryPermitted() return request.RequestJson( endpoint, method='POST', use_cache=False, use_auth=True, **params)
5,320,137
def dist(p, q): """ Euclidean distance for multi-dimensional data Examples -------- >>> dist((1, 2), (5, 5)) 5.0 """ return sqrt(sum((x - y) ** 2 for x, y in zip(p, q)))
5,320,138
def put_html(fragment): """ Put the given fragment into the clipboard. Convenience function to do the most common operation """ cb = HtmlClipboard() cb.put_fragment(fragment)
5,320,139
def create_item(metadata_href: str) -> pystac.Item: """Creates a STAC Item from modis data. Args: metadata_href (str): The href to the metadata for this hdf. This function will read the metadata file for information to place in the STAC item. Returns: pystac.Item: A STAC Item represe...
5,320,140
def get_args(): """ get args """ parser = argparse.ArgumentParser('NewP eval') parser.add_argument('--pred_path', required=True) parser.add_argument('--golden_path', required=True) args = parser.parse_args() return args
5,320,141
def getQRdataImg(file:str = "img.jpg") -> dict: """ Girilen resim dosyasında qr kodunu arar ve bulursa {'barkod':barkod,'tckn':tckn} olarak returnler. """ return parseQRdata(readQRImg(file))
5,320,142
def removeHandler(handler): """ Remove a handler from the internal logger Parameters ---------- handler: :class:`python.logging.Handler` Handler to be removed """ return __logger__.removeHandler(handler)
5,320,143
def find_telomeres(seq, telomere="ACACCCTA", minlength=24): """Find telomere sequences with NCRF in a list of sequences Assumes that NCRF is in the PATH. Parameters ---------- seq : str Sequence to be scanned telomere : str Sequence of the telomere repeat. Default is ACACCCTA, ...
5,320,144
def mock_parse_args(): """ Mock runner.parse_args() """ patcher = mock.patch("ixian.runner.parse_args") mock_parse_args = patcher.start() mock_parse_args.return_value = fake.build_test_args() yield mock_parse_args patcher.stop()
5,320,145
def has_prefix(sub_s, d): """ :param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid :return: (bool) If there is any words with prefix stored in sub_s """ for key in d[sub_s[0]]: if key.startswith(sub_s): return True
5,320,146
def empty_transition_values(): """Return an empty transition value.""" return TransitionValues(0, 0)
5,320,147
def float32(img, start_range, end_range): """Convert image to data type float32""" return cv2.normalize(img, None, start_range, end_range, cv2.NORM_MINMAX, cv2.CV_32F)
5,320,148
def loadtest_name(prefix: str, scenario_name: str, uniquifiers: Iterable[str]) -> str: """Constructs and returns a valid name for a LoadTest resource.""" base_name = loadtest_base_name(scenario_name, uniquifiers) elements = [] if prefix: elements.append(prefix) elements.app...
5,320,149
def get_STP_in_multi_cameras(obj_single_camera_stp_cam_1, obj_single_camera_stp_cam_2, associate_dict): """ Parameters: obj_single_camera_stp_cam_1: STP in cam 1 obj_single_camera_stp_cam_2: STP in cam 2 associate_dict:mapping relation between objects in cam_1 and cam_2 """ # cho...
5,320,150
def main(testing=False): """ Main function for the app. """ inputs = { 'job_status': os.getenv('INPUT_STATUS'), 'token': os.getenv('INPUT_TOKEN'), 'notification_title': os.getenv('INPUT_NOTIFICATION_TITLE'), 'message_format': os.getenv('INPUT_MESSAGE_FORMAT'), 'f...
5,320,151
def resize(I, scale): """ Resize the image `I` by a factor of `scale`, while keeping the original aspect ratio. If `scale` is smaller than `1.0`, cubic interpolation is used, otherwise nearest-neighbor interpolation. """ interpolationType = cv2.INTER_CUBIC if (scale < 1.0) else cv2.INTER_N...
5,320,152
def get_current_signal_level(slot: int, channel: int) -> int: """ From 0 to 255 """
5,320,153
def collisioncallback(report,fromphysics): """Whenever a collision or physics detects a collision, this function is called""" s = 'collision callback with ' if report.plink1 is not None: s += '%s:%s '%(report.plink1.GetParent().GetName(),report.plink1.GetName()) else: s += '(NONE)' s...
5,320,154
def flip_3D_bb(x, image_width): """ Flips the annotation of the image around y axis. Input: x: coordinates of points fbr, rbr, fbl, rbl, ftr, rtr, ftl, rtl image_width: width of the flipped image Return: x - flipped coordinates """ # First flip the x coordinates of the points x[0,:] = image_widt...
5,320,155
def train_model(bert_model, dataloader_train, optimizer, scheduler, device): """The architecture's training routine.""" bert_model.train() loss_train_total = 0 for batch_idx, batch in enumerate(dataloader_train): # set gradient to 0 bert_model.zero_grad() batch = tuple(b.to(...
5,320,156
def get_content(num_pages: int = constants.NUM_PAGES) -> Tuple[Set[str], List[str]]: """Retrieves page contents from random Wikipedia articles Args: num_pages: maximum number of pages to generate output from """ all_words = set() # type: Set[str] all_content = [] # type: List[str] ...
5,320,157
def create_barplot(out2,outbar): """ creates a barplot of FRiP scores where the x-axis is the bam sample, the y-axis is the FRiP score, the color is the sample used to create the peak file, and the panels are the different peak calling tools """ sns.set(style="whitegrid", palette="Set1", ...
5,320,158
def find_flight(location_from, location_to, date_from, date_to = None, num_adults = 1, num_children = 0, round=True): """Returns list of flights with given parameters Args: location_from (str): IATA code of departing airport location_to (str): IATA code of arriving airport date_from (st...
5,320,159
def delivery_report(from_date, to_date, reportfile): """ Generate the monthly report from from_date to to_date. It is assumed that from_date is the start of a month, and to_date is the end of a month. Dates must be strings of the form YYYY-MM-DDThh:mm:ssZ :param from_date: start of month date f...
5,320,160
def get_date_row(repositories): """Generate row with dates.""" row = ["Date"] for repository in repositories: row.append("Sources") row.append("Issues") row.append("Correct") # one more for summary row.append("Sources") row.append("Issues") row.append("Correct") ...
5,320,161
def test_does_have_mode_has_mode(pyric): """ Test does_have_mode function when the interface has the requested mode """ pyric.getcard.return_value = None pyric.devmodes.return_value = ["AP", "monitor"] name = "wlan0" mode = "AP" message = "Failed to return True when interface had mo...
5,320,162
def get_extensions() -> list: """ Gets extensions from the `features.yml` to be loaded into the bot :return: list """ log.info("Getting extensions...") exts = [] if osp.isfile(features_path): with open(features_path, 'r') as file: data = yaml.full_load(file) ...
5,320,163
def mini_batch_grad_descent(X, y, mini_batch_size=64, seed=0): """an implementation of the mini-batch gradient descent to improve the convergence speed""" np.random.seed(seed) m = X.shape[0] num_mini_batches = m // mini_batch_size mini_batches = [] permutation = list(np.random.permutation(m)) ...
5,320,164
def light_percentage_schema(gateway, child, value_type_name): """Return a validation schema for V_PERCENTAGE.""" schema = {"V_PERCENTAGE": cv.string, "V_STATUS": cv.string} return get_child_schema(gateway, child, value_type_name, schema)
5,320,165
def main(args): """ Pipeline for unsupervised ranking using graph and node features """ graph = load_graph(args.inputgraph) feat = load_features(args.inputfeature) print(type(graph)) if not args.directed: graph = np.concatenate((graph, graph[:, [1, 0]])) AR = AttriRank(grap...
5,320,166
def get_generator(ds_root, # dataset root directory (where to find meta.db file) batch_size=8192, # how many samples per batch to load mode='train', # mode of use of the dataset object (may be 'train', 'validation' or 'test') num_workers=None, # how many subproc...
5,320,167
def plot_flee_forecast(input_dir: str, region_names: list = None) -> None: """ Summary Args: input_dir (str): Description region_names (list, optional): Description """ print("INPUT DIRECTORY={}".format(input_dir)) # data_dir = os.path.join(input_dir, 'RUNS') # print("data_d...
5,320,168
def nodeclass_from_tag(tag): """Get the class for a reST node given its tag name. This searches in antidox's pseudo-elements, docutils' nodes and sphinx' addnodes. """ if tag in PseudoElementMeta.tag_map: return PseudoElementMeta.tag_map[tag] try: return getattr(addnodes, tag) ...
5,320,169
def observation_space(): """Return observation space. The state is (susceptible, exposed, infected, recovered). """ state_dim = State.num_variables() state_space_low = np.zeros(state_dim) state_space_high = np.inf * np.ones(state_dim) return spaces.Box(state_space_low, state_space_high, dtyp...
5,320,170
async def test_state_with_mac(hass, remote, wakeonlan): """Test for state property.""" await setup_samsungtv(hass, MOCK_CONFIG) assert await hass.services.async_call( DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: ENTITY_ID}, True ) state = hass.states.get(ENTITY_ID) assert state.state == STA...
5,320,171
def generate_sun_hits_products(dataset, prdcfg): """ generates sun hits products. Accepted product types: 'PLOT_SUN_HITS': Plots in a sun-radar azimuth difference-sun-radar elevation difference grid the values of all sun hits obtained during the processing period 'PLOT_SU...
5,320,172
def get_option_chains(symbol: str, expiry: str) -> pd.DataFrame: """ Parameters ---------- symbol : str Ticker to get options for expiry : str Expiration date in the form of "YYYY-MM-DD" Returns ------- chains: pd.DataFrame Dataframe with options for the gievn S...
5,320,173
def set_basic_data_pyxb(pyxb_class, element): """Helper function for save_teaser_xml to set the basic data Parameters ---------- pyxb_class : PyXBClass pyxb class representation of xml element : TEASERClass teaser class representation of a building element """ if type(ele...
5,320,174
def send_notification(summary, message="", icon=None, update=True): """This function takes information and sends a notification to the notification daemon using pynotify or notify-send. If update is set to False, a new notification will be created rather than updating the previous one""" if icon == None: ...
5,320,175
def _fid(mu1, sigma1, mu2, sigma2, eps=1e-6): """Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). Stable version by Dougal J. Sutherlan...
5,320,176
def _clip_raster_by_extent(raster, out_file, bounds, no_data): """ Clip raster by extent Parameters ---------- raster: pyrasta.raster.RasterBase out_file: pyrasta.io_.files.RasterTempFile bounds: tuple boundaries as (minx, miny, maxx, maxy) no_data: int or float No data valu...
5,320,177
def gen_structures_n(size: Tuple[int, int], n: int) -> Pylist: """Generates a list of numpy arrays, where each array is a grid representation of the adsorbate distribution, 1 means that an adsorbate is present on a grid space and 0 means that the adsorbate is not present Args: size (Tuple[int, ...
5,320,178
def get_neutron_subnetpool_name(subnet_cidr): """Returns a Neutron subnetpool name. :param subnet_cidr: The subnetpool allocation cidr :returns: the Neutron subnetpool_name name formatted appropriately """ name_prefix = cfg.CONF.subnetpool_name_prefix return '-'.join([name_prefix, subnet_cidr])
5,320,179
def test_chan_nonpositive_buffer(): """ WHEN n is buffer with a non-positive maxsize. EXPECT Throws a ValueError. """ buf = asyncio.Queue() with pytest.raises(ValueError): create_channel(buf)
5,320,180
def test_atomic_g_year_enumeration_4_nistxml_sv_iv_atomic_g_year_enumeration_5_4(mode, save_output, output_format): """ Type atomic/gYear is restricted by facet enumeration. """ assert_bindings( schema="nistData/atomic/gYear/Schema+Instance/NISTSchema-SV-IV-atomic-gYear-enumeration-5.xsd", ...
5,320,181
def verify(ui, repo): """verify the integrity of the repository Verify the integrity of the current repository. This will perform an extensive check of the repository's integrity, validating the hashes and checksums of each entry in the changelog, manifest, and tracked files, as well as the in...
5,320,182
def error500(request): """ http 500 page :param request: :return: """ return render(request, "50x.html", status=500)
5,320,183
def apply_anti_area( self: Player, target: Player, rules: dict, left: bool ) -> EffectReturn: """ Apply the effects of anti_attack: Take damage if self uses area """ if self.action == "area": self = inflict_damage(100, self) return self, target, rules
5,320,184
def as_utc(time): """Convert a time to a UTC time.""" return time.astimezone(pytz.utc)
5,320,185
def gelu_new(x): """ Implementation of the gelu activation function currently in Google Bert repo (identical to OpenAI GPT). Also see https://arxiv.org/abs/1606.08415 """ return 0.5 * x * (1 + th.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * th.pow(x, 3))))
5,320,186
def message(): """Mimic message abstraction""" def _message(fields): required_fields = { "is_direct": False, "is_private_chat": False, "is_group_chat": True, "will_is_mentioned": False, "will_said_it": False, "sender": "TBD", ...
5,320,187
def detail_url(product_id): """Return product detail Url""" return reverse('api:products-detail', args=[product_id])
5,320,188
def encode(data): """Encode data using LZ78 compression. Args: data: A str to encode. Returns: A list of two-element tuples of int and str. """ dictionary = {} index = itertools.count(1) word = '' result = [] for character in data: new_word = word + characte...
5,320,189
def add_password_arg(cmd, psw, required=False): """Append password switch to commandline.""" if UNRAR_TOOL == ALT_TOOL: return if psw is not None: cmd.append('-p' + psw) else: cmd.append('-p-')
5,320,190
def start_router(router_class, router_name): """Wrapper for starting a router and register it. Args: router_class: The router class to instantiate. router_name: The name to give to the router. Returns: A handle to newly started router actor. """ handle = router_class.remote...
5,320,191
def run_ghostscript(pdf_path: str, img_tmp: str) -> None: """ Run ghostscript as a subprocess over pdf files """ with tempfile.TemporaryFile() as gs_stdout, tempfile.TemporaryFile() as gs_stderr: subprocess.run(['gs', '-dBATCH', '-dNOPAUSE', ...
5,320,192
def completeness_scores(include_commutative=False): """ Provide a dict with the completeness scores of rings in database :param include_commutative: if False, it will filter out the specialized commutative Properties. If True, it will include all Properties. ...
5,320,193
def _is_activity_overlapping(df): """ checks if any activity is overlapping another Parameters ---------- df : pd.DataFrame """ assert df.shape[1] == 3 epsilon = pd.Timedelta('0ms') mask = (df[END_TIME].shift()-df[START_TIME]) > epsilon overlapping = df[mask] return not over...
5,320,194
def logarithmic(x, y, new_x): """ Linearly interpolates values in new_x based in the log space of y. Parameters ---------- x : array_like Independent values. y : array_like Dependent values. new_x : array_like The x values to return interpolated y values a...
5,320,195
def replace_num(s): """Remueve los numeros de los tweets""" for i in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]: s = s.replace(i, "") return s
5,320,196
def rotation_phi_beta(x, y, L, phi_deg, beta_deg, scale) : """Returns horizontal and vertical components of the scattering vector in units of scale (k) x, y can be arrays, L-scalar in the same units, ex. scale = k[1/A] or in number of pixels etc. """ xrot, yrot = rotation(np.array(x), np.array(y), ph...
5,320,197
def check_gtis(gti): """Check if GTIs are well-behaved. No start>end, no overlaps. Raises ------ AssertionError If GTIs are not well-behaved. """ gti_start = gti[:, 0] gti_end = gti[:, 1] logging.debug('-- GTI: ' + repr(gti)) # Check that GTIs are well-behaved assert np...
5,320,198
def _sample_rois(self, all_rois, gt_boxes, gt_labels, fg_rois_per_image, rois_per_image, num_classes): """Generate a random sample of RoIs comprising foreground and background examples. """ # overlaps: (rois x gt_boxes) overlaps = bbox_overlaps( np.ascontiguousarray(all_rois[:, 1:5], dtype=n...
5,320,199