content
stringlengths
22
815k
id
int64
0
4.91M
def multilateral_methods( df: pd.DataFrame, price_col: str = 'price', quantity_col: str = 'quantity', date_col: str='month', product_id_col: str='id', characteristics: Optional[Sequence[str]] = None, groups: Optional[Sequence[str]] = None, method: str = 'all', bilateral_method: str =...
5,314,000
def update_benchmarks(args): """Update benchmarks by overriding parameters provided by a user. :param argparse args: Command line arguments. The following command line arguments are used: * ``args.input_file`` A file with benchmark results. * ``args.params`` Specification of mandatory paramete...
5,314,001
def causal_fftconv( signal: torch.Tensor, kernel: torch.Tensor, bias: torch.Tensor = None, ) -> torch.Tensor: """ Args: signal: (Tensor) Input tensor to be convolved with the kernel. kernel: (Tensor) Convolution kernel. bias: (Optional, Tensor) Bias tensor to add to the outpu...
5,314,002
def sell_at_loss_switch(value, exchange): """enable/disable buy size amount""" tg_wrapper.helper.config[exchange]["config"].update({"sellatloss": 0}) if "sellatloss" in value: tg_wrapper.helper.config[exchange]["config"].update({"sellatloss": 1}) return False, False return True, True
5,314,003
def check_key_up_events(event, ship): """Respond to key releases.""" if event.key == pygame.K_RIGHT: ship.moving_right = False elif event.key == pygame.K_LEFT: ship.moving_left = False
5,314,004
async def test_hmip_illuminance_sensor2(hass, default_mock_hap_factory): """Test HomematicipIlluminanceSensor.""" entity_id = "sensor.lichtsensor_nord_illuminance" entity_name = "Lichtsensor Nord Illuminance" device_model = "HmIP-SLO" mock_hap = await default_mock_hap_factory.async_get_mock_hap( ...
5,314,005
def strify(iterable_struct, delimiter=','): """ Convert an iterable structure to comma separated string. :param iterable_struct: an iterable structure :param delimiter: separated character, default comma :return: a string with delimiter separated """ return delimiter.join(map(str, iterable_struc...
5,314,006
def unzip_file(filename, location, flatten=True): # type: (str, str, bool) -> None """ Unzip the file (with path `filename`) to the destination `location`. All files are written based on system defaults and umask (i.e. permissions are not preserved), except that regular file members with any execut...
5,314,007
def repython(version, script_path): """Update the Python environment modules to the specified ``version`` and replace the current process with an updated Python execution running the script specified by ``script_path``. """ # Establish the environment modules envmod.setup() if not os.envir...
5,314,008
def load_shifting_multiple_tech( fueltypes, enduse_techs, technologies, fuel_yh, param_lf_improved_cy ): """Shift demand in case of multiple technologiesself. Check how much of each technology is shifted in peak hours. Calculate the absolute and relative demand o...
5,314,009
def configure_node( cluster, node, certnkey, dataset_backend_configuration, provider, logging_config=None ): """ Configure flocker-dataset-agent on a node, so that it could join an existing Flocker cluster. :param Cluster cluster: Description of the cluster. :param Node node...
5,314,010
def unsubdivide(P, T, iter=1): """ Unsubdivides the given mesh n times In order to work, the mesh is intended subdivided using the method 'subdivide'. Parameters ---------- P : Tensor the input points set T : LongTensor the topology tensor iter : int (optional) ...
5,314,011
def table2sparse(data, shape, order, m_type=lil_matrix): """Constructs a 2D sparse matrix from an Orange.data.Table Note: This methods sort the columns (=> [rows, cols]) Args: data: Orange.data.Table shape: (int, int) Tuple of integers with the s...
5,314,012
def wait_for_element_not_visible(element, timeout=20): """DEPRECATED, use wait_for_element_not_displayed Wait for an element to stop being visible. Parameters: element : element timeout (optional, default: 20) : value """ execution.logger.warning('wait_for_element_not_visible is DEPRECATED,...
5,314,013
def _test_evaluate_cli(test_outputs: List[str], test_target_path: str): """ Runs sockeye-evaluate CLI with translations and a reference file. """ with TemporaryDirectory(prefix="test_evaluate") as work_dir: # write temporary output file out_path = os.path.join(work_dir, 'hypotheses') ...
5,314,014
def get_s_bi_status(c: analyze.CZSC) -> OrderedDict: """倒数第1笔的表里关系信号 :param c: CZSC 对象 :return: 信号字典 """ freq: Freq = c.freq s = OrderedDict() v = Signal(k1=str(freq.value), k2="倒1笔", k3="表里关系", v1="其他", v2='其他', v3='其他') s[v.key] = v.value if c.bi_list: # 表里关系的定义参考:http://...
5,314,015
def shuffle_code_book(encode_book): """ shuffle the code book :param encode_book: code book :return: shuffled code book """ codbok = np.array(list(encode_book.items())) ids0 = np.random.permutation(codbok.shape[0]) ids1 = np.random.permutation(codbok.shape[0]) cod = codbok[ids0, 0] ...
5,314,016
def default_handler(data: pd.Series, *args, **kwargs) -> pd.Series: """Processes given data and indicates if the data matches requirements. Parameters ---------- data: pd.Series The data to process. Returns ------- pd.Series: The logical list indicating if the data matches requirem...
5,314,017
def p_params(p): """params : var_declaration2 | empty""" pass
5,314,018
def load_original_data(data, load_dirty=False): """ Loads the original dataframe. Missing values are replaced with np.nan. If load_dirty is set to True, the dirty dataset of a cleaning experiment is loaded. Otherwise, the default clean dataset is loaded. """ if load_dirty: df = pd.re...
5,314,019
def merge_cpr_fr24_data(date, *, max_speed=DEFAULT_MAX_SPEED, distance_accuracy=DEFAULT_DISTANCE_ACCURACY): """ Match, merge and clean refined CPR and FR24 ADS-B data for the given date. Parameters ---------- date: string The date in ISO8601 format, e.g. 2017-08-16 ...
5,314,020
def bfsw_detector_pt(Y, X, mask, image_type='textured', sigma=3, sigma_scene=1.5, nu=1, stride_u=16, stride_v=16, max_iter=1024, thresh=0, step=tensor(1e0, device=device(), dtype=precision()), articulation_pt=None): """Brute Force Sliding Window optimization-based detector Search for a ...
5,314,021
def _full_path_to(folder_name: str, i_f_r: str): """ Helper method to find the full path to a folder in Data :param folder_name: Name of the folder in Data :param i_f_r: 'i' (Input), 'f' (Files) or 'r' (Results). 'r' has subfolders 'l' (Labs), 't' (Tables), 'f' (Figures) and 'v' (LabVisualisations)...
5,314,022
def mapped_col_index_nb(mapped_arr, col_arr, n_cols): """Identical to `record_col_index_nb`, but for mapped arrays.""" col_index = np.full((n_cols, 2), -1, dtype=np.int_) prev_col = -1 for r in range(mapped_arr.shape[0]): col = col_arr[r] if col < prev_col: raise ValueError("...
5,314,023
def get_greedy_advanced(data: OrderedDictType[_T1, Set[_T2]], unit_counts: Dict[_T1, int], mode: SelectionMode) -> OrderedSet[_T1]: """The parameter ngrams needs to be ordered to be able to produce reproductable results.""" assert isinstance(data, OrderedDict) logger = getLogger(__name__) all_ngrams = {e for s ...
5,314,024
def test_delete_gifs_non_admin(client: FlaskClient) -> None: """Assert when DELETE /gifs is requested, that non-admin users are not allowed to make the request. Args: client (:obj:`~flask.testing.FlaskClient`): The Client fixture. """ username = create_random_username() auth_token = cre...
5,314,025
def test(nose_argsuments): """ Run application tests """ from nose import run params = ['__main__', '-c', 'nose.ini'] params.extend(nose_argsuments) run(argv=params)
5,314,026
def generate_pattern_eq_ipv4(value): """ makes a pattern to check an ip address """ return "ipv4-addr:value = '" + value + "'"
5,314,027
def generate_result_tables(repo_dir, data_dir): """ Generate the cross-check result tables """ import os import csv from fmpy.cross_check import get_vendor_ids combinations = [] # all permutations of FMI version, type and platform for fmi_version in ['1.0', '2.0']: for fmi_type in ['...
5,314,028
def data_upgrades(): """Add optional data upgrade migrations here""" conn = op.get_bind() project = conn.execute(sa.select([t_project])).fetchall() for proj_id, _, _, _, graph, _, _, user_id, dir_id, _, _ in project: nodes = graph['nodes'] edges = graph['edges'] projects_id, proj...
5,314,029
async def do_run(): """Connect to the PLM and load the ALDB.""" # devices = await async_connect(device=DEVICE) devices = await async_connect(host=HOST, username=USERNAME, password=PASSWORD) await devices.async_load(workdir=PATH, id_devi...
5,314,030
def get_dump_date(): """Iterate through labs dumps and find the newest one.""" dates = sorted(next(os.walk(DIRECTORY))[1], reverse=True) for date in dates: if os.path.isfile(FILENAME.format(date=date)): return date return None
5,314,031
def get_pub_velocity_cmd_vel(**kvargs): """ Returns publisher for :setpoint_velocity: plugin, :cmd_vel: topic """ return rospy.Publisher(mavros.get_topic('setpoint_velocity', 'cmd_vel'), TwistStamped, **kvargs)
5,314,032
def get_point_information(form): """ Функция для формирования json с полигоном для отрисовки аналитики по точке :param form: форма из POST запроса с координатами точки и 6 основными фильтрами :return: json с полигоном с необходимой информацией """ point_info = generate_point_information(form) ...
5,314,033
def __kspack(ks): """takes a kset and returns an 8-bit number""" bits = 0 _ks = __make_ks() for i in range(8): if _ks[i] in ks: bits += 2**i return bits
5,314,034
def rec_join(key, r1, r2, jointype='inner', defaults=None, r1postfix='1', r2postfix='2'): """ Join record arrays *r1* and *r2* on *key*; *key* is a tuple of field names -- if *key* is a string it is assumed to be a single attribute name. If *r1* and *r2* have equal values on all the keys in the *key...
5,314,035
def cf(data): """AFF Community Facts""" # AFF linked to Community Facts by place name # CEDSCI links to Community Profiles by GEOID, but we can get around # that by using search instead raw_data = OrderedDict(zip(aff_cf, data)) if raw_data["geo_type"] == "zip": raise KeyError("CEDSCI doe...
5,314,036
def record( population_trace, evolution, points=20, iteration_step=10, filename=None, mode="2D", ax=None, display=False, ): """Record evolution in 3d. Displays surface and population. Arguments: population_trace: list of populations' coordinates in each iteration ...
5,314,037
def perspective_transform(img): """ Applies the perspective transformation to the image. If the pickle file does not exist, the transformation is determined first and saved in the pickle file. :param img: The image to be transformed :return: The warped/transformed image and the transformation M...
5,314,038
def test20_taskfile(): """ Read a taskfile, process data """ with tempfile.NamedTemporaryFile() as f: stats = process_file( datafile("orig.txt"), f.name, "en", taskfile=datafile("taskfile.json") ) exp = {"calls": 3, "CREDIT_CARD": 1, "BITCOIN_ADDRESS": 1} asse...
5,314,039
def print_server_info(ip, user, password): """ Fetch and print servers info @params: ip - Required : the ip of the server (Str) user - Required : the administrator username (Str) password - Required : The administrator password (Str) """ try: r = requests.get(f'...
5,314,040
def bytes_string(text, encode="utf-8"): """Return a bytes object on Python 3 and a str object on Python 2""" if not PY3: if isinstance(text, unicode): # pylint: disable=undefined-variable result = text.encode(encode) else: result...
5,314,041
def main(): """Run the module on its own.""" _print_status(_get_cli_arguments())
5,314,042
def log_gaussian_prior(map_data, sigma, ps_map): """ Gaussian prior on the power spectrum of the map """ data_ft = jnp.fft.fft2(map_data) / map_data.shape[0] return -0.5*jnp.sum(jnp.real(data_ft*jnp.conj(data_ft)) / (ps_map+sigma**2))
5,314,043
def calculate_cdf(data): """Calculate CDF given data points Parameters ---------- data : array-like Input values Returns ------- cdf : series Cumulative distribution funvtion calculated at indexed points """ data = pd.Series(data) data = data.fillna(0) tota...
5,314,044
def test_get_instance(): """Test for method of the same name""" # def get_instance(instance_id, region): region = 'us-west-2' instance_id = mocks.create_instances(region, count=1)[0] found_instance = utils.get_instance(instance_id, region) assert found_instance['InstanceId'] == instance_id
5,314,045
def get_special_size(obj: Any, ids: Optional[Set[int]] = None) -> SpecialTuple: """ Handles size requests for classes and data structures :param obj: object to calculate size :param ids: set of already seen ids :return: Tuple of the size in bytes of the special data structures of that object, and th...
5,314,046
def sanitize_df(df, d_round=2, **options): """All dataframe cleaning and standardizing logic goes here.""" for c in df.columns[df.dtypes == float]: df[c] = df[c].round(d_round) return df
5,314,047
def bind_args(func: FunctionType, *args: Any, **kwargs: Any) -> Dict[str, Any]: """Bind values from `args` and `kwargs` to corresponding arguments of `func` :param func: function to be inspected :param args: positional arguments to be bound :param kwargs: keyword arguments to be bound :return: `dic...
5,314,048
def register_user(request): """ ---REGISTER USER--- :param request: """ registered = False if request.method == 'POST': # Using forms to collect new user data user_form = UserForm(request.POST) if user_form.is_valid(): neighborhood = Neighborhood.objects.get(division_title=request.POST['neighborhood_text...
5,314,049
def trans_quarter(string): """Transform from (not lexicographic friendly) {quarter}Q{year} to a datetime object. >>> trans_quarter('4Q2019') datetime.datetime(2019, 10, 1, 0, 0) """ quarter, year = qy_parser.str_to_tuple(string) return dt(year=year, month=month_of_quarter[quarter], day=1)
5,314,050
def edit_post(post_id): """EDIT-POST page helps in editing of blog post.""" post = Post.query.get(post_id) if post: form = PostForm(obj=post) if form.validate_on_submit(): post.title = form.data.get("title") post.body = form.data.get("body") db.session.ad...
5,314,051
def home_delete(): """Delete all top-level collections!?""" raise NotImplementedError("Delete all top-level collections!?")
5,314,052
def map_emoji_ids(): """ Match Emoji ID's from the server with emojis in the config """ with open(configFileLocation, "r") as settingsFile: settingsData = json.load(settingsFile) configuredRoles = settingsData["roles"] for item in configuredRoles: if item["react_id"] == 0: ...
5,314,053
def shutdown(at_time=None): """ Shutdown a running system at_time The wait time in minutes before the system will be shutdown. CLI Example: .. code-block:: bash salt '*' system.shutdown 5 """ if ( salt.utils.platform.is_freebsd() or salt.utils.platform.is_...
5,314,054
def _query( db, keyword, person, album, uuid, title, no_title, description, no_description, ignore_case, edited, external_edit, favorite, not_favorite, hidden, not_hidden, missing, not_missing, shared, not_shared, isphoto, ismovie, ...
5,314,055
def list_products(website, category, search): """ There are 3 ways to list the products, 1 by category, 2 by the search bar, 3 by accessing the homepage. """ if search: return Products.objects.filter(websites=website, is_available=True, title__icontains=se...
5,314,056
def get_feature_columns(num_hash_buckets, embedding_dimension): """Creates sequential input columns to `RNNEstimator`. Args: num_hash_buckets: `int`, number of embedding vectors to use. embedding_dimension: `int`, size of embedding vectors. Returns: List of `tf.feature_column` ojects. """ id_co...
5,314,057
def afsluitmiddel_soort(damo_gdf=None, obj=None): """" Zet naam van SOORTAFSLUITMIDDEL om naar attribuutwaarde """ data = [_afsluitmiddel_soort(name) for name in damo_gdf['SOORTAFSLUITMIDDEL']] df = pd.Series(data=data, index=damo_gdf.index) return df
5,314,058
def d2tf(ndp, days): """ Wrapper for ERFA function ``eraD2tf``. Parameters ---------- ndp : int array days : double array Returns ------- sign : char array ihmsf : int array Notes ----- The ERFA documentation is below. - - - - - - - - e r a D 2 t f - ...
5,314,059
def libxl_init_members(ty, nesting = 0): """Returns a list of members of ty which require a separate init""" if isinstance(ty, idl.Aggregate): return [f for f in ty.fields if not f.const and isinstance(f.type,idl.KeyedUnion)] else: return []
5,314,060
def generate(ui_file, output, indent, execute): """ Generate the Python code. """ from .compile_ui import compileUi if output == '-': import io pyfile = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8') needs_close = False else: pyfile = open(output, 'wt', encoding=...
5,314,061
def find_commands(cache=True): """ Scans the script directory and extracts all commands. """ global _command_cache if _command_cache is not None and cache: return _command_cache files = os.walk(command_dir) commands = {} for (dirpath, dirnames, filenames) in files: for f...
5,314,062
def test_epacems_to_parquet( datapkg_bundle, pudl_settings_fixture, pudl_etl_params, request, live_dbs, ): """Attempt to convert a small amount of EPA CEMS data to parquet format.""" if live_dbs: pytest.skip("Don't attempt EPA CEMS to Parquet conversion with live DBs.") epacems_...
5,314,063
def snr_and_sounding(radar, soundings_dir=None, refl_field_name='DBZ'): """ Compute the signal-to-noise ratio as well as interpolating the radiosounding temperature on to the radar grid. The function looks for the radiosoundings that happened at the closest time from the radar. There is no time diff...
5,314,064
def make_weekly_data(con, ticker_id, begin_date, today): """ INPUTS: con (mysql) - pymysql database connection ticker_id (int) - Ticker id number from symbols table begin_date (str) - Last price date in series. Iso8601 standard format today (str) - Today's date in iso8601 standar...
5,314,065
def readKeyGraph(queryID): """ """ import os curpath = os.getcwd() f = open("%s.txt" % queryID, "r") topics = int(next(f)) nodelabel = {} E = [] nodetopic = {} for x in range(0, topics): thisnodes = [] nodes = int(next(f).split("KEYGRAPH_NODES:")[1]) for ...
5,314,066
def kill_service(ctrl_addr): """kill the LLH service running at `ctrl_addr`""" with zmq.Context.instance().socket(zmq.REQ) as sock: sock.setsockopt(zmq.LINGER, 0) sock.setsockopt(zmq.RCVTIMEO, 1000) sock.connect(ctrl_addr) sock.send_string("die") return sock.re...
5,314,067
def test_groups_put_details(app, client, session): """Good cases.""" token = factory_auth_header() headers = {"Authorization": f"Bearer {token}", "content-type": "application/json"} response = client.get("/groups", headers=headers) assert len(response.json) > 0 id = response.json[0]["id"] ...
5,314,068
def dmp_grounds(c, n, u): """ Return a list of multivariate constants. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.densebasic import dmp_grounds >>> dmp_grounds(ZZ(4), 3, 2) [[[[4]]], [[[4]]], [[[4]]]] >>> dmp_grounds(ZZ(4), 3, -1) [4, 4, 4] ...
5,314,069
def has_attrs(inst, *args): """ checks if the instance has all attributes as specified in *args and if they not falsy :param inst: obj instance :param args: attribute names of the object """ for a in args: try: if not getattr(inst, a, None) return False ...
5,314,070
def bin_decomp(fbin, st_addr, end_addr, fout=None): """ decompost a region from a binary file decompost a region from start to end address from a binary file and write the region content to a file the output file name is optional. The default output file name is input file name with address range :param...
5,314,071
def test_rfx_glm(): """ Smoke test for RFX GLM. """ meta = ibma.RFX_GLM(null='theoretical', n_iters=None) meta.fit(pytest.dset_conse) assert isinstance(meta.results, nimare.base.MetaResult)
5,314,072
def get_related_offers(order): """ Search related offers to order from parameter :param order: client order :return: string with related offers to order from parameter or empty string """ related_offers = "" if OrdersOffers.objects.filter(order=order).count() > 0: order_offers = Orde...
5,314,073
def test_uint8_default(path_rgb_byte_tif): """Get uint8 array from uint8 dataset""" with rasterio.open(path_rgb_byte_tif) as dataset: assert dataset.read().dtype == numpy.dtype('uint8')
5,314,074
def undo_imagenet_preprocess(image): """ Undo imagenet preprocessing Input: - image (pytorch tensor): image after imagenet preprocessing in CPU, shape = (3, 224, 224) Output: - undo_image (pytorch tensor): pixel values in [0, 1] """ mean = torch.Tensor([0.485, 0.456, 0.406]).view((3, 1, 1)) ...
5,314,075
def ob_mol_from_file(fname, ftype="xyz", add_hydrogen=True): """ Import a molecule from a file using OpenBabel fname: the path string to the file to be opened ftype: the file format add_hydrogen: whether or not to insert hydrogens automatically openbabel does not always add ...
5,314,076
def collapse(html): """Remove any indentation and newlines from the html.""" return ''.join([line.strip() for line in html.split('\n')]).strip()
5,314,077
def multiclass_cross_entropy(phat, y, N_classes, weights, EPS = 1e-30) : """ Per instance weighted cross entropy loss (negative log-likelihood) """ y = F.one_hot(y, N_classes) # Protection loss = - y*torch.log(phat + EPS) * weights loss = loss.sum() / y.shape[0] return loss
5,314,078
def get_arc_polygon(resolution,size=[1,1],arc=[0,1]): """resolution is the quantity of polygon points horizontal and vertical size are requested arc give the starting and ending angles""" polygon=[] for increment in range(resolution+1): inc= arc[1]*(increment/resolution) angl=(arc[0]+inc)*pi*2 polygon.append...
5,314,079
def mypy(ctx): """Check typing with mypy.""" ctx.run(f"{PIPENV_RUN} mypy --ignore-missing-imports {PACKAGE_NAME}")
5,314,080
def load(filename): """ Loads data line by line from a .wbp file, initiates a WellPlan object and populates it with data. Parameters ---------- filename: string The location and filename of the .wbp file to load. Returns ------- A welleng.exchange.wbp.WellPlan o...
5,314,081
def get_input_fn(data_dir, is_training, num_epochs, batch_size, shuffle, normalize=True): """ This will return input_fn from which batches of data can be obtained. Parameters ---------- data_dir: str Path to where the mnist data resides is_training: bool Whether to read the trai...
5,314,082
def getDashApp(title:str, notebook:bool, usetunneling:bool, host:str, port:int, mode: str, theme, folder): """ Creates a dash or jupyter dash app, returns the app and a function to run it :param title: Passed to dash app :param notebook: Uses jupyter dash with default port of 1005 (instead of 8050) ...
5,314,083
def get_pagination_request_params(): """ Pagination request params for a @doc decorator in API view. """ return { "page": "Page", "per_page": "Items per page", }
5,314,084
def access_bit(data, num): """ from bytes array to bits by num position """ base = int(num // 8) shift = 7 - int(num % 8) return (data[base] & (1 << shift)) >> shift
5,314,085
def _any_isclose(left, right): """Short circuit any isclose for ndarray.""" return _any(np.isclose, left, right)
5,314,086
def generation(locations, travels, mode): """ fill the travels file with datas of locations file acoording to the method explicited in notes (L. 4) mode == generation1 => travels will be erased beforehand mode == generation2 => possible travels will be added to travels. To use if we clustered the stuff ...
5,314,087
def kill_everything(starter_dp, servers): """ Kill all running servers and remove from database """ # Get list of running servers and stop them running_servers = starter_dp.DevGetRunningServers(True) for server in running_servers: starter_dp.DevStop(server) # Wait for servers to stop w...
5,314,088
def push(src, dest): """ Push object from host to target :param src: string path to source object on host :param dest: string destination path on target :return: result of _exec_command() execution """ adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_PUSH, src, dest] return _exec_comm...
5,314,089
def merge_set_if_true(set_1, set_2): """ Merges two sets if True :return: New Set """ if set_1 and set_2: return set_1.from_merge(set_1, set_2) elif set_1 and not set_2: return set_1 elif set_2 and not set_1: return set_2 else: return None
5,314,090
def localtime(utc_dt, tz_str): """ Convert utc datetime to local timezone datetime :param utc_dt: datetime, utc :param tz_str: str, pytz e.g. 'US/Eastern' :return: datetime, in timezone of tz """ tz = pytz.timezone(tz_str) local_dt = tz.normalize(utc_dt.astimezone(tz)) return local_d...
5,314,091
def _flatten_tensor_optim_state( state_name: str, pos_dim_tensors: List[torch.Tensor], unflat_param_names: List[str], unflat_param_shapes: List[torch.Size], flat_param: FlatParameter, ) -> torch.Tensor: """ Flattens the positive-dimension tensor optimizer state given by the values ``tens...
5,314,092
def variance ( func , xmin = None , xmax = None , err = False ) : """Get the variance for the distribution using >>> fun = ... >>> v = variance( fun , xmin = 10 , xmax = 50 ) """ ## ## get the functions from ostap.stats.moments actor = lambda x1,x2 : Variance ( x1 , x2 , err ) ## use...
5,314,093
def get_mysql_entitySets(username, databaseName): """ View all the enity sets in the databaseName """ password = get_password(username) try: cnx = connectSQLServerDB(username, password, username + "_" + databaseName) mycursor = cnx.cursor() sql = "USE " + username + "_" + databaseNam...
5,314,094
def check_dbconnect_success(sess, system): """ 測試資料庫是否成功連上(若連上且查詢成功代表資料庫存在) Args: sess: database connect session system: 使用之系統名稱 Returns: [0]: status(狀態,True/False) [1]: err_msg(返回訊息) """ try: if not sess.execute("select 1 as is_alive"): raise Exception ...
5,314,095
def split(filename, size=10.): """split the figure into color bands""" arr, aspect = _load_array(filename) fig = Figure(figsize=(size, size*aspect)) cmaps = ['Reds_r', 'Greens_r', 'Blues_r', 'gray_r'] for i, band in enumerate(arr): ax = fig.add_axes([(i % 2) * .5, (1 - i // 2) * .5, .5, .5...
5,314,096
def main(): """ Main body """ # validate the input if len(argv) != 2: print("usage: python gen_rand_sys.py <size of grid>") return 1 else: # get size from input size = int(argv[1]) grid = gen_rand_sys(size) print(grid)
5,314,097
def _compute_common_args(mapping): """Compute the list of arguments for dialog common options. Compute a list of the command-line arguments to pass to dialog from a keyword arguments dictionary for options listed as "common options" in the manual page for dialog. These are the options that ar...
5,314,098
def is_url(url): """URL書式チェック""" return url.startswith("https://") or url.startswith("http://")
5,314,099