content
stringlengths
22
815k
id
int64
0
4.91M
def fan_on(): """ Turn only the fan on """ global PAUSED print("Temps vary too much; toggling fan on") GPIO.output(HEATPIN, RELAYOFF) GPIO.output(COOLPIN, RELAYOFF) GPIO.output(FANPIN, RELAYON) while (loc_temp_diff > TEMPDIFF) and (PAUSED == False): time.sleep(10) if ...
34,300
def model_query(context, model, *args, **kwargs): """Query helper. :param context: context to query under :param session: if present, the session to use """ session = kwargs.get('session') or object_sqla.get_session() query = session.query(model, *args) return filter_by_project(context, q...
34,301
def bert_dropout_model(num_classes, bert_config, use_mc_dropout_mha=False, use_mc_dropout_att=False, use_mc_dropout_ffn=False, use_mc_dropout_output=False, channel_wise_dropout_mha=F...
34,302
def calculate_monthly_sales(year: int, month: int, beer_style: str) -> int: """Calculates the sales of a particular type of beer in a given month. param: month -- an int ranges from 1 to 12, beer_style; return: total_sales """ total_sales = 0 for item in data: if item[...
34,303
def check_canopy_height(region_info, regional_lookup): """ Check the regional canopy height. """ mean_canopy_height = region_info['mean_canopy_height'] if mean_canopy_height == 'no data': mean_canopy_height = 0 return mean_canopy_height
34,304
def annotated_var(prs): """ Parser for annotated variable in parentheses. Annotation is parsed with prs. Parser output is a var token annotation is stored in attribute 'annotation' of var token. Sample input to parser: (x : A) """ def trt(acc): v,ann = acc ...
34,305
def action_from_json(project, value): """return a action from the given json """ json_type = value.get('type') for class_ in sftoolbox.engine.action_classes_register: if json_type == class_.json_type: return class_.from_json(project, value) return DummyAction.from_json(project, ...
34,306
def get_springer_doi(node): """ :param node: :return: """ for elem in find_key(node, 'occurrence'): if isinstance(elem, list): for sub_elem in elem: if isinstance(sub_elem, dict): values = sub_elem.values() if len(values) =...
34,307
def check_versions(versions=[]): """ Check if there are version to build the changelog. """ if len(versions) == 0: raise NotEnoughVersionsError() return True
34,308
def create_fnet(widths, nfeat, nfeato, orthoinit, llbias): """ Creates feature-generating network, a multi-layer perceptron. Parameters: widths: list of widths of hidden layers nfeat, nfeato: # input and output channels of the convolution orthoinit: whether to use orthogonal weight initialization ...
34,309
def start_fun(): """ To start the program """ ag = argparse.ArgumentParser() ag.add_argument('data_dir',nargs='*', action='store',default="flowers") ag.add_argument('--arch', action='store', dest='arch', default= 'vgg19') ag.add_argument('--gpu',action='store',dest='gpu',default='gpu') ...
34,310
def pytorch_array_setitem(op): """Implementation of array_setitem for pytorch.""" def _impl(array, begin, end, strides, value): idx = tuple(slice(b, e, s) for b, e, s in zip(begin, end, strides)) ret = array.clone() ret[idx] = value return (ret,) return _impl, op.inputs[1:]
34,311
def invalidate_voucher_codes_with_campaign(affiliate, campaign): """Invalidates all codes under the given campaign name.""" voucher_codes = VoucherCode.objects.filter(batch__affiliate=affiliate, batch__campaign=campaign) LOGGER.info('Found %d codes with affilia...
34,312
async def help_(message: discord.Message, command: str.lower=None, *args): """ Display commands or their usage and description. """ command_prefix = config.server_command_prefix(message.server) # Display the specific command if command: if command.startswith(command_prefix): command...
34,313
def time_series_seasonal_test(x: pd.Series, expected_lags: list): """ 通过自相关系数来获取不同lag的相关系数,通过相关系数来判断时序数据的周期值 PS:需要列出lag的值的列表 :param x: 时序数据x,type: Series :param expected_lags: 可供选择的的滞后值 :return: 返回滞后值值的自相关性排序序列 """ acf_scores = [] for lag in expected_lags: acf_score = acf(x.v...
34,314
def test_get_registered_collectors(): """Test for the function get_registered_collectors().""" collectors = f8a_tagger.recipes.get_registered_collectors() assert collectors # ['Maven', 'NPM', 'PyPI', 'StackOverflow'] assert len(collectors) >= 4
34,315
def comment_like(): """ - 1.判断用户是否登陆 - 2.获取参数 - 3.校验参数,为空校验 - 4.操作类型校验 - 5.根据评论编号取出,评论对象 - 6.判断评论对象是否存在 - 7.根据操作类型,点赞,取消点赞 - 8.返回响应 :return: """ # - 1.判断用户是否登陆 if not g.user: return jsonify(errno=RET.NODATA, errmsg="用户未登录") # - 2.获取参数 comment_id = req...
34,316
def open_fits(subject, field, wavelength, size='2x2'): """Opens a FITS image of a subject. Can be used as a context handler. subject: RGZ subject dict, from the ATLAS survey. field: 'elais' or 'cdfs' wavelength: 'ir' or 'radio' size: Optional. '2x2' or '5x5'. -> FITS image file. """ ...
34,317
def ann_set(ax, fontsize, bracket_x, bracket_y, text_x, texta, textb): """ Annotate a set of spectra with text """ ax.plot( [bracket_x[0], bracket_x[1], bracket_x[1], bracket_x[0]], [bracket_y[0], bracket_y[0], bracket_y[1], bracket_y[1]], "k-", linewidth=3.0, ) t...
34,318
def spent_estimated_time_chart_by_user(chart_title, stat_extractor, file_path, period="month", measure="spent"): """ Creates a chart that shows spent and estimated (in that order) times by user. :param chart_title: :param stat_extractor: :param file_path: :param period: :param measure: :...
34,319
def create_relationships(model_cls, data): """ Create the relationship dict of the specified model class with the data :param model_cls: :param data: :return: """ relationships = model_cls.get_relationships() relationship_map = {} for key in relationships.keys(): re...
34,320
def get_news_items_from_web(url): """ Calls the Athletics News RSS API, parses the resulting response and returns a list of parsed news_items to be stored in DynamoDB :param url: Url for the RSS API for UBCO Heat :return: Parsed news items in a JSON formatted list """ try: request_r...
34,321
def get_node_model(manager, handle_id=None, node=None): """ :param manager: Context manager to handle transactions :type manager: Neo4jDBSessionManager :param handle_id: Nodes handle id :type handle_id: str|unicode :param node: Node object :type node: neo4j.v1.types.Node :return: Node mo...
34,322
def write_graph_file(filename, G, nodelist, write_header=True): """ write_graph_file() - write edge list in Pajek format Note that because snap.ConvertGraph() fails to keep node attributes so we cannot use it to renumber nodes, we also use nodelist to get a sequential node number for each node:...
34,323
def convert_hcp_plane(plane: list) -> np.ndarray: """ four index notion to three index notion for hcp and rhombohedral plane Args: plane (list): four index notion Returns: three index notion of plane """ u1 = plane[0] v1 = plane[1] w1 = plane[3] plane = [u1, v1, w1...
34,324
def should_process(data): """Quick check if processing is needed at all.""" from sentry.plugins import plugins for plugin in plugins.all(version=2): processors = safe_execute( plugin.get_event_preprocessors, data=data, _with_transaction=False ) if processors: ...
34,325
def load_fasta_file(input_file: str) -> Tuple[str, List]: """ Load a fasta file into a list of SeqRecords. :param input_file: The path to the input fasta file. :returns: A tuple of the sequence type ('protein' or 'dna'), and the list of SeqRecords. """ if _is_gzipped(input_file): openfu...
34,326
def files( files, out_dir, min_zoom, title, task_procs, procs_per_task, catalog_delim, cat_wcs_fits_file, image_engine, ): """--Convert a files to a map. CLI interface: files command.\n FILES should be a comma seperated list of files i.e. a.fits,b.fits,c.cat """ ...
34,327
def train_valid_test_datasets_provider(train_val_test_num_samples): """Build train, valid, and test datasets.""" args = get_args() print_rank_0('> building train, validation, and test datasets ' 'for GPT3 ...') train_ds, valid_ds, test_ds = build_train_valid_test_datasets( data...
34,328
def pred_and_plot_multiclass(model, filename, class_names, img_shape=[224,224], scale=True): """ Imports an imaged located at filename, makes a prediction with model and plots the image with the predicted class as the title. Need to import Tensorflow, matplotlib.image as mpimg """ img= load_and_prep_image(f...
34,329
def get(username, start): """ Second level function to pull up to 50 reviews. start - review number to start from """ r = requests.get( '{}/user/beers/?start={}&&ba={}&order=dateD&view=R'.format( BASE_URL, start, username ) ) beers = [] pq = PyQuery(r.text) ...
34,330
def isInContinent(country_name: str, continent: str): """Permet de vérifier si le pays est dans un continent Paramètres ---------- country_name : str Le nom du pays continent : str Le code du continent (alpha2) Retours ------- is_in_continent : int entier binair...
34,331
def test_base__BaseReader__canRead__3(): """It returns `False` if `getFieldNames()` returns an empty list.""" with patch.object(BaseReader, 'getFieldNames', return_value=[]): assert False is BaseReader.canRead(None)
34,332
def encoder_decoder_archi(inputs, is_train): """ Input is assumed to be a 4-D Tensor, with [batch_size, phrase_len, 1, features] """ encoder_layers = [] encoded = inputs encoder_layers.append(encoded) for i in range(config.encoder_layers): encoded = encoder_conv_block(encoded, i,...
34,333
def build_dict_conforming_to_schema(schema, **kwargs): """ Given a schema object (for example, TIMESTAMP_SCHEMA from this module) and a set of keyword arguments, create a dictionary that conforms to the given schema, using the keyword arguments to define the elements of the new dict. Checks the result to mak...
34,334
def drop_non_channels(overlaps_df, filename): """ Return the overlap dataframe with all channels dropped and index reset. Save the df as a csv with the filename passed this function. """ df = overlaps_df channels_df_dict = {} for column in df.columns: # For eac...
34,335
def main(): """ Find all the instances of the regular expression of the KO number in the file""" args = get_args() pattern = 'K{1}[0-9]{5}' result = re.findall(pattern, args.file.read()) # extract the konumbers from texg # the following are conversions to print in correct format resul...
34,336
def AddWorkloadMetadataFromNodeFlag(parser, hidden=False): """Adds the --workload-metadata-from-node flag to the parser. Args: parser: A given parser. hidden: Whether or not to hide the help text. """ help_text = """\ Sets the node metadata option for workload metadata configuration. This feature is sc...
34,337
def debug_task(self): """Simple testing task to debug celery.""" print('Request: {0!r}'.format(self.request))
34,338
def evaluate_all_flights(model, train_flights_dict, val_flights_dict, trial_folder, n_extreme_flights=10): """ Arguments model: trained tf model to make the predictions train_flights_dict: a dictionary whose key is flight name and value is a tuple of (features,labels) val_flights_...
34,339
def _train_with_autotune(root_dir): """Starts training using a tuner (i.e. Vizier). Args: root_dir: String directory to save the training results. """ study_name = 'aptamer_ff.%s' % (FLAGS.study_name or FLAGS.run_name) client_handle = '%s/%s' % (study_name, FLAGS.task) tuner = tf.training.HPTuner(clien...
34,340
def _REOM(y,t,pot,l2): """ NAME: _REOM PURPOSE: implements the EOM, i.e., the right-hand side of the differential equation INPUT: y - current phase-space position t - current time pot - (list of) Potential instance(s) l2 - angular momentum squared OU...
34,341
def optimize_inst(module, inst): """Simplify one instruction""" for operand in inst.operands: if isinstance(operand, ir.Id): if operand.inst.op_name not in ir.CONSTANT_INSTRUCTIONS: return inst if inst.op_name == 'OpCompositeConstruct': inst = optimize_OpComposit...
34,342
def main(argv): """Runs XROTOR over all desired conditions and output to a JSON file.""" # Parse flags. try: argv = FLAGS(argv) except gflags.FlagsError, e: print '\nError: %s\n' % e sys.exit(1) logging.basicConfig(stream=sys.stdout, format='%(asctime)s %(levelname)-8s %(mes...
34,343
def table_3_3(M, lambd_nos, lambd_cil): """ Функция для вывода Су для оживальной ГЧ arguments: число Маха, относительное удлинение носка и цилиндрической части return: Значение Су ГЧ """ cy1iz_alf_0 = [0.0350, 0.0350, 0.0350, 0.0350, 0.0362, 0.0375, 0.0380, 0.0378, 0.0374...
34,344
def test(): """ Ensure that DMC obtains the exact result for a hydrogen atom """ from pyscf import gto, scf from pyqmc.dmc import limdrift import pandas as pd mol = gto.M(atom="H 0. 0. 0.", basis="sto-3g", unit="bohr", spin=1) mf = scf.UHF(mol).run() nconf = 1000 configs = pyq.initial_g...
34,345
def ms_to_timestamp(ms): """Convert ms to 'HH:MM:SS,mmm'""" # XXX throw on overflow/underflow? if ms < 0: ms = 0 if ms > MAX_REPRESENTABLE_TIME: ms = MAX_REPRESENTABLE_TIME h, m, s, ms = ms_to_times(ms) return "%02d:%02d:%02d,%03d" % (h, m, s, ms)
34,346
def _lovasz_softmax_flat(y_pred, y_true, classes="present"): """ Multi-class Lovasz-Softmax loss y_pred: [P, C] Variable, class probabilities at each prediction (between 0 and 1) y_true: [P] Tensor, ground truth y_true (between 0 and C - 1) classes: 'all' for all, 'present' for classes present...
34,347
def m_rounding(m, weights): """ Control the M-value for rounding """ if not isinstance(m, int): raise ValueError('M for rounding should be an integer number') if m < len(weights): raise ValueError('M is lower than number of items in a sum')
34,348
def quantum_state_encoding_circuit(bits): """根据`bits`构建并返回量子态编码线路.""" circuit = cirq.Circuit() circuit.append(cirq.H.on_each(bits)) return circuit
34,349
def parse_mov_date(date_str): """converts string to date""" try: return datetime.datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S%z") except (TypeError, ValueError): pass return None
34,350
def get_settable_attr(attr): """ If attr is not settable, navigate upp in the connection hierarchy until we find the settable attribute. For example, in RigSqueeze, the ikFk state attribute will be redirected to the root ctrl. Note that in some case the attribute might have been piped in an utility node...
34,351
def adds(repo, subset, x): """Changesets that add a file matching pattern. The pattern without explicit kind like ``glob:`` is expected to be relative to the current directory and match against a file or a directory. """ # i18n: "adds" is a keyword pat = getstring(x, _(b"adds requires a pat...
34,352
def adjust_spines(ax, spines, position=5): """ Set custom visibility and position of axes ax : Axes Axes handle spines : List String list of 'left', 'bottom', 'right', 'top' spines to show position : Integer Number of points for position of axis """ for loc, spine in ...
34,353
def setup_experiment(exp_dir, config, resume = False): """Initializes a pretraining or RL experiment.""" # If the experiment directory doesn't exist yet, creates it and dumps the # config dict as a yaml file and git hash as a text file. # If it exists already, raises a ValueError to prevent overwriting # unl...
34,354
async def test_disabled(hass): """When enabled=False, everything fails.""" hass.states.async_set("switch.test", "on", {"friendly_name": "Test switch"}) request = get_new_request("Alexa.PowerController", "TurnOn", "switch#test") call_switch = async_mock_service(hass, "switch", "turn_on") msg = awai...
34,355
def repeat_exp(plan_func, n=1): """ Quick wrapper to repeat certain experiment, e.g. >> RE(repeat_exp(tomo_scan('tomo_scan_config.yml')), 2) """ for _ in range(n): yield from plan_func
34,356
def data_context_topology_context_topologyuuid_linklink_uuid_available_capacity_bandwidth_profile_committed_information_rate_get(uuid, link_uuid): # noqa: E501 """data_context_topology_context_topologyuuid_linklink_uuid_available_capacity_bandwidth_profile_committed_information_rate_get returns tapi.common.Ca...
34,357
def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ l = len(matrix) for i in range(l): for j in range(i, l): temp = matrix[i][j] matrix[i][j] = matrix[j][i] ...
34,358
def CreateMD5ChecksumFile(filename, mangled_filename=None): """Create and upload an MD5 checksum file for filename.""" if not mangled_filename: mangled_filename = os.path.basename(filename) checksum = CalculateMD5Checksum(filename) checksum_filename = '%s.md5sum' % filename with open(checksum_filename, ...
34,359
def parse_arguments() -> argparse.Namespace: """Parse the arguments.""" parser = argparse.ArgumentParser( description="Panoptic segmentation evaluation." ) parser.add_argument( "--gt", "-g", required=True, help="path to panseg ground truth" ) parser.add_argument( "--resul...
34,360
def get_similarity_graph( *, fullgraph: Union[str, BELGraph] = DEFAULT_FULLGRAPH_WITHOUT_CHEMSIM_PICKLE, rebuild: bool = False, mapping_file: str = DEFAULT_CHEMICALS_MAPPING_PATH, chemsim_graph_path=None, clustered: bool = True, weighted: bool = False, minimum_similarity: float = 0.7, ...
34,361
def update_mlwh_with_cog_uk_ids(samples: List[Dict[str, str]]) -> None: """Update the MLWH to write the COG UK barcode for each sample. Arguments: samples {List[Dict[str, str]]} -- list of samples to be updated """ if len(samples) == 0: return None # assign db_connection to avoid U...
34,362
def make_09f9(): """倉庫インベントリーフッタ""" return ""
34,363
def get_last_successful_hour_or_start_hour(): """Get the last hour that ran successfully or the start hour.""" last_hour = crash_stats.get_last_successful_hour() if last_hour: return last_hour return get_start_hour()
34,364
def print_hex_data(data, begin_offset=0, desc=""): """ print on stdout "hexdump -C < data" like output params: data - bytearray or array of int where each int < 255 begin_offset - int offset that should be printed in left column desc - str optional description to print on...
34,365
def encode_jwt(payload, secret): """ Return ``payload`` as a JWT encoded with ``secret``. Return a JWT whose payload is ``payload`` and that is signed using ``secret``. :arg payload: the payload to encode :type payload: dict :arg secret: the secret to sign the JWT with :type secret: st...
34,366
def make_model(): """ Loads pretrained torchvision model and redefines fc layer for car classification """ # uses about 1 GiB of GPU memory model = models.vgg19(pretrained = True) #model = models.resnet50(pretrained = True) in_feat_num = model.classifier[3].in_features mid_feat_num = int...
34,367
def empty_call_false(*args, **kwargs) -> bool: """ Do nothing and return False """ return False
34,368
def GenerateColumnAttributesReport(): """ * Perform key steps in order. """ print ("------------------------------") print ("GenerateNewETL") print ("------------------------------") # Get script arguments: args = GenerateNewETLJsonArgs() attributes = GenerateReportAndTable(args) ...
34,369
def cookie_is_encoded(data): """ Tests whether or not a cookie is encoded / HMAC signed -> #bool True if encoded .. from vital.security import cookie_is_encoded cookie_is_encoded( "!YuOoKwDp8GhrwwojdjTxSCj1c2Z+7yz7r6cC7E3hBWo=?IkhlbGxvLCB3b3JsZC4i") ...
34,370
def to_file(df, file_name, *args, **kwargs): """ Writes the DataFrame `df` to a file in `file_name`. This is an example implementation that delegates to `DataFrame.to_csv` and freezes some standard arguments. When rewriting this and switching to a different file format, you need to rewrite test...
34,371
def test_converter_convert_with_an_unknown_event_raises_an_exception( event, valid_uuid, caplog ): """Tests given an unknown event the convert method should raise an UnknownEventException. """ result = Converter(platform_url="", uuid_namespace=valid_uuid).convert( [event], ignore_errors=Fal...
34,372
def sync_ldap_truststore(manager, dest: str = "") -> None: """Pull secret contains base64-string contents of LDAP truststore and save it as a JKS file. :param manager: An instance of :class:`~jans.pycloudlib.manager._Manager`. :param dest: Absolute path where generated file is located. """ dest = d...
34,373
def plot_pump1(): """ This function would plot all the pumps bg getting the flow_rate in X_axis and head pump in y_axis. """ plt.figure(num=None, dpi=120) plt.plot(flux_rate1.flow_range(), Pump1.head_formula(), label="1.5HP(1.1kw)") plt.plot(flux_rate2.flow_range(), Pump...
34,374
def l2_normalize(x: torch.Tensor, eps: float = 1e-12) -> torch.Tensor: """Normalizes the input tensor using L2-norm. Args: x: Tensor to be normalized. eps: Small value to avoid division by zero. Returns: Normalized tensor. """ return x / (torch.norm(x, p=2, dim=1, keepdim=...
34,375
def ssq_cwt(x, wavelet='gmw', scales='log-piecewise', nv=None, fs=None, t=None, ssq_freqs=None, padtype='reflect', squeezing='sum', maprange='peak', difftype='trig', difforder=None, gamma=None, vectorized=True, preserve_transform=None, astensor=True, order=0, patience=0, ...
34,376
def publish_train_request_to_broker(): """publish_train_request_to_broker Publish a Train a DNN message to the Celery Worker's broker queue. This message is a JSON Dictionary. Default Broker: ``redis://localhost:6379/6`` Default Exchange: ``webapp.train.requests`` Default Routing Key: ``we...
34,377
def predict_image_classification(model: nn.Module, input_: torch.Tensor): """ Predict using an image classification model. Args: model (`nn.Module`): Pytorch model. input_ (`Tensor`): Input image tensor. Returns: (`tuple`) Prediction score whic...
34,378
def _id_to_box(id_, dim): """Convert id to box ID""" row = id_ // (dim ** 3) col = (id_ % (dim ** 2)) // dim return row * dim + col
34,379
def _load_hex(instream): """Load font from a .hex file.""" global_comment = [] glyphs = [] comment = [] for line in instream: line = line.rstrip('\r\n') if ':' in line: # parse code line key, value = line.rsplit(':', 1) value = value.strip() ...
34,380
def imshow(data, which, levels): """ Display order book data as an image, where order book data is either of `df_price` or `df_volume` returned by `load_hdf5` or `load_postgres`. """ if which == 'prices': idx = ['askprc.' + str(i) for i in range(levels, 0, -1)] idx.extend(['...
34,381
def make_small_graph(graph_description, create_using=None): """ Return the small graph described by graph_description. graph_description is a list of the form [ltype,name,n,xlist] Here ltype is one of "adjacencylist" or "edgelist", name is the name of the graph and n the number of nodes. This ...
34,382
def get_masksize(mask, labelnum = None): """ Compute mask size in surface space Parameters: ---------- mask: label image (mask) labelnum: mask's label number, use for group analysis Return: -------- masksize: mask size of each roi Example: -------- >>> masksize = g...
34,383
def _context_py2rpmversion(context): """get a python PEP0440 compatible version and translate it to an RPM version""" # the context needs a variable set via {% set upstream_version = 'ver' %} _context_check_variable(context, CONTEXT_VAR_UPSTREAM_VERSION, 'py2rpmversion') ...
34,384
def Scrrencapture_MACOS(jarvis, s): """ By holding Ctrl + Alt + Shift + R key we start screen capture in """ def engine(): pg.keyDown("command") pg.keyDown("shift") pg.press("5") pg.keyDown("shift") pg.keyUp("command") jarvis.say('Screen Recording Started') ...
34,385
def odInit(nodename): """ Create an Open Directory object to operate on the specified directory service node name. @param nodename: C{str} containing the node name. @return: C{object} an object to be passed to all subsequent functions on success, C{None} on failure. """
34,386
def testViewMenuOptions(base_fixture, qtbot): """ Test the view menu entries. Check, that activating the entry set the hide flag is set on the widget. """ temp_ini_path = os.path.join(tempfile.gettempdir(), "config.ini") settings = Settings(ini_file=Path(temp_ini_path)) config_file_path = b...
34,387
def check_and_format_address(address): """ check address """ try: formatted_address = to_checksum_address(address) return formatted_address except Exception as e: raise ArgumentsError("invalid address {}, reason: {}" .format(address, e))
34,388
def integration_tests(session): """ Nox run integration tests Args: session: nox session Returns: None Raises: N/A """ session.install("-U", "pip") if session.python == "3.6": session.install("dataclasses", "async_generator") session.install("-e"...
34,389
def get_cache_name(cache_type: str, tag: Optional[str] = None) -> str: """ Get the canonical cache name (e.g., "tmp.cache.mem.tag") for a type of cache. :param cache_type: type of a cache :param tag: optional unique tag of the cache, empty by default :return: name of the folder for a cache ...
34,390
def _aves2_cfg(): """ Read aipctl config """ config = ConfigObj() # The result is a merge of all the files as they appear in the list f_list = cfg_files() if not f_list: print("error: configuration file not found") exit(1) for f in cfg_files(): _cfg = ConfigObj(f, e...
34,391
def create_readme(top_dir,package_name,description="",docs=False): """ README requires the name of the package and the directory in which to write the file in. Optionally, give a description and whether or not to create a 'docs' directory. """ readme_str=""" # {package} ## Description {descrip...
34,392
def estimate_responsivity(mis_MU, norm_MU): """from the estimated base intensities, we return onlu users which have zero base intensity for misinformation and greater than zero base intensity for normal content. """ no_bad_intentions_ids = [] for id in range(len(mis_MU)): if mis_MU[id] ==...
34,393
def parse_field_constraint( x: Union[str, int, float, bool, list], constraint: str, type: str = "string", **field: Any, ) -> Union[str, int, float, bool, list, datetime.datetime, ConstraintTypeError]: """ Parse field constraint. Arguments: x: Constraint value. constraint: Co...
34,394
def test_burn(token_with_customer_balance: Contract, customer: str): """Burn tokens.""" token = token_with_customer_balance initial_balance = token.call().balanceOf(customer) initial_supply = token.call().totalSupply() amount = 1000 token.transact({"from": customer}).burn(amount) assert t...
34,395
def compute_ab_cycles(c_cycles, linear_combinations, g, tretkoff_graph): """ Returns the a- and b-cycles of the Riemann surface given the intermediate 'c-cycles' and linear combinations matrix. Input: - c_cycles - linear_combinations: output of the Frobenius transform of the """ linco...
34,396
def pmlb_multiclass_classification_dataset_names(): """Returns list of multiclass classification datasets in PMLB.""" try: name = pickle.load(open(".pmlb/mcdn.pkl", "rb")) except FileNotFoundError: pathlib.Path(".pmlb").mkdir(parents=True, exist_ok=True) name = [] for datase...
34,397
def get_loss(p, task=None): """ Return loss function for a specific task """ if task == 'edge': from losses.loss_functions import BalancedCrossEntropyLoss criterion = BalancedCrossEntropyLoss(size_average=True, pos_weight=p['edge_w']) elif task == 'semseg' or task == 'human_parts': ...
34,398
def main() -> None: """Run main loop. Listens for new connections.""" geneve_sock = socket.socket( socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP ) # Create a bind socket to let the outside world know # we're listening on `UDP_PORT`. Packets received on this # socke...
34,399