content
stringlengths
22
815k
id
int64
0
4.91M
def element_png_display(element, max_frames): """ Used to render elements to PNG if requested in the display formats. """ if 'png' not in Store.display_formats: return None info = process_object(element) if info: IPython.display.display(IPython.display.HTML(info)) return ...
37,000
def list_documents(connection, name: str = None, to_dictionary: bool = False, to_dataframe: bool = False, limit: int = None, **filters): """Get all Documents available in the project specified within the `connection` object. Args: connection(object): MicroStrategy connection obje...
37,001
def test_read_metric_thresholds(): """Test that the metric thresholds can be read form a csv file.""" thresholds = StringIO( """Quadrant, Complexity, Function size, Coverage Q1, < 5,< 15,> 80 Q2, < 8,< 30,> 95 Q3, < 16,< 50,> 70 Q4, < 20,< 100,> 60""" ) threshold_file = r"../sr...
37,002
def rsa_obj(key_n, key_e, key_d=None, key_p=None, key_q=None): """ Wrapper for the RSAObj constructor The main reason for its existance is to compute the prime factors if the private exponent d is being set. In testing, the construct method threw exceptions because it wasn't able t...
37,003
def create_surface_and_gap(surf_data, radius_mode=False, prev_medium=None, wvl=550.0, **kwargs): """ create a surface and gap where surf_data is a list that contains: [curvature, thickness, refractive_index, v-number] """ s = surface.Surface() if radius_mode: if s...
37,004
def deprecate_build(id): """Mark a build as deprecated. **Authorization** User must be authenticated and have ``deprecate_build`` permissions. **Example request** .. code-block:: http DELETE /builds/1 HTTP/1.1 Accept: */* Accept-Encoding: gzip, deflate Authorization:...
37,005
def link_set_addr(devname, macaddr): """Set mac address of the link :param ``str`` devname: The name of the network device. :param ``str`` macaddr: The mac address. """ subproc.check_call( [ 'ip', 'link', 'set', 'dev', devname, ...
37,006
def project_task_list_layout(list_id, item_id, resource, rfields, record, icon="tasks"): """ Default dataList item renderer for Tasks on Profile pages Args: list_id: the HTML ID of the list item_id: the HTML ID of the item resource: t...
37,007
def subtractNums(x, y): """ subtract two numbers and return result """ return y - x
37,008
def getTraceback(error=None): """Get formatted exception""" try: return traceback.format_exc( 10 ) except Exception, err: return str(error)
37,009
def test_registry_delete_key(cbcsdk_mock): """Test the response to the 'reg delete key' command.""" cbcsdk_mock.mock_request('POST', '/integrationServices/v3/cblr/session/2468', SESSION_INIT_RESP) cbcsdk_mock.mock_request('GET', '/integrationServices/v3/cblr/session/1:2468', SESSION_POLL_RESP) cbcsdk_mo...
37,010
def db_cluster(fileutils, wlmutils, request): """ Yield fixture for startup and teardown of a clustered orchestrator. This should only be used in on_wlm and full_wlm tests. """ launcher = wlmutils.get_test_launcher() exp_name = request.function.__name__ exp = Experiment(exp_name, launcher=l...
37,011
def _copy_and_rename_file(file_path: str, dest_dir: str, new_file_name): """ Copies the specified file to the dest_dir (creating the directory if necessary) and renames it to the new_file_name :param file_path: file path of the file to copy :param dest_dir: directory to copy the file to :param new_f...
37,012
def greasePencilCtx(*args, **kwargs): """ This is a tool context command for the grease pencil tool. In query mode, return type is based on queried flag. Flags: - autoCreateFrames : acf (bool) [] - canDraw : cd (int) [] ...
37,013
def confirm_email(token): """ Verify email confirmation token and activate the user account.""" # Verify token user_manager = current_app.user_manager db_adapter = user_manager.db_adapter is_valid, has_expired, object_id = user_manager.verify_token( token, user_manager.confir...
37,014
def get_vector_paths_4_sample_set(set_name: str, base_path: str) -> List[PosixPath]: """ Gets the files for a given directory containing sample set :param set_name: Str indicating the name of the directory for a given set of samples :param base_path: Str indicating the location directory of samples ...
37,015
def _GetInstanceField(instance, field): """Get the value of a field of an instance. @type instance: string @param instance: Instance name @type field: string @param field: Name of the field @rtype: string """ return _GetInstanceFields(instance, [field])[0]
37,016
def test_get_most_populous_class2(): """ """ segment_mask = np.array( [ [1,0,0], [1,1,0], [0,1,0] ]) label_map = np.array( [ [9,8,8], [7,7,8], [8,7,8] ]) assert get_most_populous_class(segment_mask, label_map) == 7
37,017
def infectious_rate_tweets(t, p0=0.001, r0=0.424, phi0=0.125, taum=2., t0=0, tm=24, bounds=None): """ Alternative form of i...
37,018
def test_valid_registration(test_client, init_database): """ GIVEN a Flask application WHEN the '/register' page is posted with valid data THEN check the response is valid and the user is logged in """ response = test_client.post('/users/register', data=dict(email...
37,019
def fetch_user(username): """ This method 'fetch_user' fetches an instances of an user if any """ return User.objects.get(username=username)
37,020
def plot_segments(onsets, offsets, y=0.5, ax=None, line_kwargs=None): """plot segments on an axis. Creates a collection of horizontal lines with the specified `onsets` and `offsets` all at height `y` and places them on the axes `ax...
37,021
def print_advancement(file: str, curr: int, total: int): """Prints an advancement info of the predict_on_stocks function""" print('\r\x1b[2K', end='') print(f'[{LOADING[curr % LEN_LOADING]}]', end='') current_percent = round((curr / total) * 20) advancement = '\033[0;37;44m \033[0;0;0m' * \ ...
37,022
def test_pyparser(): """Test case: general parsing.""" def _check_blocks(actual, expected): assert actual, "No parse results" for i in range(len(actual)): assert i < len(expected), "Unexpected block %d:\n%r" % (i, actual[i]) valid = False if isinstance(expecte...
37,023
def write_tableau_old_format(n, Omega, ssestr): """ Write tableau to stdout in the original (Arun) TableauCreator format, with angles in degrees, full matrix, number of SSEs on first line and SSE sequence (DSSP codes E,H) on second line. n - order of tableau matrix (n by n) Omega - Numeric...
37,024
def get_script_name(key_combo, key): """ (e.g. ctrl-shift, a -> CtrlShiftA, a -> A """ if key_combo != 'key': return get_capitalized_key_combo_pattern(key_combo) + key.capitalize() return key.capitalize()
37,025
def _configure_legend(axs): """Configure the legend for the plot""" blue = mpatches.Patch(color='blue', label='commercial') green = mpatches.Patch(color='green', label='regular broadcast') yellow = mpatches.Patch(color='#fcba03', label='playing through') black = mpatches.Patch(color='black', label='...
37,026
def layer(name, features): """Make a vector_tile.Tile.Layer from GeoJSON features.""" pbl = vector_tile_pb2.tile.layer() pbl.name = name pbl.version = 1 pb_keys = [] pb_vals = [] pb_features = [] for j, f in enumerate( chain.from_iterable(singles(ob) for ob in features)): ...
37,027
def serialize(formula, threshold=None): """Provides a string representing the formula. :param formula: The target formula :type formula: FNode :param threshold: Specify the threshold :type formula: Integer :returns: A string representing the formula :rtype: string """ return get_e...
37,028
def shutdown_all_simulators(path=None): """Shutdown all simulator devices. Fix for DVTCoreSimulatorAdditionsErrorDomain error. Args: path: (str) A path with simulators """ command = ['xcrun', 'simctl'] if path: command += ['--set', path] LOGGER.info('Shutdown all simulators from folder %s.' % ...
37,029
def find_single_network_cost(region, option, costs, global_parameters, country_parameters, core_lut): """ Calculates the annual total cost using capex and opex. Parameters ---------- region : dict The region being assessed and all associated parameters. option : dict Contain...
37,030
def get_headings(bulletin): """"function to get the headings from text file takes a single argument 1.takes single argument list of bulletin files""" with open("../input/cityofla/CityofLA/Job Bulletins/"+bulletins[bulletin]) as f: ##reading text files data=f.read().r...
37,031
def phi_text_page_parse(pageAnalyse_str, phi_main_url): """ params: pageAnalyse_str, str. return: phi_page_dict, dict. It takes the precedent functions and maps their information to a dictionary. """ # phi_page_dict = {} phi_page_dict["phi_text_id_no"] = phi_text_id(pageAnalyse_str,...
37,032
def fdfilt_lagr(tau, Lf, fs): """ Parameters ---------- tau : delay / s Lf : length of the filter / sample fs : sampling rate / Hz Returns ------- h : (Lf) nonzero filter coefficients ni : time index of the first element of h n0 : time index of the center of h ...
37,033
def main(): """! Main program entry.""" arg_dict = gd.cli("jh") get_jh_data(**arg_dict)
37,034
def hit_n_run(A_mat, b_vec, n_samples=200, hr_timeout=ALG_TIMEOUT_MULT): """ Hit and Run Sampler: 1. Sample current point x 2. Generate a random direction r 3. Define gamma_i = ( b - a_i'x ) / ( r'a_i ) 4. Calculate max(gamma < 0) gamma_i and min(gamma > 0) gamma_i 5. Sampl...
37,035
def construct_simulation_hydra_paths(base_config_path: str) -> HydraConfigPaths: """ Specifies relative paths to simulation configs to pass to hydra to declutter tutorial. :param base_config_path: Base config path. :return Hydra config path. """ common_dir = "file://" + join(base_config_path, 'c...
37,036
def delete_from_limits_by_id(id, connection, cursor): """ Delete row with a certain ID from limits table :param id: ID to delete :param connection: connection instance :param cursor: cursor instance :return: """ check_for_existence = get_limit_by_id(id, cursor) if check_for_existence...
37,037
def _dummy_func(x): """Decorate to to see if Numba actually works""" x += 1
37,038
def article_search(request): """Пошук статті і використанням вектору пошуку (за полями заголовку і тексту з ваговими коефіцієнтами 1 та 0.4 відповідно. Пошуковий набір проходить стемінг. При пошуку враховується близькість шуканих слів одне до одного""" query = '' results = [] if 'query' in reque...
37,039
def get_campaign_data(api, campaign_id): """Return campaign metadata for the given campaign ID.""" campaign = dict() # Pulls the campaign data as dict from GoPhish. rawCampaign: dict = api.campaigns.get(campaign_id).as_dict() campaign["id"] = rawCampaign["name"] campaign["start_time"] = rawCa...
37,040
def create_small_map(sharing_model): """ Create small map and 2 BS :returns: tuple (map, bs_list) """ map = Map(width=150, height=100) bs1 = Basestation('A', Point(50, 50), get_sharing_for_bs(sharing_model, 0)) bs2 = Basestation('B', Point(100, 50), get_sharing_for_bs(sharing_model, 1)) ...
37,041
def save_dataz(file_name, obj, **kwargs): """Save compressed structured data to files. The arguments will be passed to ``numpy.save()``.""" return np.savez(file_name, obj, **kwargs)
37,042
def tfrecord_iterator(data_path: str, index_path: typing.Optional[str] = None, shard: typing.Optional[typing.Tuple[int, int]] = None ) -> typing.Iterable[memoryview]: """Create an iterator over the tfrecord dataset. Since the tfrecords file stor...
37,043
def test_wps_ext_kwa_proto_kwa_mismatch(dev, apdev): """WPS and KWA error: KWA mismatch""" r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev) data = build_wsc_attr(ATTR_R_SNONCE1, r_s1) # Encrypted Settings and KWA with incorrect value data += build_wsc_attr(ATTR_KEY...
37,044
def step(x): """Heaviside step function.""" step = np.ones_like(x, dtype='float') step[x<0] = 0 step[x==0] = 0.5 return step
37,045
def createRaviartThomas0VectorSpace(context, grid, segment=None, putDofsOnBoundaries=False, requireEdgeOnSegment=True, requireElementOnSegment=False): """ Create and return a space of lowest order Raviart...
37,046
def testimage(): """ PIL lets you create in-memory images with various pixel types: >>> from PIL import Image, ImageDraw, ImageFilter, ImageMath >>> im = Image.new("1", (128, 128)) # monochrome >>> _info(im) (None, '1', (128, 128)) >>> _info(Image.new("L", (128, 128))) # grayscale (luminanc...
37,047
def test_create_option_model(): """Tests for create_option_model().""" utils.reset_config({ "env": "cover", "approach": "nsrt_learning", }) model = create_option_model("oracle") assert isinstance(model, _OracleOptionModel) utils.reset_config({ "env": "pybullet_blocks", ...
37,048
def query_by_band_gap(min_band_gap=None, max_band_gap=None): """ Find all chemicals with a band gap within the specified range. Parameters ---------- min_band_gap : float, optional Minimum allowed band gap. Default is ``None``. max_band_gap : float, optional Maximum allowed band...
37,049
def edus_toks2ids(edu_toks_list, word2ids): """ 将训练cbos的论元句子们转换成ids序列, 将训练cdtb论元关系的论元对转成对应的论元对的tuple ids 列表并返回 """ tok_list_ids = [] for line in edu_toks_list: line_ids = get_line_ids(toks=line, word2ids=word2ids) tok_list_ids.append(line_ids) # 数据存储 return tok_list_ids
37,050
def pd_log_with_neg(ser: pd.Series) -> pd.Series: """log transform series with negative values by adding constant""" return np.log(ser + ser.min() + 1)
37,051
def filter_X_dilutions(df, concentration): """Select only one dilution ('high', 'low', or some number).""" assert concentration in ['high','low'] or type(concentration) is int df = df.sort_index(level=['CID','Dilution']) df = df.fillna(999) # Pandas doesn't select correctly on NaNs if concentration...
37,052
def test_delete_data_file(test_cloud_manager): """ Test that deleting an object actually calls the google API with given bucket and object name """ # Setup # test_cloud_manager._authed_session.delete.return_value = _fake_response(200) bucket = "some_bucket" object_name = "some_object" ...
37,053
def update_params(base_param: dict, additional: dict): """overwrite base parameter dictionary Parameters ---------- base_param : dict base param dictionary additional : dict additional param dictionary Returns ------- dict updated parameter dictionary """ ...
37,054
def test_GarbageTracker_get_tracker(): """ Test function for GarbageTracker.get_tracker(). """ tracker1 = GarbageTracker.get_tracker() tracker2 = GarbageTracker.get_tracker() assert tracker1 is tracker2
37,055
def lanczos_generalized( operator, metric_operator=None, metric_inv_operator=None, num_eigenthings=10, which="LM", max_steps=20, tol=1e-6, num_lanczos_vectors=None, init_vec=None, use_gpu=False, ): """ Use the scipy.sparse.linalg.eigsh hook to the ARPACK lanczos algorithm...
37,056
def get_articles_news(name): """ Function that gets the json response to our url request """ get_news_url = 'https://newsapi.org/v2/top-headlines?sources={}&apiKey=988fb23113204cfcb2cf79eb7ad99b76'.format(name) with urllib.request.urlopen(get_news_url) as url: get_news_data = url.read() ...
37,057
def execute( name, params=None, constraints=None, data_folder=None, tag=None, time_to_expire_secs=None, suffix=None, app_metrics=None, app_params=None, metadata=None, ): """ Create an instance of a workflow :param name: name of the workflow to create the instance ...
37,058
def coordConv(fromP, fromV, fromSys, fromDate, toSys, toDate, obsData=None, refCo=None): """Converts a position from one coordinate system to another. Inputs: - fromP(3) cartesian position (au) - fromV(3) cartesian velocity (au/year); ignored if fromSys is Geocentr...
37,059
def sample_recipe(user, **params): """create recipe""" defaults = { 'title': 'paneer tikka', 'time_minute': 10, 'price': 5.00 } defaults.update(**params) return Recipe.objects.create(user=user, **defaults)
37,060
def updateSections(thisconfig): """ Re-read the test config INI file. Load into the test environment config object. """ raise NotImplementedError
37,061
def briconToScaleOffset(brightness, contrast, drange): """Used by the :func:`briconToDisplayRange` and the :func:`applyBricon` functions. Calculates a scale and offset which can be used to transform a display range of the given size so that the given brightness/contrast settings are applied. :...
37,062
def parse_read_name_map_file(read_map, directories, recursive=False): """Parse either a seq summary file or a readdb file :param read_map: either a readdb file or sequencing summary file :param directories: check all the directories for the fast5 path :param recursive: boolean option to check the sub di...
37,063
def HostNameRequestHeader(payload_size): """ Construct a ``MessageHeader`` for a HostNameRequest command. Sends local host name to virtual circuit peer. This name will affect access rights. Sent over TCP. Parameters ---------- payload_size : integer Length of host name string....
37,064
def california_quadtree_region(magnitudes=None, name="california-quadtree"): """ Returns object of QuadtreeGrid2D representing quadtree grid for California RELM testing region. The grid is already generated at zoom-level = 12 and it is loaded through classmethod: QuadtreeGrid2D.from_quadkeys The grid ce...
37,065
def cinema_trip(persons, day, premium_seating, treat): """ The total cost of going to the cinema Parameters: ---------- persons: int number of people who need a ticket day: int day of the week to book (1 = Monday, 7 = Sunday) preimum_seating: bool ...
37,066
def check_path(path: pathlib.Path) -> bool: """Check path.""" return path.exists() and path.is_file()
37,067
def omega2kwave(omega, depth, grav=9.81): """ Solve the linear dispersion relation close to machine precision:: omega**2 = kwave * grav * tanh(kwave*depth) Parameters ---------- omega : float Wave oscillation frequency [rad/s] depth : float Constant water depth. [m] (<0...
37,068
def is_true(a: Bool) -> bool: """Returns whether the provided bool can be simplified to true. :param a: :return: """ return z3.is_true(a.raw)
37,069
def traverse_caves_recursive(cave: str, cave_system: dict, current_path: list[str]): """Recursively traverse through all paths in the cave.""" if cave != "START": # build the current path traversed current_path = current_path[:] current_path.append(cave) if cave == "END": ...
37,070
def check_dummybots(): """ Checks the availablity of dummybots and set the global flag. Runs once per test session. """ global DUMMYBOTS if not DUMMYBOTS['tested']: DUMMYBOTS['tested'] = True # Load bot configuration fp = open(path.join(TEST_CONFIG_PATH, 'bots.json'), 'r...
37,071
def main(tests=None, **kwargs): """Run the Python suite.""" Regrtest().main(tests=tests, **kwargs)
37,072
def letter_generator(start: str, end: str) -> typing.Generator: """ Возвращаем символы из дипазона :param start: начальный символ кодировки, с которого начинать возврат :param end: конечный символ кодировки, которым необходимо закончить :return: Generator """ for code in range(ord(start), or...
37,073
def count(A,target): """invoke recursive function to return number of times target appears in A.""" def rcount(lo, hi, target): """Use recursion to find maximum value in A[lo:hi+1].""" if lo == hi: return 1 if A[lo] == target else 0 mid = (lo+hi)//2 left = rcount(lo...
37,074
def nothing(x): """ Pass nothing. This function does nothing. It's just for passing as fourth argument of cv.createTrackbar. """ pass
37,075
def plot_images(images, class_names, labels, file_name, n_cols=10): """Plot a sample of images from the training set :param images: the set of images :param class_names: mapping from class indices to names :param labels: the labels of the images :param file_name: the file where the figure will be sa...
37,076
def asset_get_current_log(asset_id): """ """ db = current.db s3db = current.s3db table = s3db.asset_log query = ( table.asset_id == asset_id ) & \ ( table.cancel == False ) & \ ( table.deleted == False ) # Get the log with the maximum time asset_log = db(query)....
37,077
def step_decay_lr_scheduler(optimizer, epoch, lr_decay=0.1, lr_decay_epoch=7): """Decay learning rate by a factor of lr_decay every lr_decay_epoch epochs""" if epoch % lr_decay_epoch: return for param_group in optimizer.param_groups: param_group['lr'] *= lr_decay
37,078
def _filter_to_k_shot(dataset, num_classes, k): """Filters k-shot subset from a dataset.""" # !!! IMPORTANT: the dataset should *not* be shuffled. !!! # Make sure that `shuffle_buffer_size=1` in the call to # `dloader.get_tf_data`. # Indices of included examples in the k-shot balanced dataset. keep_example...
37,079
async def test_no_state_change_on_failure(v3_server): """Test that the system doesn't change state on an error.""" v3_server.post( ( f"https://api.simplisafe.com/v1/ss3/subscriptions/{TEST_SUBSCRIPTION_ID}" "/state/away" ), status=401, body="Unauthorized",...
37,080
def _create_tf_example(entry): """ Creates a tf.train.Example to be saved in the TFRecord file. Args: entry: string containing the path to a image and its label. Return: tf_example: tf.train.Example containing the info stored in feature """ image_path, label = _get_i...
37,081
def _gen_parameters_section(names, parameters, allowed_periods=None): """Generate the "parameters" section of the indicator docstring. Parameters ---------- names : Sequence[str] Names of the input parameters, in order. Usually `Ind._parameters`. parameters : Mapping[str, Any] Parameter...
37,082
async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None: """Set up Guardian switches based on a config entry.""" @callback def add_new_paired_sensor(uid: str) -> None: """Add a new paired sensor.""" coordinator = hass.data[...
37,083
def unload_agent(): """returns zero in case of success or if the plist does not exist""" plist_path = installed_plist_path() ret = 0 if os.path.exists(plist_path): ret = sync_task([LAUNCHCTL_PATH, "unload", "-w", "-S", "Aqua", plist_path]) else: log_message("nothing to unload") ...
37,084
def readCSV(name): """Read the filters from a CSV file. Note that the only the Remark and ToDo fields are taken from the CSV file. The filter names and which toolkits have each filter comes from is not read from the file. Rather that information is loaded from the ITK and SimpleITK Python symbol t...
37,085
def bins(df): """Segrega os dados de notas de 10 em 10 pontos para construção de gráficos. Parameters ---------- df : type Pandas DataFrame DataFrame de início. Returns ------- type Pandas DataFrame DataFrame final. """ df_bins = pd.DataFrame(df['ALUNO'].rename('Co...
37,086
def test_percentage(): """ Test percentage is calculated correctly """ ndarr = np.array([ [1, 2, 3, 4, 5, 6], [6, 5, 4, 3, 8, 1], [1, 1, 9, 1, 1, 1], [9, 2, 2, 2, 2, 2], [3, 3, 3, 9, 3, 3], [1, 2, 2, 9, 1, 4] ]) arr = np.array([1, 2, 3, 4, 5, 6]) exp_driver_scor...
37,087
def _GetBrowserSharedRelroConfig(): """Returns a string corresponding to the Linker's configuration of shared RELRO sections in the browser process. This parses the Java linker source file to get the appropriate information. Return: None in case of error (e.g. could not locate the source file). ...
37,088
def relative_to_abs() -> None: """Updates paths in the dataset_config.yaml file from relative to absolute. This function is used to replace the dataset path in the `dataset_config.yml` file from a relative to absolute path. Returns: None """ with open('dataset_config.yml') as f: ...
37,089
def parse_pcap(pcap, pcap_path, file_name): """Print out information about each packet in a pcap Args: pcap: dpkt pcap reader object (dpkt.pcap.Reader) """ counter = 0 pcap_dict = {} # For each packet in the pcap process the contents for ts, packet in pcap: # Unpack t...
37,090
def insert_video(ID): """ The function gets a valid YouTube ID, checks for its existence in database, if not found calls YouTube API and inserts into the MongoDB database. """ client = MongoClient('localhost:27017') db = client['PreCog'] collection = db['YoutubeRaw'] check_collection = db['YoutubeProcess...
37,091
def get_neighbor_v6_by_search(search=None): """Return a list of NeighborV6's by dict.""" try: objects = NeighborV6.objects.filter() search_dict = search if search else dict() object_map = build_query_to_datatable_v3(objects, search_dict) except FieldError as e: raise api_res...
37,092
def validate_customer(fn): """ Validates that credit cards are between 1 and 5 and that each is 16 chars long """ @functools.wraps(fn) def wrapped(*args, **kwargs): # Validate credit card length cc_list = kwargs.get("credit_cards") trimmed_cc = [remove_non_numeric(cc.replace...
37,093
def format_field(value: Any) -> str: """ Function that formats a single field for output on a table or CSV output, in order to deal with nested arrays or objects in the JSON outputs of the API. :param value: the value to format :return: a string that is fit for console output """ if isinstan...
37,094
def count_honeypot_events(): """ Get total number of honeypot events Returns: JSON/Dict number of honeypot events """ date = fix_date( get_value_from_request("date") ) if date: try: return jsonify( { "count_honeypot_eve...
37,095
def k_i_grid(gridsize, boxsize): """k_i_grid(gridsize, boxlen)""" halfgrid = gridsize // 2 boxsize = egp.utils.boxsize_tuple(boxsize) dk = 2 * np.pi / boxsize kmax = gridsize * dk _ = np.newaxis k1, k2, k3 = dk[:, _, _, _] * np.mgrid[0:gridsize, 0:gridsize, 0:halfgrid + 1] k1 -= kmax[0] ...
37,096
def is_bool_type(typ): """ Check if the given type is a bool. """ if hasattr(typ, '__supertype__'): typ = typ.__supertype__ return isinstance(typ, type) and issubclass(typ, bool)
37,097
def gaussians_entropy(covars, ns=nt.NumpyLinalg): """ Calculates entropy of an array Gaussian distributions :param covar: [N*D*D] covariance matrices :return: total entropy """ N = covar.shape[0] D = covar.shape[-1] return 0.5 * N * D * (1 + log(2*ns.pi)) + 0.5 * ns.sum(ns.det(covar))
37,098
def stop_client(signum, frame): """Stop the monitoring client.""" logger.debug('Received signal, shutting down [signal=%s]', signum) # Inform workers of shutdown SHUTDOWN.set() # Join all workers [x.join() for x in WORKERS]
37,099