content
stringlengths
22
815k
id
int64
0
4.91M
def getFileList(*args, **kwargs): """ Returns a list of files matching an optional wildcard pattern. Note that this command works directly on raw system files and does not go through standard Maya file path resolution. Flags: - filespec : fs (unicode) [create] ...
5,358,100
def export_descriptor(config, output_dir, args): """ # input 2 images, output keypoints and correspondence save prediction: pred: 'image': np(320,240) 'prob' (keypoints): np (N1, 2) 'desc': np (N2, 256) 'warped_image': np(320,240) 'warped_p...
5,358,101
def test_left_right_transitions_linear(): """Set a transition matrix generated by a left-right topology on a linear HMM""" hmm = deepcopy(hmm_lr) topology = _LinearTopology(n_states=5, random_state=rng) transitions = topology.random_transitions() hmm.transitions = transitions assert_equal(hmm.tr...
5,358,102
def LinkSigningChain(*certs): """Sets up the parent cert ID property values for a chain of certs.""" for i, cert in enumerate(certs): if i == len(certs) - 1: cert.parent_certificate_id = 0 else: cert.parent_certificate_id = certs[i + 1].id
5,358,103
def meta_caption(meta) -> str: """makes text from metadata for captioning video""" caption = "" try: caption += meta.title + " - " except (TypeError, LookupError, AttributeError): pass try: caption += meta.artist except (TypeError, LookupError, AttributeError): ...
5,358,104
def ticket_id_correctly_formatted(s: str) -> bool: """Checks if Ticket ID is in the form of 'PROJECTNAME-1234'""" return matches(r"^\w+-\d+$|^---$|^-$")(s)
5,358,105
def test_1(): """ f(x) = max(.2, sin(x)^2) """ test_graph = FunctionTree('Test_1') max_node = Max('max') const_node = Constant('0.2', .2) square_node = Square('square') sin_node = Sin('sin') test_graph.insert_node(max_node, 'Output', 'x') test_graph.insert_node(square_node, 'max'...
5,358,106
def export_vector(vector, description, output_name, output_method='asset'): """Exports vector to GEE Asset in GEE or to shapefile in Google Drive. Parameters ---------- vector : ee.FeatureCollection Classified vector segments/clusters. description : str Description of the expor...
5,358,107
def gather_competition_data(comp_url, target_directory=None): """ gather all competition data from the url: "https://www.digitalrock.de/dav_calendar.php?no_dav=1&year=2019" :return: - nothing - but side efect are the competition files in target directory """ print("Fetching co...
5,358,108
def fetch_configs(config=''): """ Fetch config files from the remote, via rsync. Specify a config directory, such as 'cylinder' to copy just one config. Config files are stored as, e.g. cylinder/config.dat and cylinder/config.xml Local path to use is specified in machines_user.json, and should n...
5,358,109
def test_bytes_head(path): """It should get the first lines of a file as bytes""" assert bytes_head(path('0_0.csv'), 1) == b'a,b\n' assert bytes_head(path('0_0.csv'), 100) == b'a,b\n0,0\n0,1'
5,358,110
def reminder() -> None: """Send reminder if no entry as of certian times""" utc_now = pytz.utc.localize(datetime.datetime.utcnow()) # Heroku scheduler usually runs a couple mins after hour, not at top, so just hour compared now = datetime.datetime.strftime(utc_now.astimezone(pytz.timezone("America/Chic...
5,358,111
def optimize_centers_mvuiq(A, B, Q, centers, keep_sparsity=True): """ minimize reconstruction error after weighting by matrix A and make it unbiased min_{c_i} \|A.(\sum_i Q_i c_i) - B\|_F^2 such that sum(B-A(\sum_i Q_i c_i)) = 0 """ num_levels = len(centers) thr = sla.norm(A) * 1e-6 # 1- co...
5,358,112
def container_instance_task_arns(cluster, instance_arn): """Fetch tasks for a container instance ARN.""" arns = ecs.list_tasks(cluster=cluster, containerInstance=instance_arn)['taskArns'] return arns
5,358,113
def sierpinski_triangle(order, length, upper_left_x, upper_left_y): """ :param order: int, the order of Sierpinski Triangle :param length: int, the length of order n Sierpinski Triangle :param upper_left_x: str, the upper left x coordinate of order n Sierpinski Triangle :param upper_left_y: str, the upper left y c...
5,358,114
def control_logic(center_x,center_y): """ Purpose: --- This function should implement the control logic to balance the ball at a particular setpoint on the table. The orientation of the top table should "ONLY" be controlled by the servo motor as we would expect in a practical scenario. Hence "ONLY" the shaft ...
5,358,115
def benchmark(pipelines=None, datasets=None, hyperparameters=None, metrics=METRICS, rank='f1', distributed=False, test_split=False, detrend=False, output_path=None): """Evaluate pipelines on the given datasets and evaluate the performance. The pipelines are used to analyze the given signals and l...
5,358,116
def notNone(arg,default=None): """ Returns arg if not None, else returns default. """ return [arg,default][arg is None]
5,358,117
def get_scorer(scoring): """Get a scorer from string """ if isinstance(scoring, str) and scoring in _SCORERS: scoring = _SCORERS[scoring] return _metrics.get_scorer(scoring)
5,358,118
def triangle_num(value: int) -> int: """Returns triangular number for a given value. Parameters ---------- value : int Integer value to use in triangular number calculaton. Returns ------- int Triangular number. Examples: >>> triangle_num(0) 0 >>> t...
5,358,119
def show_whole_td_msg(whole_td_msg): """ 显示完整的td_msg :param whole_td_msg: np.ndarray, shape=(20, 16, 200, 1000) :return: """ img_path = '../tmp/td_msg' for tag in range(20): final = np.zeros((200, 1000), dtype=np.uint8) for i in range(16): pic = np.zeros((200, 100...
5,358,120
def locations_sim_euclidean(image:DataBunch, **kwargs): """ A locations similarity function that uses euclidean similarity between vectors. Predicts the anatomical locations of the input image, and then returns the eucliean similarity between the input embryo's locations vector and the locations vectors...
5,358,121
def assert_almost_equal( actual: Tuple[numpy.float64, numpy.float64], desired: List[numpy.float64], decimal: int, err_msg: Literal["(4, 200)normal"], ): """ usage.statsmodels: 1 """ ...
5,358,122
def _butter_bandpass_filter(data, low_cut, high_cut, fs, axis=0, order=5): """Apply a bandpass butterworth filter with zero-phase filtering Args: data: (np.array) low_cut: (float) lower bound cutoff for high pass filter high_cut: (float) upper bound cutoff for low pass filter fs...
5,358,123
def transform_and_normalize(vecs, kernel, bias): """应用变换,然后标准化 """ if not (kernel is None or bias is None): vecs = (vecs + bias).dot(kernel) return vecs / (vecs**2).sum(axis=1, keepdims=True)**0.5
5,358,124
def mpesa_response(r): """ Create MpesaResponse object from requests.Response object Arguments: r (requests.Response) -- The response to convert """ r.__class__ = MpesaResponse json_response = r.json() r.response_description = json_response.get('ResponseDescription', '') r.error_code = json_response.get('e...
5,358,125
def swap_flies(dataset, indices, flies1=0, flies2=1): """Swap flies in dataset. Caution: datavariables are currently hard-coded! Caution: Swap *may* be in place so *might* will alter original dataset. Args: dataset ([type]): Dataset for which to swap flies indices ([type]): List of ind...
5,358,126
def get_log_events(logGroupName=None, logStreamName=None, startTime=None, endTime=None, nextToken=None, limit=None, startFromHead=None): """ Lists log events from the specified log stream. You can list all the log events or filter using a time range. By default, this operation returns as many log events as ...
5,358,127
def test_event_data(create_main_loop): """Test after_epoch and after_batch event args match the expectation.""" recording_hook = DataRecordingHook() model, dataset, mainloop = create_main_loop(epochs=3, model_class=RecordingModel, extra_hooks=[recording_hook],...
5,358,128
def periodic_kernel(avetoas, log10_sigma=-7, log10_ell=2, log10_gam_p=0, log10_p=0): """Quasi-periodic kernel for DM""" r = np.abs(avetoas[None, :] - avetoas[:, None]) # convert units to seconds sigma = 10**log10_sigma l = 10**log10_ell * 86400 p = 10**log10_p * 3.16e7 g...
5,358,129
def emails(request): """ A view to send emails out to hunt participants upon receiving a valid post request as well as rendering the staff email form page """ teams = Hunt.objects.get(is_current_hunt=True).real_teams people = [] for team in teams: people = people + list(team.person_...
5,358,130
def _stochastic_universal_sampling(parents: Population, prob_distribution: list, n: int): """ Stochastic universal sampling (SUS) algorithm. Whenever more than one sample is to be drawn from the distribution the use of the stochastic universal sampling algorithm is preferred compared to roulette wheel algor...
5,358,131
def format_exception_with_frame_info(e_type, e_value, e_traceback, shorten_filenames=False): """Need to suppress thonny frames to avoid confusion""" _traceback_message = "Traceback (most recent call last):\n" _cause_message = getattr( traceback, "_cause_message", ("\nThe above exce...
5,358,132
def _add_simple_procparser(subparsers, name, helpstr, func, defname='proc', xd=False, yd=False, dualy=False, other_ftypes=True): """Add a simple subparser.""" parser = _add_procparser(subparsers, name, helpstr, func, defname=defname) _add_def_args(parser, xd=xd, yd=yd, dualy=dualy...
5,358,133
def save_instrument_data_reference(msg_struct): """Checks to see if there is already an instrument data reference for this event code, and if there isn't, creates one. Instrument data references are used to allow the servers to track which events are pertinent to a particular instrument (some events are for...
5,358,134
def addSortMethod(handle, sortMethod): """A stub implementation of the xbmcplugin addSortMethod() function""" return
5,358,135
def get_volumes(fn): """Return number of volumes in nifti""" return int(subprocess.check_output(['fslnvols', fn]))
5,358,136
async def _execSubprocess(command: str) -> tuple[int, bytes]: """Execute a command and check for errors. Args: command (str): commands as a string Returns: tuple[int, bytes]: tuple of return code (int) and stdout (str) """ async with SEM: process = await asyncio.create_subprocess_shell( command, stdo...
5,358,137
def submit_job(app_id, app_key, task_id, mimetype, text_col, dedupe): """Submit a job to the queue for the Celery worker. Create the required JSON message and post it to RabbitMQ.""" # These are the args that the Python function in the adjunct processor will use. kwargs = {"app_id": app_id, "a...
5,358,138
def comprspaces(*args): """ .. function:: comprspaces(text1, [text2,...]) -> text This function strips (from the beginning and the end) and compresses the spaces in its input. Examples: >>> table1(''' ... ' an example with spaces ' 'another example with spaces ' ...
5,358,139
def find_available_port(): """Find an available port. Simple trick: open a socket to localhost, see what port was allocated. Could fail in highly concurrent setups, though. """ s = socket.socket() s.bind(('localhost', 0)) _address, port = s.getsockname() s.close() return port
5,358,140
def redirect_std(): """ Connect stdin/stdout to controlling terminal even if the scripts input and output were redirected. This is useful in utilities based on termenu. """ stdin = sys.stdin stdout = sys.stdout if not sys.stdin.isatty(): sys.stdin = open_raw("/dev/tty", "r", ...
5,358,141
def merge_deep(dct1, dct2, merger=None): """ Deep merge by this spec below :param dct1: :param dct2: :param merger Optional merger :return: """ my_merger = merger or Merger( # pass in a list of tuples,with the # strategies you are looking to apply # to each ty...
5,358,142
def step( context, bind_to, data, title='', area=False, x_is_category=False, labels=False, vertical_grid_line=False, horizontal_grid_line=False, show_legend=True, zoom=False, group_tooltip=True, height=None, width=None ): """Generates javascript code to show a 'step' chart. ...
5,358,143
def get(user_request, url, **kwargs): """ A wrapper of requests.get. This method will automatically add user's session key as the cookie to enable sso Sends a GET request. Returns :class:`Response` object. :param user_request: The http request contains the authentication key and is triggered by user. ...
5,358,144
def get_baseline_y(line: PageXMLTextLine) -> List[int]: """Return the Y/vertical coordinates of a text line's baseline.""" if line_starts_with_big_capital(line): return [point[1] for point in line.baseline.points if point[1] < line.baseline.bottom - 20] else: return [point[1] for point in li...
5,358,145
def get_device_type(dev, num_try=1): """ Tries to get the device type with delay """ if num_try >= MAX_DEVICE_TYPE_CHECK_RETRIES: return time.sleep(1) # if devtype is checked to early it is reported as 'unknown' iface = xwiimote.iface(dev) device_type = iface.get_devtype() if not device...
5,358,146
def register_barrier(): """So we don't have multiple jobs running simulateously""" register_job( user="vogels", project="sgd", experiment=experiment, job="barrier", priority=priority, n_workers=16, config_overrides={}, runtime_environment={"clone":...
5,358,147
def index(): """ This is the grocery list. Concatenates the ingredients from all the upcoming recipes The ingredients dict that we pass to the template has this structure { "carrot": { "g": 200, "number": 4, "str": "200g, 4number", }, "salt...
5,358,148
def test_Fit_MinFunc(): """ There are times where I don't pass just a simple function to the fitting algorithm. Instead I need to calculate the error myself and pass that to the model. This tests that ability. """ init = { 'm': 20, 'b': -10 } def func(X, *args): ...
5,358,149
def BOP(data): """ Balance of Power Indicator :param pd.DataFrame data: pandas DataFrame with open, high, low, close data :return pd.Series: with indicator data calculation results """ fn = Function('BOP') return fn(data)
5,358,150
def get_infinite(emnist_client_data, num_pseudo_clients): """Converts a Federated EMNIST dataset into an Infinite Federated EMNIST set. Infinite Federated EMNIST expands each writer from the EMNIST dataset into some number of pseudo-clients each of whose characters are the same but apply a fixed random affine ...
5,358,151
def extractHavingSubDomain(): """ [Passive] Sets the having_Sub_Domain feature after checking how many sub-domains the hostname has. This number include the "www." prefix and the top level domain like ".com" or ".uk" 1) -1 if the hostname has more than 3 parts after splitting along '.' ie "www." + some ...
5,358,152
def exec_crossover_once(ind1, ind2, cxpoint, n_degree): """single point crossover for two individuals Parameters ---------- ind1: individual 1 ind2: individual 2 cxpoint: crossover point n_degree: number of degree """ g1 = ind1.G g2 = ind2.G x = np.min(cxpoint) y = ...
5,358,153
def create_plot(df, title, carbon_unit, cost_unit, ylimit=None): """ :param df: :param title: string, plot title :param carbon_unit: string, the unit of carbon emissions used in the database/model, e.g. "tCO2" :param cost_unit: string, the unit of cost used in the database/model, e.g. "USD"...
5,358,154
def get_app(name, **kwargs): """Returns an instantiated Application based on the name. Args: name (str): The name of the application kwargs (dict): Keyword arguments used for application instantiation Returns: deepcell.applications.Application: The instantiated application """ ...
5,358,155
def test_subscriber__CreatorAnnotator__1(person): """`CreatorAnnotator` sets the creator on adding a person with browser.""" assert u'global editor' == IEditor(person).creator
5,358,156
def worker_complete(): """Complete worker.""" participant_id = request.args.get('participant_id') if not participant_id: return error_response( error_type="bad request", error_text='participantId parameter is required' ) try: _worker_complete(participant_...
5,358,157
def combine(connected_events): """ Combine connected events into a graph. :param connected_events: see polychronous.filter :return: graph_of_connected_events """ graph_of_connected_events = nx.Graph() graph_of_connected_events.add_edges_from(connected_events) return (graph_of_connected_e...
5,358,158
def set_config(**kwargs): """ Set SleepECG preferences and store them to the user configuration file. If a value is `None`, the corresponding key is deleted from the user configuration. See :ref:`configuration` for a list of possible settings. Parameters ---------- **kwargs: dict, opti...
5,358,159
def calculate_hash(filepath, hash_name): """Calculate the hash of a file. The available hashes are given by the hashlib module. The available hashes can be listed with hashlib.algorithms_available.""" hash_name = hash_name.lower() if not hasattr(hashlib, hash_name): raise Exception('Hash algorithm ...
5,358,160
def specify_run_step( args: RunConfig, aml_resources: AMLResources, run_script_path: Path, loop_config_class: Type[OptimizerConfig], check_consistency: bool = True, ) -> Tuple[List[PythonScriptStep], List[PipelineData], Dict[str, List[str]], List[str]]: """ Create the pipeline step(s) to run...
5,358,161
def upgrade_to_blender2910(nodes): """ Blender 2.91 adds a new input to the BSDF node, emit strength in slot 18, moving the previous slot 18 up etc. Anything that connect to slot 18 or above from before 2.91 will have it's slot number increased by one. The input default values will also be updated to ma...
5,358,162
def default_mp_value_parameters(): """Set the different default parameters used for mp-values. Returns ------- dict A default parameter set with keys: rescale_pca (whether the PCA should be scaled by variance explained) and nb_permutations (how many permutations to calculate emp...
5,358,163
def change_auth_keys(server, user, auth_keys): """ update authorize keys. ath_keys is list of keys. will get current auth_keys, remove keys with auth_tag, and add new auth_keys with auth_tag. return: if success, none. else, a dict: { stdout: xxx, stderr: yyy } """ auth_tag = os.getenv('AUT...
5,358,164
def svn_wc_diff(*args): """ svn_wc_diff(svn_wc_adm_access_t anchor, char target, svn_wc_diff_callbacks_t callbacks, void callback_baton, svn_boolean_t recurse, apr_pool_t pool) -> svn_error_t """ return _wc.svn_wc_diff(*args)
5,358,165
def plot3d_gmphd_track(model, grid, gm_s_list=None, gm_list_list=None, observation_list=None, prediction_list=None, truth=None, title=None, contours=4, log_plot=True): """ Animate GM-PHD Filter result on 3D plot with mayavi Args: model (:obj:`pymrt.tracking...
5,358,166
def _FindResourceIds(header, resource_names): """Returns the numerical resource IDs that correspond to the given resource names, as #defined in the given header file." """ pattern = re.compile( r'^#define (%s) _Pragma\S+ (\d+)$' % '|'.join(resource_names)) with open(header, 'r') as f: res_ids = [...
5,358,167
def resolve_request_path(requested_uri): """ Check for any aliases and alter the path accordingly. Returns resolved_uri """ for key, val in PATH_ALIASES.items(): if re.match(key, requested_uri): return re.sub(key, val, requested_uri) return requested_uri
5,358,168
async def test_import_invalid_ip(hass: HomeAssistant) -> None: """Test that invalid IP error is handled during import.""" name = "Vallox 90 MV" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={"host": "vallox90mv.host.name", "name"...
5,358,169
def apim_api_delete( client, resource_group_name, service_name, api_id, delete_revisions=None, if_match=None, no_wait=False): """Deletes an existing API. """ cms = client.api return sdk_no_wait( no_wait, cms.delete, resource_group_name=resource_group_name, service_n...
5,358,170
def deep_copy(obj): """Make deep copy of VTK object.""" copy = obj.NewInstance() copy.DeepCopy(obj) return copy
5,358,171
def search_exception(n, num_incr=1000): """ search for exception to perfect mirsky for given n, checking pairs checks in reversed order to check pairs with permutations of less fixed points first """ eigvals = [] in_rad = np.cos(np.pi/n) x_ranges, lines = pm_boundary(n) f...
5,358,172
def get_dunn_index(fdist, *clusters): """ Returns the Dunn index for the given selection of nodes. J.C. Dunn. Well separated clusters and optimal fuzzy partitions. 1974. J.Cybern. 4. 95-104. """ if len(clusters)<2: raise ValueError, "At least 2 clusters are required" intra_dist =...
5,358,173
def sample(words, n=10) -> str: """Sample n random words from a list of words.""" return [random.choice(words) for _ in range(n)]
5,358,174
def extract_peaks( imzml_path, db, tol_ppm=DEFAULT_TOL_PPM, tol_mode=DEFAULT_TOL_MODE, base_mz=DEFAULT_BASE_MZ, ): """ Extract all peaks from the given imzML file for the supplied database of molecules. :param imzml_path: :param db: A pandas DataFrame containing an 'mz' column. Addit...
5,358,175
def cov_dense(n_features=100, scale=0.5, edges='ones', pos=True, force_psd=True, random_state=None): """ Returns a covariance matrix with a constant diagonal and whose off diagnale elements are obtained from adj_mats.complete_graph() Parameters ---------- n_features: int scale: f...
5,358,176
def measure_fwhm(array): """Fit a Gaussian2D model to a PSF and return the FWHM Parameters ---------- array : numpy.ndarray Array containing PSF Returns ------- x_fwhm : float FWHM in x direction in units of pixels y_fwhm : float FWHM in y direction in units of...
5,358,177
def test_not_impartial(g): """ Test that these games are not impartial. """ assert not g.is_impartial
5,358,178
def exists(profile, bucket, name): """Check if a file exists in an S3 bucket. Args: profile A profile to connect to AWS with. bucket The name of the bucket you want to find the file in. name The name of a file. Returns: True if it exis...
5,358,179
def fetchquota(adr): """Retrieves the account quota information and passes the interesting part of the json object along to the request source. Arguments: adr (str): The email account address of interest. Returns: The quota part of the json object for the response. """ debuginf...
5,358,180
def saslocal(): """Set sasurl to local.""" set_sasurl(loc='local')
5,358,181
def print_basic_csv(file_name, delimiter=','): """This function extracts and prints csv content from given filename Details: https://docs.python.org/2/library/csv.html Args: file_name (str): file path to be read delimiter (str): delimiter used in csv. Default is comma (',') Returns: ...
5,358,182
def project_login(driver): """ 針對多綫程執行設定不同樣本編號,若修改問卷,也許提供該問卷樣本編號的第一順位號碼。 """ SAMPLE_NUMBER = 20200101+sample_add try: WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.XPATH, '//*[@name="{}"][1]' .format(str(SAMPLE_NUMBER))))).click() # 選擇樣本編號作答 sleep(...
5,358,183
def set_directory_request_data(directory, key, value): """Allows to associate a value to a key on the data object of a request :param directory: The name of the directory of the request to which the data will be associated :type directory: str :param key: The key to which the data will be associate...
5,358,184
def convert_convolutionfunction_to_image(cf): """ Convert ConvolutionFunction to an image :param cf: :return: """ return create_image_from_array(cf.data, cf.grid_wcs, cf.polarisation_frame)
5,358,185
def macro(libname): """Decorator for macros (Moya callables).""" def deco(f): exposed_elements[libname] = f return f return deco
5,358,186
def product(*generators): """generate the cartesian product of infinite generators.""" generators = list(map(GenCacher, generators)) for distance in itertools.count(0): for idxs in _summations(distance, len(generators)): yield tuple(gen[idx] for gen, idx in zip(generators, idxs))
5,358,187
def get_dataloaders(dataset, mode='train', root=None, shuffle=True, pin_memory=True, batch_size=8, logger=logging.getLogger(__name__), normalize=False, **kwargs): """A generic data loader Parameters ---------- dataset : {"openimages", "jetimages", "evaluation"} Name of the ...
5,358,188
def ie(): """Interest Expense Function""" ww = float(input("for Short-Term Loan Press 1:\nfor Long-Term Loan Press 2:\nfor Bonds-Payable Press 3: ")) if(ww == 1): e = float(input("Please Enter The Principal Value: ")) ew = float(input("Please Enter Interest rate %: ")) ea = flo...
5,358,189
def stats_file(filename, shape, dtype=None, file_format='raw', out_of_core=True, buffer_size=None, max_memory=None, progress_frequency=None): """stats_file(filename, shape, dtype=None, file_format='raw', out_of_core=True, buffer_size=None, max_memory=None, ...
5,358,190
def get_info(args): """ Loads todo.txt, sets up file paths, loads in any available star information, saves the relevant parameters for each of the two main routines and sets the plotting parameters. Parameters ---------- args : argparse.Namespace command-line arguments parallel : b...
5,358,191
def test_isupport_getattr(): """Test using ISUPPORT parameters as read-only attributes.""" instance = isupport.ISupport(awaylen=50) assert hasattr(instance, 'AWAYLEN') assert not hasattr(instance, 'awaylen'), 'attributes are ALL_UPPERCASE' assert not hasattr(instance, 'UNKNOWN') assert instanc...
5,358,192
def _weight_func(dist): """Weight function to replace lambda d: d ** -2. The lambda function is not valid because: if d==0 then 0^-2 is not valid.""" # Dist could be multidimensional, flatten it so all values # can be looped with np.errstate(divide="ignore"): retval = 1.0 / dist ret...
5,358,193
def enable_logging( debug=False, http_debug=False, path=None, stream=None, format_stream=False, format_template='%(asctime)s %(levelname)s: %(name)s %(message)s', handlers=None, ): """Enable logging output. Helper function to enable logging. This function is available for debugging purposes...
5,358,194
def two_poles(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Cartpole Balance task with two poles.""" physics = Physics.from_xml_string(*get_model_and_assets(num_poles=2)) task = Balance(swing_up=True, sparse=False, random=random) environment_kwargs = environ...
5,358,195
def process_topic_entity(entity: dict, language: str) -> bool: """ Given a topic entity, gather its metadata :param entity :param language: :type entity dict :type language str :returns bool """ try: # Get ID remote_id = entity["title"] print("%s\t%s" % ("ID"...
5,358,196
def _no_grad_trunc_normal_(tensor: Tensor, mean: float, std: float, a: float, b: float) -> Tensor: """Cut & paste from PyTorch official master until it's in a few official releases - RW Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf Args: tensor (Tensor)...
5,358,197
def inverse_update(C, m, return_drop=False): """ Compute the inverse of a matrix with the m-th row and column dropped given knowledge of the inverse of the original matrix. C = inv(A) B = drop_col(drop_row(A, m),m) computes inv(B) given only C Args: C: inverse of full m...
5,358,198
def loss_calc(settings, all_batch, market_batch): """ Calculates nn's NEGATIVE loss. Args: settings: contains the neural net all_batch: the inputs to neural net market_batch: [open close high low] used to calculate loss Returns: cost: loss - l1 penalty """ loss = set...
5,358,199