content
stringlengths
22
815k
id
int64
0
4.91M
def callback_on_failure(): """Simple callback on failure""" return False
78,200
def _reconstitute(cls, dict_, items): """ Reconstitute an ``OrderingList``. This is the adjoint to ``OrderingList.__reduce__()``. It is used for unpickling ``OrderingList``\\s """ obj = cls.__new__(cls) obj.__dict__.update(dict_) list.extend(obj, items) return obj
78,201
def id_attributes_map(dataset_path, id_field_names, field_names, **kwargs): """Return dictionary mapping of field attribute for each feature ID. Note: There is no guarantee that the ID field(s) are unique. Use ArcPy cursor token names for object IDs and geometry objects/ properties. ...
78,202
def modify_attack_types(id_, attack_types, user, **kwargs): """ Set the Indicator attack type. :param indicator_id: The ObjectId of the indicator to update. :type indicator_id: str :param attack_types: The new indicator attack types. :type attack_type: list,str :param user: The user updatin...
78,203
def _soft_update(model, target_model, tau): """Update parameters in the target policy and Q-value network.""" for t_param, param in zip(target_model.parameters(), model.parameters()): t_param.data.copy_(t_param.data * (1.0 - tau) + param.data * tau)
78,204
def ParseArgs(): """Parses command line arguments Args: None. Returns: None. """ parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(help='commands') # Install subparser. install_parser = subparsers.add_parser('install') install_parser.add_argument( 'install', action...
78,205
def addUpdateCarriers(): """ Add or Update a carrier """ db = DummySession() newgwid = None try: if not session.get('logged_in'): return redirect(url_for('index')) if (settings.DEBUG): debugEndpoint() db = SessionLoader() form = stripD...
78,206
def mdotvpw(M, v, w): """ M.v + w """ return vaddw(mdotv(M, v), w)
78,207
def get_ip(device): """ Return first ip on an interface """ cmd = "ip addr show dev %s" % device for i in execute(cmd): vals = i.lstrip().split() if (vals[0] == 'inet'): return vals[1] return ""
78,208
def index2int(index): """Helper function to convert timeindexes to ints""" return index.view(np.int64).reshape(-1,1)
78,209
def fetch_documents_front(document_id): """ Obtém o JSON do Document do Kernel com base no parametro 'document_id' """ return fetch_data("/documents/%s/front" % (document_id))
78,210
def get_positions( topology: PathLike, trajectory: List[str], *, mask: str = "all", stride: Optional[int] = None, ) -> NDArray[(Any, ...), Float]: """Read a molecular dynamics trajectory and retrieve the coordinates. Parameters ---------- topology : PathLike Topology file ...
78,211
def snd(pair): """Return the second element of pair """ return pair[1]
78,212
def test_is_autumn_for_southern_hemisphere(months): """Test returns true for autumn months on the southern hemisphere""" assert season_info(months.january, Hemisphere.SOUTHERN).is_autumn is False assert season_info(months.february, Hemisphere.SOUTHERN).is_autumn is False assert season_info(months.march...
78,213
def create_swagger_spec(): """ Swagger API definition. """ return jsonify(spec.to_dict())
78,214
def sleep(ms: int): """sleep for the given number of milliseconds."""
78,215
def reboot(): """ Reboot command """ useful.reboot("Reboot device")
78,216
def quicksort_hoare(a): """Quicksorts a list, using Hoare partitioning.""" def partition(low, high): swap_center_to_front(low, high) pivot = a[low] low -= 1 high += 1 while True: low += 1 while a[low] < pivot: low += 1 ...
78,217
def trimArgsKwargs(fn, givenArgs, givenKwargs=None): """ given function, and tuple and dict of args and kwargs, trim args to accepted length, and remove all but given kwargs from dict for use in signals - some functions just need to trigger on specific signals, while others may need more detail information passed ...
78,218
def get_estimator(batch_size=1, epochs=500, steps_per_epoch=128, model_dir=tempfile.mkdtemp(), path_brats=os.path.join(os.getenv('HOME'), 'fastestimator_data', 'BraTs')): """Args: path_brats: folder path of BraTs 2018 dataset, containin...
78,219
def load_release_gcc_settings(conf): """ Setup all compiler/linker flags with are shared over all targets using the gcc compiler for the "release" configuration """ v = conf.env conf.load_gcc_common_settings() COMPILER_FLAGS = [ '-O2', ] v['CFLAGS'] += COMPILER...
78,220
def norm_hue_channel(value): """Normalize hex channel.""" return norm_angle(value)
78,221
def latest_checkpoint(ckpt_dir, prefix='checkpoint_'): """Retrieve the path of the latest checkpoint in a directory. Args: ckpt_dir: str: directory of checkpoints to restore from. prefix: str: name prefix of checkpoint files. Returns: The latest checkpoint path or None if no checkpoints were found. ...
78,222
def _add_common_cc_options(version, **kwargs): """Add common C++ defines, compiler and linker options. This function will add common Xykivo C++ options to the given cc_library or cc_binary optional arguments. :param version: The version of the of the C++ target :param kwargs: Optional C++ target a...
78,223
def ServiceAccountCredentials(email, key_file=None, key_data=None): """Configure OAuth2 credentials for a Google Service Account. Args: email: The email address of the account for which to configure credentials. key_file: The path to a file containing the private key associated with the service acc...
78,224
def get_prop_type(value, key=None): """ Performs typing and value conversion for the graph_tool PropertyMap class. If a key is provided, it also ensures the key is in a format that can be used with the PropertyMap. Returns a tuple, (type name, value, key) """ if isinstance(key, unicode): ...
78,225
def get_pb_by_name(xml_parent, name): """ Searches for a pb_type with the given name inside a parent pb_type. Returns either a child or the parent. The provided parent may be a mode but a pb_type is always returned. """ assert xml_parent.tag in ["pb_type", "mode"], xml_parent.tag # Check t...
78,226
def getTimeframe(start: date, stop: date) -> str: """Given two dates, returns a stringified version of the interval between the two dates which is used to retrieve data for a specific time frame from Google Trends. """ return f"{start.strftime('%Y-%m-%d')} {stop.strftime('%Y-%m-%d')}"
78,227
def set_val(request): """AJAX POST for setting arbitrary values to an object.""" user = request.user msg = "fail" instance = None if request.method == 'POST': cid = request.POST.get('cid') oid = request.POST.get('oid') field = request.POST.get('field') instance_value ...
78,228
def h3_to_parent(h, res=None): """ Get parent of arrays of cells. Parameters ---------- h : array of H3Cells res: int or None, optional The resolution for the parent If `None`, then `res = resolution(h) - 1` Returns ------- array of H3Cells """ h = np.array(...
78,229
def writeconfig(filename,options,mode='w+'): """ Write the configuratin file """ options = options OPTION_CHAR = ' = ' f = open(filename,mode) key = sorted(options) for i in key: f.write(str(i)+str(OPTION_CHAR)+str(options[i])+'\n') f.close()
78,230
def packFileInfo(file, byte_order='<'): """ packs FileInfo object into bytearray b """ if file.address is None: raise ValueError('FileInfo object does not have an address') if (byte_order != '<') and (byte_order != '>'): raise ValueError('unknown byte_order: '+str(byte_order)) fmt=...
78,231
def debugLog(debug: bool = False, message: str = None): """Debug message when debug is enabled. :param debug: If we have debug enabled or not. :type debug: bool :param message: The message we want to print. :type message: str :example: >>> import djWasabi >>> djWasabi.generic.debugLog(...
78,232
def contenttype(filename, default='text/plain'): """ Returns the Content-Type string matching extension of the given filename. """ i = filename.rfind('.') if i >= 0: default = CONTENT_TYPE.get(filename[i:].lower(), default) j = filename.rfind('.', 0, i) if j >= 0: ...
78,233
def add_log_level(level_name, level_value, method_name=None): """Add a new logging level. Comprehensively adds a new logging level to the `logging` module and the currently configured logging class. Arguments: level_name (str): becomes an attribute of the `logging` module level_value (...
78,234
def _validate_mean_cols(df, fix=False): """ Validates contents of mean column in a given dataframe """ col = 'mean' if col in df.columns: # Check if columns are floats if not df[col].values.dtype == float: # Check whether values can be interpreted as floats ...
78,235
def search_async(start: datetime.datetime, end: datetime.datetime, programs: List[str] = None, platforms: List[str] = None, instrument_types: List[str] = None, metadata_filters: List[Dict] = None, response_format: Dict...
78,236
def test_post_reboot_wait_until_healthy_with_maintenance( run_cli, consul_cluster, forward_consul_port, default_config, reboot_in_progress, reboot_task, mocker): """ Test if we wait until consul checks are passing after reboot. Since none of these services have the tag "ignore_maintenance", ...
78,237
def publish_ego_car(ego_car_pub): """ Publish left and right 45 degree FOV lines and ego car model mesh """ marker_array = MarkerArray() marker = Marker() marker.header.frame_id = FRAME_ID marker.header.stamp = rospy.Time.now() marker.id = 0 marker.action = Marker.ADD marker.li...
78,238
def drawLegend(isHtml): """ This draws the legend box that goes beneath the scale bar and ASCII tree. """ if isHtml: print '<pre style="margin-left:2em;">' print '+ Legend %s+' % ('-' * 97) print ('| %3s %21s %3s %21s %3s %21s%26s |\n' '| %3s %21s %3s %21s %3s %21s %3s %21s |\n' ...
78,239
def delete_aip(mets_file): """Delete the file""" mets_instance = METS.query.filter_by(metsfile='%s' % (mets_file)).first() db.session.delete(mets_instance) db.session.commit() return render_template('deletesuccess.html')
78,240
def update_resource(RoleArn=None, ResourceArn=None): """ Updates the data access role used for vending access to the given (registered) resource in AWS Lake Formation. See also: AWS API Documentation Exceptions :example: response = client.update_resource( RoleArn='string', ...
78,241
def read_commandline_args(): """Read arguments passed on program execution""" parser = argparse.ArgumentParser() parser.add_argument('-v', '--verbose', action='store_true', help='print verbose output') config = vars(parser.parse_args()) if config.get('verbose'): con...
78,242
def bel_process_pybel_neighborhood(): """Process BEL Large Corpus neighborhood and return INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) genes = body.get('genes') bp = bel.process_pybel_neighborhoo...
78,243
async def source(dev: Device, scheme: str): """List available sources. If no `scheme` is given, will list sources for all sc hemes. """ if scheme is None: all_schemes = await dev.get_schemes() schemes = [str(scheme.scheme) for scheme in all_schemes] else: schemes = [scheme] ...
78,244
def _induced_power_cwt(data, sfreq, frequencies, use_fft=True, n_cycles=7, decim=1, n_jobs=1, zero_mean=False): """Compute time induced power and inter-trial phase-locking factor The time frequency decomposition is done with Morlet wavelets Parameters ---------- data : array...
78,245
def _resample_egde_for_node(sbm_graph, node_id): """Function to resample the nodes Attributes: sbm_graph (Object): Networkx Graph Object node_id (int): Id of the node to resample """ if sbm_graph._graph is None: sbm_graph.sample_graph() else: ...
78,246
def clean_tag_text(tag): """ Convert a tag to a string, with all extra whitespace removed. """ if tag is None: return None # Get tag text and remove soft hyphens added by Word text = tag.get_text().replace('\xad', '') return RE_CLEAN_TEXT.sub(' ', text).strip()
78,247
def fib(n): """ Devuelve el término n de la secuencia de Fibonacci @param n: posición a devolver @return: El término n de la secuencia """ pass # Tu codigo aqui
78,248
def get_xfmr_pose(pose: str, dim: int, **kwargs) -> nn.Module: """ Return position encodings layer Args: pose (str): positional encoding type, {abs|rel|xl|conv1d} """ if pose not in PosEncodings: raise ValueError(f"Unsupported pose layer: {pose}") return PosEncodings[pose](dim, *...
78,249
def base64_middleware(): """Provide a middleware configured with the Base64Backend.""" return EPDBServe(backend=Base64Backend(), serve_options={"port": 9000})
78,250
def log_mean(T_hi, T_lo, exact=False): """ compute the logarithmic mean """ if exact: from numpy import log return (T_hi-T_lo)/log(T_hi/T_lo) else: d = T_hi - T_lo return T_hi - d/2*(1 + d/6/T_hi*(1 + d/2/T_hi))
78,251
def getheader(header_text, default="ascii"): """Decode the specified header""" headers = decode_header(header_text) header_sections = [(text.encode(charset or default)).decode() if type(text) == str else text.decode(charset or default) for text, charset in headers] return ''....
78,252
def load_json(fp_in): """Loads JSON and returns items :param fp_in: (str) filepath :returns: data from JSON """ if not Path(fp_in).exists(): log.error('file does not exist: {}'.format(fp_in)) return {} with open(str(fp_in), 'r') as fp: data = json.load(fp) return data
78,253
def uniform_glorot(nin, nout, mean=0., gain=1., **kwargs): """ Uniform Glorot Initialization :param nin: :param nout: :param mean: :param gain: float or 'relu' :return: """ if gain == 'relu': gain = np.sqrt(2) logger.warn('Uniform Glorot weight with {} fan-in, {} fan-out,...
78,254
def elevate(command, param="", wait=False): """ Execute a shell command with elevated rights when the current user can have the privilge. Deisgned to be used with Windows Vista, 7 and 8. It also works on Windows XP although it is not necessary on many occasions. It may pops User Access Con...
78,255
def to_tiff(filepath, data, transform, no_data_val=None, crs=32633): """ Writes data to a tiff-file Args: filepath: path of new tiff file data: transform: no_data_val: crs: """ if len(data.shape) == 2: data = data[:, :, None] with rasterio.open( ...
78,256
def pearson_corrcoef(preds: Tensor, target: Tensor) -> Tensor: """ Computes pearson correlation coefficient. Args: preds: estimated scores target: ground truth scores Example: >>> from torchmetrics.functional import pearson_corrcoef >>> target = torch.tensor([3, -0.5, 2...
78,257
def get_local_env_method(method): # pylint:disable=too-many-return-statements """get a local environment method based on its name""" method = method.lower() if method.lower() == "crystalnn": # see eq. 15 and 16 in # https://pubs.acs.org/doi/full/10.1021/acs.inorgchem.0c02996 # for ...
78,258
def name_for(obj): """ Get a name for something. Allows overriding of default names using the `__alias__` attribute. """ if isinstance(obj, str): return obj cls = obj if isclass(obj) else obj.__class__ if hasattr(cls, "__alias__"): return underscore(cls.__alias__) els...
78,259
def reduceSet(setList): """Step through a list of sets and combine sets that overlap. This will create a unique list of sets, where each set contains the headers of reads that optical duplicates.""" setList2 = [setList[0]] for item1 in setList[1:]: inSetList2 = False for item2 ...
78,260
def weird_compare(interval, start, end): """ This is a function that is used later on in data_upscale, to add a corrective integer (either 1 or 0), when that function checks whether the image it is working on has reached the border. This function is not expected to be used anywhere outside data_upscale....
78,261
def make_word(letters, beginnings=[], endings=[]): """Return word dictionary""" return { 'word': ''.join(letters), 'letters': letters, 'beginnings': beginnings, 'endings': endings, }
78,262
def dependence_vector(iter_vars, iter_slices, source, sink, invariant=None): """ Uses ISL for dependence testing and returns the dependence vector. iter_vars: Iteration variables iter_slices: Iteration starts, stops and steps; stop is inclusive! source, sink: Subscript objects invariant: Loop i...
78,263
def get_role(classpath): """Get a role implementation by its path name.""" return importlib.get_class(classpath, __name__)
78,264
def run_command(command, work_dir='.', skip_output=True, shell=False): """Runs a generic command without capturing its output. Args: command (list[str]): List of command parts (like in constructor of Popen) work_dir (str): Working directory in which the command should be run. skip_outpu...
78,265
def compute_batch_accuracy(output, target): """Computes the accuracy for a batch""" with torch.no_grad(): batch_size = target.size(0) _, pred = output.max(1) correct = pred.eq(target).sum() return correct * 100.0 / batch_size
78,266
def get_ram_memory(units="Mb"): """Get the RAM memory of the current machine. Args: units (str): Units [bytes, Kb, Mb, Gb] Returns: float: Memory size. Examples: >>> num = get_ram_memory("Gb") >>> num >= 4 True """ s_bytes = psutil.virtual_...
78,267
def gsl_blas_zswap(*args, **kwargs): """gsl_blas_zswap(gsl_vector_complex * X, gsl_vector_complex * Y) -> int""" return _gslwrap.gsl_blas_zswap(*args, **kwargs)
78,268
def create_user(): """Endpoint to create a user data.""" data = json.loads(request.data) password = data['password'].encode('utf-8') hashed = bcrypt.hashpw(password, bcrypt.gensalt()) user = User(username=data['username'], password=hashed.decode('utf-8'), phone=data['phone'], addres...
78,269
def valid_proof(last_hash, proof, difficulty): """ Validates the Proof: Multi-ouroborus: Do the last six characters of the hash of the last proof match the first six characters of the proof? IE: last_hash: ...AE9123456, new hash 123456888... """ # TODO: Your code here! last_hash = ...
78,270
def true_auth_user(true_auth_client_user): """Expensive authenticated user""" yield true_auth_client_user[1]
78,271
def test_main_test10(m_isfile, m_procconf, m_testcon, m_testenv, m_testapp, m_procjob, m_schedprep, m_stagup, m_sub, m_mon, m_del, m_stagdown, m_clean): """Test the keyboard interrupt feature with running jobs.""" m_isfile.return_value = True args = ["longbow", "...
78,272
def set_mon_sites(node: CephAdmin, tiebreaker_node) -> bool: """ Adds the mon daemons into the two sites with arbiter node at site 3 as a tie breaker Args: node: Cephadm node where the commands need to be executed tiebreaker_node: name of the monitor to be added as tie breaker( site 3 ) ...
78,273
def test_framework_run_operator(): """Check for Operator Framework was successful.""" checker = Framework() with patch.object(Framework, "_check_operator", lambda self, path: True): result = checker.run("somepath") assert result == Framework.Result.operator assert checker.text == "The charm ...
78,274
def data_together(filepath): """ :param filepath: all the csv files with raw data :return: """ csvs = [] dfs = [] for subdir, dirs, files in os.walk(filepath): for file in files: filepath = subdir + os.sep + file if filepath.endswith(".csv"): ...
78,275
def conv1d( ni: int, no: int, ks: int = 1, stride: int = 1, padding: int = 0, bias: bool = False ): """Create and initialize a `nn.Conv1d` layer with spectral normalization. Unmodified from https://github.com/fastai/fastai/blob/5c51f9eabf76853a89a9bc5741804d2ed4407e49/fastai/layers.py """ conv ...
78,276
def main(): """ Genera un registro de actividades sobre las consultas enviadas a Georef API Return: None """ try: seconds = 0 queries_length_requested = len(QUERIES) * QUERIES_AVG_REQUESTED print('-- Iniciando test de consultas. Total de consultas: {}.' .format...
78,277
def _GetPrincipalQuantumNumber(atNum): """ *Internal Use Only* Get the principal quantum number of atom with atomic number equal to atNum Parameters: atNum: int Returns: PrincipalQuantumNumber: int """ if atNum <= 2: return 1 elif ...
78,278
def wrap_single_convertor(convert_single): """ Wraps a ``__ua_convert__`` defined for a single element to all elements. If any of them return ``NotImplemented``, the operation is assumed to be undefined. Accepts a signature of (value, type, coerce). """ @functools.wraps(convert_single) ...
78,279
def rot(theta): """returns a 2D-rotation matrix with rotation angle theta""" R = np.array(((cos(theta), -sin(theta)), (sin(theta), cos(theta)))) return R
78,280
def integrate(params, t, gamma_max, nu_max, phiR, Kd=Kd): """ Integrates the system of differential equations, including the dilution factor and assumes that nutrient concentration is high enough such that nu ≈ nu_max. """ # Unpacking Mr, Mp, cAA = params gamma_max, nu_max, phiR = args...
78,281
def build_streamflow_cube(nc_files, river_ids=None, consistent_id_order=True): """Reads streamflow from several NWM files into a single array. Reads streamflow from several files into a single array. Each file from the National Water Model represents a single time step. This function can be used to rea...
78,282
def shutdown(pj): """Shutdown Pi.""" shutdown_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") update_tag("SHUTDOWN_TIME", shutdown_time) set_alarm(SLEEP_INTERVAL) pj.power.SetPowerOff(60) balena.models.supervisor.shutdown(device_uuid=os.environ['BALENA_DEVICE_UUID'], ...
78,283
def mutate(mushroom, i): """ Randomly flips one bit in a mushroom bit string""" return mushroom ^ 1 << i
78,284
def avoid_multiple_update(func): """Decorator to prevent handlers to update multiple times.""" def wrapper(self, attr, old, new): if self.in_update: return self.in_update = True func(self, attr, old, new) self.in_update = False return wrapper
78,285
def zeros(shape, dtype=float): """ Array of zeros. Return an array of given shape and type, filled with zeros. Parameters ---------- shape : {sequence of ints, int} Shape of the array dtype : data-type, optional The desired data-type for the array, default is np.float64. ...
78,286
def invalidate_acr_caches(mapper, content, target): # pylint: disable=unused-argument """Clear `global_role_names` if ACR created or update or deleted.""" if hasattr(flask.g, "global_role_names"): del flask.g.global_role_names if hasattr(flask.g, "global_ac_roles"): del flask.g.global_ac_roles
78,287
def on_message(mqtt_client, data_object, msg): # pylint: disable=W0613 """Default callback on MQTT message.""" logger.error("Don't publish to %s", msg.topic)
78,288
def node_draw_color(node): """given a row of a nodes() dataframe, return the color it should be drawn""" if 'draw_color' in node.axes[0]: # if this value has already been calculated return node.draw_color color = '#d2d2e6' # (210, 210, 230) #default color if 'HoursFlooded' in node and...
78,289
def tabulated(dr: Array, spline: Callable[[Array], Array], **unused_kwargs) -> Array: """ Tabulated radial potential between particles given a spline function. Args: dr: An ndarray of pairwise distances between particles spline: A function computing the spline values at a given pairwise dis...
78,290
def create_slice_mask(plane_dict, infile_dims): """Create a binary array defining a mask covering the area below a given plane in the 3D image. :type plane_dict: dict :param plane_dict: A dictionary matching z voxel coordinates to corresponding (x,y) coordinates. :type infile...
78,291
def postprocess_braces(value, **options): """Remove any braces from a string value.""" if bibpy.is_string(value): return "".join([e for e in bibpy.parser.parse_braced_expr(value) if e not in '{}']) return value
78,292
def row2dict(row): """ Converts a row of SQLAlchemy into a dictionary :see: http://stackoverflow.com/questions/1958219/convert-sqlalchemy-row-object-to-python-dict :param row: SQLAlchemy row :return: dictionary """ if row is None: return None d = {} if hasattr(row, '__table_...
78,293
def retrieve_by_index(index_dir_path: str, question: str, top_k: int=1) -> List[str]: """ Retrieves the most relevant passages to a question, using the indexed embedding of the passages. :param index_dir_path: path to the index and texts. :param question: :param top_k: number of relevant passages t...
78,294
def init_dist(opt, local_rank): """ Adopted from BasicSR """ if mp.get_start_method(allow_none=True) is None: mp.set_start_method('spawn') torch.cuda.set_device(local_rank) dist.init_process_group(backend='nccl') rank, world_size = get_dist_info() opt.update({ 'dist': True,...
78,295
def _output_to_existing(parsed_file: parse.PyTestGenParsedFile, output_dir: str, include: List[str] = []) -> None: """Output the tests in 'parsed_file' to an existing file, optionally only including a whitelist of functions to output tests for. This function w...
78,296
def run_batch_qc(gid, input_dir, adapter=None, contaminants=None, exclude=[], kmers=8, out_dir=".", threads=1): """Builds group directory tree which holds individual sample QCs. Args: gid (str): unique ID, e.g. experiment ID input_dir (str): path of directory containing FASTQ files adap...
78,297
def unsigned_to_signed(seq, width): """ Convert unsigned integer to signed. """ out = [] k = pow(2, width) for x in seq: if x >= k/2: x -= k out.append(x) return out
78,298
def action(arguments): """ Given parsed arguments, filter input files. """ if arguments.quality_window_mean_qual and not arguments.quality_window: raise ValueError("--quality-window-mean-qual specified without " "--quality-window") if trie is None or triefind is None: ...
78,299