content
stringlengths
22
815k
id
int64
0
4.91M
def kdump(self_update=False, snapshot=None): """Regenerate kdump initrd A new initrd for kdump is created in a snapshot. self_update Check for newer transactional-update versions. snapshot Use the given snapshot or, if no number is given, the current default snapshot as a base for the next snapshot. Use "continue" to indicate the last snapshot done. CLI Example: .. code-block:: bash salt microos transactional_update kdump snapshot="continue" """ cmd = ["transactional-update"] cmd.extend(_global_params(self_update=self_update, snapshot=snapshot)) cmd.append("kdump") return _cmd(cmd)
7,100
def register_keywords_user(email, keywords, price): """Register users then keywords and creates/updates doc Keyword arguments: email - email for user keywords - string of keywords price -- (optional) max price can be set to None """ logging.info('[INFO] Registering user email \'{}\' '.format(email)) # create user doc if doesn't exist db = utils.get_db_handle('users') doc = db.find_one({ 'email': email }) # metadata keywords_id = keywords.replace(" ", "_") date = str(datetime.datetime.now()).split('.')[0] num_keywords = 0 list_keywords = [] if doc == None: doc = db.insert_one({ 'email': email, 'dateCreated': date, 'numKeywords': num_keywords, 'keywords': [] }) logging.info('[INFO] Creating new user doc {} with _id: {}'.format(email, doc.inserted_id)) else: num_keywords = doc['numKeywords'] list_keywords = doc['keywords'] logging.info('[INFO] Found user doc \'{}\' with {} keywords'.format(email, num_keywords)) # insert keywords info along in user doc max_keywords = 5 if not utils.check_key_exists(list_keywords, keywords_id): if num_keywords < max_keywords: update = utils.update_users_doc(db, email, keywords_id, price, date) if update: logging.info('[INFO] Successfully created or updated doc for \'{}\''.format(email)) else: logging.info('[INFO] Error creating or updating doc for \'{}\''.format(email)) return False, 'ERROR_CREATE_DOC' else: logging.info('[INFO] Unable to create doc for \'{}\''.format(email)) logging.info('[INFO] Number of keywords exceed maximum of {}'.format(max_keywords)) return False, 'MAX_KEYWORDS_LIMIT' else: logging.info('[INFO] Unable to create doc for \'{}\''.format(email)) logging.info('[INFO] Duplicate key {} for user {}'.format(max_keywords, email)) return False, 'ERROR_DUPE_KEY' logging.info('[INFO] Registering keywords \'{}\' for email \'{}\' with price \'{}\''.format(keywords, email, price)) # create keywords doc if doesn't exist db = utils.get_db_handle('keywords') doc = db.find_one({ 'keyword': keywords_id }) # keywords metadata date = str(datetime.datetime.now()).split('.')[0] if doc == None: doc = db.insert_one({ 'keyword': keywords_id, 'subreddit': 'frugalmalefashion', 'dateCreated': date, 'users': [] }) logging.info('[INFO] Creating new keywords doc {} with _id: {}'.format(keywords_id, doc.inserted_id)) else: logging.info('[INFO] Found keywords doc \'{}\''.format(keywords_id)) # insert user info along in keyword doc update = utils.update_keywords_doc(db, keywords_id, email, price, date) if update: logging.info('[INFO] Successfully created or updated doc for \'{}\''.format(keywords_id)) else: logging.error('[ERROR] Error creating or updating doc for \'{}\''.format(keywords_id)) return False, 'ERROR_CREATE_DOC' return True, None
7,101
def domain_spec_colpair(data, i, j, rel2sub2obj, col_2_errors_repair, pair_coverage, ignore_null): """ Checks two columns i and j against a relation. Checks if i is the subject and j is the object or the other way around. If a match is found, objects that violate the matched relation are marked as errors. Parameters ---------- data i j rel2sub2obj col_2_errors_repair pair_coverage ignore_null """ for rel in rel2sub2obj: count = 0 # counts i to j relation back_count = 0 # counts j to i relation tempdict = {} backdict = {} for index, row in enumerate(data): coli = row[i] colj = row[j] if coli in rel2sub2obj[rel]: if colj == rel2sub2obj[rel][coli]: if ignore_null or coli != '': count += 1 else: repair_value = rel2sub2obj[rel][coli] tempdict[(index, j)] = repair_value if colj in rel2sub2obj[rel]: if coli == rel2sub2obj[rel][colj]: if ignore_null or colj != '': back_count += 1 else: repair_value = rel2sub2obj[rel][colj] backdict[(index, i)] = repair_value coverage = count/ len(data) backcoverage = back_count / len(data) if coverage >= pair_coverage: col_2_errors_repair.update(tempdict) # adds the errors found to the final output if backcoverage >= pair_coverage: col_2_errors_repair.update(backdict)
7,102
def test_Highest_Score__Two_Disks_Exploding_At_Last_Drop(score, max_score): """Function highest_score: Two disks, highest score when exploding at last drop.""" max_score.value += 12 try: set_up() test_board = Board.init_board \ (dimension=4, given_disks= \ ([wrapped_disk_value_1, ], [wrapped_disk_value_4, cracked_disk_value_2, cracked_disk_value_3], [cracked_disk_value_3_B], [wrapped_disk_value_4_B])) test_board_alias = Board.init_board \ (dimension=4, given_disks= \ ([wrapped_disk_value_1, ], [wrapped_disk_value_4, cracked_disk_value_2, cracked_disk_value_3], [cracked_disk_value_3_B], [wrapped_disk_value_4_B])) test_board_copy = Board.get_board_copy(test_board) highest_score, columns = Drop7.highest_score(test_board, [wrapped_disk_value_3_B, visible_disk_value_3]) assert highest_score == 14 assert columns == [1, 1] assert are_identical_boards(test_board, test_board_alias) assert are_equal_boards(test_board,test_board_copy) score.value += 12 except: pass
7,103
def plot_distribution(df, inv, ax=None, distribution=None, tau_plot=None, plot_bounds=True, plot_ci=True, label='', ci_label='', unit_scale='auto', freq_axis=True, area=None, normalize=False, predict_kw={}, **kw): """ Plot the specified distribution as a function of tau. Parameters ---------- df : pandas DataFrame DataFrame containing experimental EIS data. Used only for scaling and frequency bounds If None is passed, scaling will not be performed and frequency bounds will not be drawn inv : Inverter instance Fitted Inverter instance ax : matplotlib axis Axis on which to plot distribution : str, optional (default: None) Name of distribution to plot. If None, first distribution in inv.distributions will be used tau_plot : array, optonal (default: None) Time constant grid over which to evaluate the distribution. If None, a grid extending one decade beyond the basis time constants in each direction will be used. plot_bounds : bool, optional (default: True) If True, indicate frequency bounds of experimental data with vertical lines. Requires that DataFrame of experimental data be passed for df argument plot_ci : bool, optional (default: True) If True, plot the 95% credible interval of the distribution (if available). label : str, optional (default: '') Label for matplotlib unit_scale : str, optional (default: 'auto') Scaling unit prefix. If 'auto', determine from data. Options are 'mu', 'm', '', 'k', 'M', 'G' freq_axis : bool, optional (default: True) If True, add a secondary x-axis to display frequency area : float, optional (default: None) Active area. If provided, plot the area-normalized distribution normalize : bool, optional (default: False) If True, normalize the distribution such that the polarization resistance is 1 predict_kw : dict, optional (default: {}) Keyword args to pass to Inverter predict_distribution() method kw : keyword args, optional Keyword args to pass to maplotlib.pyplot.plot Returns ------- ax : matplotlib axis Axis on which distribution is plotted """ if ax is None: fig, ax = plt.subplots(figsize=(3.5, 2.75)) # If no distribution specified, use first distribution if distribution is None: distribution = list(inv.distributions.keys())[0] # If tau_plot not given, go one decade beyond basis tau in each direction if tau_plot is None: basis_tau = inv.distributions[distribution]['tau'] tmin = np.log10(np.min(basis_tau)) - 1 tmax = np.log10(np.max(basis_tau)) + 1 num_decades = tmax - tmin tau_plot = np.logspace(tmin, tmax, int(20 * num_decades + 1)) F_pred = inv.predict_distribution(distribution, tau_plot, **predict_kw) if normalize and area is not None: raise ValueError('If normalize=True, area cannot be specified.') if area is not None: if df is not None: for col in ['Zmod', 'Zreal', 'Zimag']: df[col] *= area F_pred *= area if normalize: Rp_kw = predict_kw.copy() # if time given, calculate Rp at given time if 'time' in predict_kw.keys(): Rp_kw['times'] = [predict_kw['time'], predict_kw['time']] del Rp_kw['time'] Rp = inv.predict_Rp(**Rp_kw) F_pred /= Rp if unit_scale == 'auto': if normalize: unit_scale = '' elif df is not None: unit_scale = get_unit_scale(df, area) else: unit_map = {-2: '$\mu$', -1: 'm', 0: '', 1: 'k', 2: 'M', 3: 'G'} F_max = np.max(F_pred) F_ord = np.floor(np.log10(F_max) / 3) unit_scale = unit_map.get(F_ord, '') scale_factor = get_factor_from_unit(unit_scale) ax.plot(tau_plot, F_pred / scale_factor, label=label, **kw) if plot_ci: if inv.fit_type.find('bayes') >= 0: F_lo = inv.predict_distribution(distribution, tau_plot, percentile=2.5, **predict_kw) F_hi = inv.predict_distribution(distribution, tau_plot, percentile=97.5, **predict_kw) if area is not None: F_lo *= area F_hi *= area if normalize: F_lo /= Rp F_hi /= Rp ax.fill_between(tau_plot, F_lo / scale_factor, F_hi / scale_factor, color='k', alpha=0.2, label=ci_label) ax.set_xscale('log') ax.set_xlabel(r'$\tau$ / s') if plot_bounds: if df is not None: ax.axvline(1 / (2 * np.pi * df['Freq'].max()), c='k', ls=':', alpha=0.6, zorder=-10) ax.axvline(1 / (2 * np.pi * df['Freq'].min()), c='k', ls=':', alpha=0.6, zorder=-10) if area is not None: ax.set_ylabel(fr'$\gamma \, (\ln{{\tau}})$ / {unit_scale}$\Omega\cdot\mathrm{{cm}}^2$') elif normalize: ax.set_ylabel(fr'$\gamma \, (\ln{{\tau}}) / R_p$') else: ax.set_ylabel(fr'$\gamma \, (\ln{{\tau}})$ / {unit_scale}$\Omega$') # add freq axis to DRT plot if freq_axis: # check for existing twin axis all_axes = ax.figure.axes ax2 = None for other_ax in all_axes: if other_ax.bbox.bounds == ax.bbox.bounds and other_ax is not ax: ax2 = other_ax break else: continue if ax2 is None: ax2 = ax.twiny() ax2.set_xscale('log') ax2.set_xlim(ax.get_xlim()) f_powers = np.arange(7, -4.1, -2) f_ticks = 10 ** f_powers ax2.set_xticks(1 / (2 * np.pi * f_ticks)) ax2.set_xticklabels(['$10^{{{}}}$'.format(int(p)) for p in f_powers]) ax2.set_xlabel('$f$ / Hz') # Indicate zero if necessary if np.min(F_pred) >= 0: ax.set_ylim(0, ax.get_ylim()[1]) else: ax.axhline(0, c='k', lw=0.5) return ax
7,104
def hilbert( turtle, length, depth ): """ Draw the U shape of iteration depth 1 """ turtle.left(90) turtle.forward(length) turtle.right(90) turtle.forward(length) turtle.right(90) turtle.forward(length) """ Finally turn into same direction we started with """ turtle.left(90)
7,105
def test_pokemon_color_read(client: TestClient): """Test case for pokemon_color_read """ headers = { } response = client.request( "GET", "/api/v2/pokemon-color/{id}/".format(id=56), headers=headers, ) # uncomment below to assert the status code of the HTTP response #assert response.status_code == 200
7,106
def dispatch(hostlist, commands, required_gpus=1, required_gpu_mem=8, required_cpu_mem=0, log_target='file'): """Main dispatcher method. Arguments ---------- hostlist : list List of hostnames or addresses commands : list List of command strings, as would be written in shell. Ensure the correct working directory by prepending a `cd ~/workdir/...;` if necessary. required_gpus : int Integer or list of integers defining the minimum number of required gpus on a single host. If list, len(required_gpus) must be equal to len(commands) required_gpu_mem : int In GB. Integer or list of integers, defining the minimum amount of free memory required per gpu on a single host. required_cpu_mem : int In GB. Integer or list of integers, defining the mimimum amount of available cpu memory on a single host. log_target : str One of the keys in LOG_TARGETS """ if type(required_gpus) is list and len(required_gpus) != len(commands): raise RuntimeError('Entries in required_gpus list must be equal to entries in commands.') if type(required_gpu_mem) is list and len(required_gpu_mem) != len(commands): raise RuntimeError('Entries in required_gpu_mem list must be equal to entries in commands.') if type(required_cpu_mem) is list and len(required_cpu_mem) != len(commands): raise RuntimeError('Entries in required_cpu_mem list must be equal to entries in commands.') # if type(required_gpus) is int: # required_gpus = [required_gpus]*len(commands) # if type(required_gpu_mem) is int: # required_gpu_mem = [required_gpu_mem]*len(commands) pool = mp.Pool(processes=MAX_PARALLEL_JOBS) m = mp.Manager() # fill queue queue_pending = m.Queue(len(hostlist)+1) queue_ready = m.Queue(len(hostlist)+1) shuffle(hostlist) for host in hostlist: queue_pending.put((host, 0)) numhosts = len(hostlist) # start enqueuer enqueuer = mp.Process(target=_utilization_enqueuer, args=(numhosts, queue_ready, queue_pending, required_gpus, required_gpu_mem, required_cpu_mem)) enqueuer.start() cmdinds = range(len(commands)) pool.map_async( partial(_async_dispatch, queue_pending=queue_pending, queue_ready=queue_ready, log_target=log_target), zip(cmdinds, commands) ).get(9999999) print('Please wait for processes to finish...') pool.close() queue_pending.put(('', 0)) pool.join() enqueuer.join()
7,107
def profitsharing_order(self, transaction_id, out_order_no, receivers, unfreeze_unsplit, appid=None, sub_appid=None, sub_mchid=None): """请求分账 :param transaction_id: 微信支付订单号,示例值:'4208450740201411110007820472' :param out_order_no: 商户分账单号,只能是数字、大小写字母_-|*@,示例值:'P20150806125346' :param receivers: 分账接收方列表,最多可有50个分账接收方,示例值:[{'type':'MERCHANT_ID', 'account':'86693852', 'amount':888, 'description':'分给商户A'}] :param unfreeze_unsplit: 是否解冻剩余未分资金,示例值:True, False :param appid: 应用ID,可不填,默认传入初始化时的appid,示例值:'wx1234567890abcdef' :param sub_appid: (服务商模式)子商户应用ID,示例值:'wxd678efh567hg6999' :param sub_mchid: (服务商模式)子商户的商户号,由微信支付生成并下发。示例值:'1900000109' """ params = {} if transaction_id: params.update({'transaction_id': transaction_id}) else: raise Exception('transaction_id is not assigned') if out_order_no: params.update({'out_order_no': out_order_no}) else: raise Exception('out_order_no is not assigned') if isinstance(unfreeze_unsplit, bool): params.update({'unfreeze_unsplit': unfreeze_unsplit}) else: raise Exception('unfreeze_unsplit is not assigned') if isinstance(receivers, list): params.update({'receivers': receivers}) else: raise Exception('receivers is not assigned') for receiver in params.get('receivers'): if receiver.get('name'): receiver['name'] = self._core.encrypt(receiver.get('name')) params.update({'appid': appid or self._appid}) if self._partner_mode: if sub_appid: params.update({'sub_appid': sub_appid}) if sub_mchid: params.update({'sub_mchid': sub_mchid}) else: raise Exception('sub_mchid is not assigned.') path = '/v3/profitsharing/orders' return self._core.request(path, method=RequestType.POST, data=params)
7,108
def merge_time_batch_dims(x: Tensor) -> Tensor: """ Pack the time dimension into the batch dimension. Args: x: input tensor Returns: output tensor """ if xnmt.backend_dynet: ((hidden_dim, seq_len), batch_size_) = x.dim() return dy.reshape(x, (hidden_dim,), batch_size=batch_size_ * seq_len) else: batch_size_, seq_len, hidden_dim = x.size() return x.view((batch_size_ * seq_len, hidden_dim))
7,109
def test_read_fhd_write_read_uvfits_no_layout(): """ Test errors/warnings with with no layout file. """ fhd_uv = UVData() files_use = testfiles[:-3] + [testfiles[-2]] # check warning raised with uvtest.check_warnings(UserWarning, "No layout file"): fhd_uv.read(files_use, run_check=False) with pytest.raises( ValueError, match="Required UVParameter _antenna_positions has not been set" ): with uvtest.check_warnings(UserWarning, "No layout file"): fhd_uv.read(files_use)
7,110
def get_log_likelihood(P, v, subs_counts): """ The stationary distribution of P is empirically derived. It is proportional to the codon counts by construction. @param P: a transition matrix using codon counts and free parameters @param v: stationary distribution proportional to observed codon counts @param subs_counts: observed substitution counts """ A = subs_counts B = algopy.log(P.T * v) log_likelihoods = slow_part(A, B) return algopy.sum(log_likelihoods)
7,111
def create_identity_model( model_dir, signature_name=( tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY), tags=(tf.saved_model.tag_constants.SERVING,)): """Create a model and saved it in SavedModel format.""" g, signature_def_map = _identity_string_graph(signature_name) _write_graph(g, signature_def_map, list(tags), model_dir)
7,112
def allChampMast(_reg, _summonerId, _apiKey): """Get all champion mastery entries sorted by number of champion points descending""" response = requests.get("https://" + _reg + ".api.riotgames.com/lol/champion-mastery/v4/champion-masteries/by-summoner/" + _summonerId +"?api_key=" + _apiKey) data = json.loads(response.text) print(json.dumps(data, indent=4))
7,113
def union(l1, l2): """ return the union of two lists """ return list(set(l1) | set(l2))
7,114
def actual_kwargs(): """ Decorator that provides the wrapped function with an attribute 'actual_kwargs' containing just those keyword arguments actually passed in to the function. Based on code from http://stackoverflow.com/a/1409284/127480 """ def decorator(function): def inner(*args, **kwargs): inner.actual_kwargs = kwargs inner.actual_kwargs_except = \ lambda keys: {key: value for key, value in kwargs.iteritems() if key not in keys} return function(*args, **kwargs) return inner return decorator
7,115
def k1(f, t, y, paso): """ f : funcion a integrar. Retorna un np.ndarray t : tiempo en el cual evaluar la funcion f y : para evaluar la funcion f paso : tamano del paso a usar. """ output = paso * f(t, y) return output
7,116
def script_from_json_string(json_string, base_dir=None): """Returns a Script instance parsed from the given string containing JSON. """ raw_json = json.loads(json_string) if not raw_json: raw_json = [] return script_from_data(raw_json, base_dir)
7,117
def write_version_file(version): """Writes a file with version information to be used at run time Parameters ---------- version: str A string containing the current version information Returns ------- version_file: str A path to the version file """ try: git_log = subprocess.check_output( ["git", "log", "-1", "--pretty=%h %ai"] ).decode("utf-8") git_diff = ( subprocess.check_output(["git", "diff", "."]) + subprocess.check_output(["git", "diff", "--cached", "."]) ).decode("utf-8") if git_diff == "": git_status = "(CLEAN) " + git_log else: git_status = "(UNCLEAN) " + git_log except Exception as e: print(f"Unable to obtain git version information, exception: {e}") git_status = "release" version_file = ".version" long_version_file = f"cached_interpolate/{version_file}" if os.path.isfile(long_version_file) is False: with open(long_version_file, "w+") as f: f.write(f"{version}: {git_status}") return version_file
7,118
def check_api_key(key: str, hashed: str) -> bool: """ Check a API key string against a hashed one from the user database. :param key: the API key to check :type key: str :param hashed: the hashed key to check against :type hashed: str """ return hash_api_key(key) == hashed
7,119
def travel_chart(user_list, guild): """ Builds the chart to display travel data for Animal Crossing :param user_list: :param guild: :return: """ out_table = [] fruit_lookup = {'apple': '🍎', 'pear': '🍐', 'cherry': '🍒', 'peach': '🍑', 'orange': '🍊'} for user in user_list: discord_user = guild.get_member(user.discord_id) if discord_user: discord_name = clean_string(discord_user.display_name, max_length=DISPLAY_CHAR_LIMIT) else: discord_name = user.discord_id island_open = '✈️' if user.island_open else '⛔' fruit = fruit_lookup[user.fruit] if user.fruit != '' else '' dodo_code = clean_string(user.dodo_code, max_length=8) out_table.append([discord_name, dodo_code, island_open + fruit]) return tabulate(out_table, headers=['User', 'Dodo', '🏝️ '], disable_numparse=True)
7,120
def evaluate_hyperparameters(parameterization): """ Train and evaluate the network to find the best parameters Args: parameterization: The hyperparameters that should be evaluated Returns: float: classification accuracy """ net = Net() net, _, _ = train_bayesian_optimization(net=net, input_picture=DATA['x_train'],\ label_picture=DATA['y_train'], parameters=parameterization,) return eval_bayesian_optimization(net=net, input_picture=DATA['x_valid'],\ label_picture=DATA['y_valid'],)
7,121
def get_post_type(h_entry, custom_properties=[]): """ Return the type of a h-entry per the Post Type Discovery algorithm. :param h_entry: The h-entry whose type to retrieve. :type h_entry: dict :param custom_properties: The optional custom properties to use for the Post Type Discovery algorithm. :type custom_properties: list[tuple[str, str]] :return: The type of the h-entry. :rtype: str """ post = h_entry.get("properties") if post is None: return "unknown" values_to_check = [ ("rsvp", "rsvp"), ("in-reply-to", "reply"), ("repost-of", "repost"), ("like-of", "like"), ("video", "video"), ("photo", "photo"), ("summary", "summary"), ] for prop in custom_properties: if len(prop) == 2 and type(prop) == tuple: values_to_check.append(prop) else: raise Exception("custom_properties must be a list of tuples") for item in values_to_check: if post.get(item[0]): return item[1] post_type = "note" if post.get("name") is None or post.get("name")[0] == "": return post_type title = post.get("name")[0].strip().replace("\n", " ").replace("\r", " ") content = post.get("content") if content and content[0].get("text") and content[0].get("text")[0] != "": content = BeautifulSoup(content[0].get("text"), "lxml").get_text() if content and content[0].get("html") and content[0].get("html")[0] != "": content = BeautifulSoup(content[0].get("html"), "lxml").get_text() if not content.startswith(title): return "article" return "note"
7,122
def get_start_end(sequence, skiplist=['-','?']): """Return position of first and last character which is not in skiplist. Skiplist defaults to ['-','?']).""" length=len(sequence) if length==0: return None,None end=length-1 while end>=0 and (sequence[end] in skiplist): end-=1 start=0 while start<length and (sequence[start] in skiplist): start+=1 if start==length and end==-1: # empty sequence return -1,-1 else: return start,end
7,123
def view_event(request, eventid): """ View an Event. :param request: Django request object (Required) :type request: :class:`django.http.HttpRequest` :param eventid: The ObjectId of the event to get details for. :type eventid: str :returns: :class:`django.http.HttpResponse` """ analyst = request.user.username template = 'event_detail.html' (new_template, args) = get_event_details(eventid, analyst) if new_template: template = new_template return render_to_response(template, args, RequestContext(request))
7,124
def main(): """Main script.""" (opts, args) = parser.parse_args() if opts.howto: print HOWTO return 1 if not args: print "No sensor expression given." parser.print_usage() return 1 if opts.cm_url in CM_URLS: cm = CentralStore(CM_URLS[opts.cm_url], opts.sensor_cache) else: cm = CentralStore(opts.cm_url, opts.sensor_cache) print "Using central monitor %s" % (cm.url,) print "Using sensor cache %s" % (cm.cache,) if opts.start_time is None: start = None start_s = 0 else: start = parse_date(opts.start_time) start_s = calendar.timegm(start.timetuple()) print "Start of date range:", start.strftime(DEFAULT_FORMATS[0]) if opts.end_time is None: end = None end_s = 0 else: end = parse_date(opts.end_time) end_s = calendar.timegm(end.timetuple()) print "End of date range:", end.strftime(DEFAULT_FORMATS[0]) if opts.title is None: title = "Sensor data from %s" % (opts.cm_url) else: title = opts.title sensor_names = cm.sensor_names() matching_names = set() for regex in [re.compile(arg) for arg in args]: matching_names.update(name for name in sensor_names if regex.search(name)) matching_names = list(sorted(matching_names)) sensors = [] for name in matching_names: sensor = cm.sensor(name) if sensor is None: print "Omitting sensor %s (no data found)." % (name,) sensors.append(sensor) if opts.list_sensors: print "Matching sensors" print "----------------" for sensor in sensors: print ", ".join(["%s.%s" % (sensor.parent_name, sensor.name), sensor.type, sensor.units, sensor.description]) return if opts.list_dates: for sensor in sensors: fullname = "%s.%s" % (sensor.parent_name, sensor.name) history = sensor.list_stored_history(start_time=start_s, end_time=end_s, return_array=True) if history is None: history = [] history = [(entry[0], entry[1]) for entry in history] history.sort() compacted = [] current_start, current_end = 0, 0 allowed_gap = 60*5 for start, end in history: if start > current_end + allowed_gap: if current_start: compacted.append((current_start, current_end)) current_start, current_end = start, end else: current_end = end if current_start: compacted.append((current_start, current_end)) print print "Available data for", fullname print "-------------------" + "-"*len(fullname) if not compacted: print "No data in range." for start, end in compacted: start = datetime.datetime.fromtimestamp(start) end = datetime.datetime.fromtimestamp(end) format = DEFAULT_FORMATS[0] print start.strftime(format), " -> ", end.strftime(format) return if opts.plot_graph: import matplotlib.pyplot as plt ap = AnimatableSensorPlot(title=title, source="stored", start_time=start_s, end_time=end_s, legend_loc=opts.legend_loc) for sensor in sensors: ap.add_sensor(sensor) ap.show() plt.show() return if True: for sensor in sensors: dump_file = "%s.%s.csv" % (sensor.parent_name, sensor.name) sensor.get_stored_history(start_time=start_s, end_time=end_s, dump_file=dump_file, select=False) return
7,125
def archiveOpen(self, file, path): """ This gets added to the File model to open a path within an archive file. :param file: the file document. :param path: the path within the archive file. :returns: a file-like object that can be used as a context or handle. """ return ArchiveFileHandle(self, file, path)
7,126
def get_masked_bin(args, key: int) -> str: """Given an input, output, and mask type: read the bytes, identify the factory, mask the bytes, write them to disk.""" if args.bin == None or args.mask == None: logger.bad("Please specify -b AND -m (bin file and mask)") return None # get the bytes of the input bin blob: bytes = helpers.get_bytes_from_file(args.bin) # if that isnt possible, return. if blob == None: return None logger.info(f"Loaded {args.bin} ({len(blob)} bytes)") # get the correct factory factory = get_mask_factory(args.mask) # if that fails, return. if factory == None: return None # if the factory is obtained, grab the class for the mask mask = factory.get_mask_type() logger.info(f"Masking shellcode with: {factory.name}") # XOR if (key != 0): # python 3 should ~~~ theoretically ~~~ handle a list of integers by auto converting to bytes blob blob: bytes = bytes([x ^ key for x in blob]) # give the blob to the class and perform whatever transformations... This should then return a multiline string containing the transformed data return mask.mask(blob, args.payload_preview)
7,127
def count_entries(df, col_name = 'lang'): """Return a dictionary with counts of occurrences as value for each key.""" # Initialize an empty dictionary: cols_count cols_count = {} # Extract column from DataFrame: col col = df[col_name] # Iterate over the column in DataFrame for entry in col: # If entry is in cols_count, add 1 if entry in cols_count.keys(): cols_count[entry] += 1 # Else add the entry to cols_count, set the value to 1 else: cols_count[entry] = 1 # Return the cols_count dictionary return cols_count
7,128
def print_header(size: int, name: str): """ Print a header looking like this : ------ NAME ------ :param size: width of the header in characters :type size: int :param name: name displayed by the header :type name: str """ templateBar = "{:-^" + str(size) + "s}" templateName = "{:^" + str(size) + "s}" print(bcolors.HEADER, flush=True) print(templateBar.format(""), flush=True) print(templateName.format(name.upper()), flush=True) print(templateBar.format(""), flush=True) print(bcolors.ENDC, flush=True)
7,129
def bo_run_7(): """ Run the bayesian optimization experiemnt 7. Same as experiment 6, but with ARD kernel, different tolerance and different max_iter. """ import GPyOpt import pickle exper = IE5_experiment_6(0,2) domain =[{'name': 'init_runs', 'type': 'discrete', 'domain': np.arange(200,501,30) }, #{'name': 'hidden_dims', 'type': 'discrete', 'domain': (1,2,3,4)}, {'name': 'Q', 'type': 'discrete', 'domain': np.arange(60,201,10) } ] kernel = GPy.kern.RBF(len(domain),ARD=True) Bopt = GPyOpt.methods.BayesianOptimization(f=exper, # function to optimize domain=domain, # box-constrains of the problem model_type = 'GP_MCMC', kernel=kernel, initial_design_numdata = 3,# number data initial design acquisition_type='EI_MCMC', # Expected Improvement exact_feval = False) #import pdb; pdb.set_trace() # --- Stop conditions max_time = None max_iter = 7 tolerance = 1e-2 # distance between two consecutive observations # Run the optimization report_file = 'report_IE5_experiment_7(0,2)' evaluations_file = 'eval_IE5_experiment_7(0,2)' models_file = 'model_IE5_experiment_7(0,2)' Bopt.run_optimization(max_iter = max_iter, max_time = max_time, eps = tolerance, verbosity=True, report_file = report_file, evaluations_file= evaluations_file, models_file=models_file, acquisition_par=3) # acquisition_par is # used to make it more explorative. It seems it did not help. #acquisition_type ='LCB', # LCB acquisition #acquisition_weight = 0.1) ff = open('IE5_experiment_7(0,2)','w') pickle.dump(Bopt,ff) ff.close()
7,130
def polyPoke(*args, **kwargs): """ Introduces a new vertex in the middle of the selected face, and connects it to the rest of the vertices of the face. Returns: `string` The node name """ pass
7,131
def workerfunc(prob, *args, **kwargs): """ Helper function for wrapping class methods to allow for use of the multiprocessing package """ return prob.run_simulation(*args, **kwargs)
7,132
def ensure_pytest_builtin_helpers(helpers='skip raises'.split()): """ hack (py.test.) raises and skip into builtins, needed for applevel tests to run directly on cpython but apparently earlier on "raises" was already added to module's globals. """ import __builtin__ for helper in helpers: if not hasattr(__builtin__, helper): setattr(__builtin__, helper, getattr(py.test, helper))
7,133
async def client(hass, hass_ws_client): """Fixture that can interact with the config manager API.""" with patch.object(config, "SECTIONS", ["core"]): assert await async_setup_component(hass, "config", {}) return await hass_ws_client(hass)
7,134
def test_curve_plot(curve): """ Tests mpl image of curve. """ fig = curve.plot().get_figure() return fig
7,135
async def _app_parser_stats(): """Retrieve / update cached parser stat information. Fields: id: identifier of parser size_doc: approximate size (bytes) per document or null """ parser_cfg = faw_analysis_set_util.lookup_all_parsers( app_mongodb_conn.delegate, app_config) parsers = [] promises = [] for k, v in parser_cfg.items(): if v.get('disabled'): continue parser = { 'id': k, 'size_doc': None, 'pipeline': True if v.get('pipeline') else False, } parsers.append(parser) r = _app_parser_sizetable.get(k) if r is not None and r[1] > time.monotonic(): parser['size_doc'] = r[0] else: async def stat_pop(k, parser): ndocs = 5 # Only include successful runs docs = await app_mongodb_conn['invocationsparsed'].find({ 'parser': k, 'exitcode': 0}).limit(ndocs).to_list(None) size = None if len(docs) > 1: # Size is actually a differential. Indicates information # added per additional document due to unique features. size = 0 fts_size = set([dr['k'] for dr in docs[0]['result']]) for d in docs[1:]: fts_new = set([dr['k'] for dr in d['result']]) fts_new.difference_update(fts_size) size += len(pickle.dumps(fts_new)) fts_size.update(fts_new) size /= len(docs) - 1 if len(docs) == ndocs: # Keep result for a long time r = [size, time.monotonic() + 600] else: # Let it load, don't hammer the DB r = [size, time.monotonic() + 30] _app_parser_sizetable[k] = r parser['size_doc'] = r[0] promises.append(asyncio.create_task(stat_pop(k, parser))) if promises: await asyncio.wait(promises) return parsers
7,136
async def test_publishing_with_custom_encoding( hass, mqtt_mock_entry_with_yaml_config, caplog, service, topic, parameters, payload, template, ): """Test publishing MQTT payload with command templates and different encoding.""" domain = siren.DOMAIN config = copy.deepcopy(DEFAULT_CONFIG[domain]) config[siren.ATTR_AVAILABLE_TONES] = ["siren", "xylophone"] await help_test_publishing_with_custom_encoding( hass, mqtt_mock_entry_with_yaml_config, caplog, domain, config, service, topic, parameters, payload, template, )
7,137
def test_announcement_get_price_result(): """Testing the announcement get_price_result function.""" # TODO assert False
7,138
def update_wishlists(wishlist_id): """ Update a Wishlist This endpoint will update a Wishlist based the body that is posted """ app.logger.info('Request to Update a wishlist with id [%s]', wishlist_id) check_content_type('application/json') wishlist = Wishlist.find(wishlist_id) if not wishlist: raise NotFound("Wishlist with id '{}' was not found.".format(wishlist_id)) data = request.get_json() app.logger.info(data) wishlist.deserialize(data) wishlist.id = wishlist_id wishlist.save() return make_response(jsonify(wishlist.serialize()), status.HTTP_200_OK)
7,139
def simplifiedview(av_data: dict, filehash: str) -> str: """Builds and returns a simplified string containing basic information about the analysis""" neg_detections = 0 pos_detections = 0 error_detections = 0 for engine in av_data: if av_data[engine]['category'] == 'malicious' or av_data[engine]['category'] == 'suspicious': neg_detections += 1 elif av_data[engine]['category'] == 'undetected': pos_detections += 1 elif av_data[engine]['category'] == 'timeout' or av_data[engine]['category'] == 'type-unsupported' \ or av_data[engine]['category'] == 'failure': error_detections += 1 vt_url = f'https://www.virustotal.com/gui/file/{filehash}' response = f"__VirusTotal Analysis Summary__:\n\nHash: `{filehash}`\n\nLink: [Click Here]({vt_url})\n\n❌" \ f" **Negative: {neg_detections}**\n\n✅ Positive: {pos_detections}\n\n⚠ " \ f"Error/Unsupported File: {error_detections}" return response
7,140
def decompress_hyper(y_strings, y_min_vs, y_max_vs, y_shape, z_strings, z_min_v, z_max_v, z_shape, model, ckpt_dir): """Decompress bitstream to cubes. Input: compressed bitstream. latent representations (y) and hyper prior (z). Output: cubes with shape [batch size, length, width, height, channel(1)] """ print('===== Decompress =====') # load model. #model = importlib.import_module(model) synthesis_transform = model.SynthesisTransform() hyper_encoder = model.HyperEncoder() hyper_decoder = model.HyperDecoder() entropy_bottleneck = EntropyBottleneck() conditional_entropy_model = SymmetricConditional() checkpoint = tf.train.Checkpoint(synthesis_transform=synthesis_transform, hyper_encoder=hyper_encoder, hyper_decoder=hyper_decoder, estimator=entropy_bottleneck) status = checkpoint.restore(tf.train.latest_checkpoint(ckpt_dir)) start = time.time() zs = entropy_bottleneck.decompress(z_strings, z_min_v, z_max_v, z_shape, z_shape[-1]) print("Entropy Decoder (Hyper): {}s".format(round(time.time()-start, 4))) def loop_hyper_deocder(z): z = tf.expand_dims(z, 0) loc, scale = hyper_decoder(z) return tf.squeeze(loc, [0]), tf.squeeze(scale, [0]) start = time.time() locs, scales = tf.map_fn(loop_hyper_deocder, zs, dtype=(tf.float32, tf.float32), parallel_iterations=1, back_prop=False) lower_bound = 1e-9# TODO scales = tf.maximum(scales, lower_bound) print("Hyper Decoder: {}s".format(round(time.time()-start, 4))) start = time.time() # ys = conditional_entropy_model.decompress(y_strings, locs, scales, y_min_v, y_max_v, y_shape) def loop_range_decode(args): y_string, loc, scale, y_min_v, y_max_v = args loc = tf.expand_dims(loc, 0) scale = tf.expand_dims(scale, 0) y_decoded = conditional_entropy_model.decompress(y_string, loc, scale, y_min_v, y_max_v, y_shape) return tf.squeeze(y_decoded, 0) args = (y_strings, locs, scales, y_min_vs, y_max_vs) ys = tf.map_fn(loop_range_decode, args, dtype=tf.float32, parallel_iterations=1, back_prop=False) print("Entropy Decoder: {}s".format(round(time.time()-start, 4))) def loop_synthesis(y): y = tf.expand_dims(y, 0) x = synthesis_transform(y) return tf.squeeze(x, [0]) start = time.time() xs = tf.map_fn(loop_synthesis, ys, dtype=tf.float32, parallel_iterations=1, back_prop=False) print("Synthesis Transform: {}s".format(round(time.time()-start, 4))) return xs
7,141
def GetManualInsn(ea): """ Get manual representation of instruction @param ea: linear address @note: This function returns value set by SetManualInsn earlier. """ return idaapi.get_manual_insn(ea)
7,142
def test_regular_expression(exp=".*", text="", fLOG=fLOG): """ Tests a regular expression. @param exp regular expression @param text text to check @param fLOG logging function """ fLOG("regex", exp) fLOG("text", text) ex = re.compile(exp) ma = ex.search(text) if ma is None: fLOG("no result") else: fLOG(ma.groups())
7,143
def feature_time(data: pd.DataFrame) -> pd.DataFrame: """ Time Feature Engineering. """ # print(data) # print(data.info()) day = 24*60*60 year = (365.2425)*day time_stp = data['time'].apply( lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:00") if isinstance(x, str) else x ).map(datetime.timestamp) data['day_sin'] = np.sin(time_stp * (2*np.pi / day)) data['day_cos'] = np.cos(time_stp * (2*np.pi / day)) data['year_sin'] = np.sin(time_stp * (2*np.pi / year)) data['year_cos'] = np.cos(time_stp * (2*np.pi / year)) return data
7,144
def _transform(mock_file) -> Tuple[List[Page], SaneJson]: """ Prepare the data as sections before calling report """ transformer = Transform(get_mock(mock_file, ret_dict=False)) sane_json = transformer.get_sane_json() pages = transformer.get_pages() return pages, sane_json
7,145
def ProcessOptions(): """Process and validate command line arguments and options""" MiscUtil.PrintInfo("Processing options...") # Validate options... ValidateOptions() AllowParamFailure = True if re.match("^No", Options["--allowParamFailure"], re.I): AllowParamFailure = False OptionsInfo["AllowParamFailure"] = AllowParamFailure AtomAliasesFormatMode = True if re.match("^DataField", Options["--chargesSDFormat"], re.I): AtomAliasesFormatMode = False OptionsInfo["AtomAliasesFormatMode"] = AtomAliasesFormatMode OptionsInfo["DataFieldLabel"] = Options["--dataFieldLabel"] MMFFChargesMode = False if re.match("^MMFF", Options["--mode"], re.I): MMFFChargesMode = True OptionsInfo["Mode"] = Options["--mode"] OptionsInfo["MMFFChargesMode"] = MMFFChargesMode OptionsInfo["MPMode"] = True if re.match("^yes$", Options["--mp"], re.I) else False OptionsInfo["MPParams"] = MiscUtil.ProcessOptionMultiprocessingParameters("--mpParams", Options["--mpParams"]) OptionsInfo["Infile"] = Options["--infile"] OptionsInfo["InfileParams"] = MiscUtil.ProcessOptionInfileParameters("--infileParams", Options["--infileParams"], Options["--infile"]) OptionsInfo["Outfile"] = Options["--outfile"] OptionsInfo["OutfileParams"] = MiscUtil.ProcessOptionOutfileParameters("--outfileParams", Options["--outfileParams"], Options["--infile"], Options["--outfile"]) OptionsInfo["Overwrite"] = Options["--overwrite"] OptionsInfo["NumIters"] = int(Options["--numIters"]) OptionsInfo["Precision"] = int(Options["--precision"])
7,146
def make_table(rows: List[List[Any]], labels: Optional[List[Any]] = None, centered: bool = False) -> str: """ :param rows: 2D array containing object that can be converted to string using `str(obj)`. :param labels: Array containing the column labels, the length must equal that of rows. :param centered: If the items should be aligned to the center, else they are left aligned. :return: A table representing the rows passed in. """ # Transpose into columns columns = list(transpose(labels, *rows) if labels else transpose(*rows)) # Padding for column in columns: # Find the required column width column_width = max(map(len, map(str, column))) # Add and record padding for i, item in enumerate(column): column[i] = f' {str(item):^{column_width}} ' if centered else f' {str(item):<{column_width}} ' # Border Widths horizontal_lines = tuple('─' * len(column[0]) for column in columns) # Create a list of rows with the row separators rows = [row_with_separators(('│', '│', '│'), row) for row in transpose(*columns)] # Create a separator between the labels and the values if needed if labels: label_border_bottom = row_with_separators(('├', '┼', '┤'), horizontal_lines) rows.insert(1, label_border_bottom) # Create the top and bottom border of the table top_border = row_with_separators(('┌', '┬', '┐'), horizontal_lines) rows.insert(0, top_border) bottom_border = row_with_separators(('└', '┴', '┘'), horizontal_lines) rows.append(bottom_border) # Join all the components return '\n'.join(rows)
7,147
def quantify_leakage(align_net_file, train_contigs, valid_contigs, test_contigs, out_dir): """Quanitfy the leakage across sequence sets.""" def split_genome(contigs): genome_contigs = [] for ctg in contigs: while len(genome_contigs) <= ctg.genome: genome_contigs.append([]) genome_contigs[ctg.genome].append((ctg.chr,ctg.start,ctg.end)) genome_bedtools = [pybedtools.BedTool(ctgs) for ctgs in genome_contigs] return genome_bedtools def bed_sum(overlaps): osum = 0 for overlap in overlaps: osum += int(overlap[2]) - int(overlap[1]) return osum train0_bt, train1_bt = split_genome(train_contigs) valid0_bt, valid1_bt = split_genome(valid_contigs) test0_bt, test1_bt = split_genome(test_contigs) assign0_sums = {} assign1_sums = {} if os.path.splitext(align_net_file)[-1] == '.gz': align_net_open = gzip.open(align_net_file, 'rt') else: align_net_open = open(align_net_file, 'r') for net_line in align_net_open: if net_line.startswith('net'): net_a = net_line.split() chrom0 = net_a[1] elif net_line.startswith(' fill'): net_a = net_line.split() # extract genome1 interval start0 = int(net_a[1]) size0 = int(net_a[2]) end0 = start0+size0 align0_bt = pybedtools.BedTool([(chrom0,start0,end0)]) # extract genome2 interval chrom1 = net_a[3] start1 = int(net_a[5]) size1 = int(net_a[6]) end1 = start1+size1 align1_bt = pybedtools.BedTool([(chrom1,start1,end1)]) # count interval overlap align0_train_bp = bed_sum(align0_bt.intersect(train0_bt)) align0_valid_bp = bed_sum(align0_bt.intersect(valid0_bt)) align0_test_bp = bed_sum(align0_bt.intersect(test0_bt)) align0_max_bp = max(align0_train_bp, align0_valid_bp, align0_test_bp) align1_train_bp = bed_sum(align1_bt.intersect(train1_bt)) align1_valid_bp = bed_sum(align1_bt.intersect(valid1_bt)) align1_test_bp = bed_sum(align1_bt.intersect(test1_bt)) align1_max_bp = max(align1_train_bp, align1_valid_bp, align1_test_bp) # assign to class if align0_max_bp == 0: assign0 = None elif align0_train_bp == align0_max_bp: assign0 = 'train' elif align0_valid_bp == align0_max_bp: assign0 = 'valid' elif align0_test_bp == align0_max_bp: assign0 = 'test' else: print('Bad logic') exit(1) if align1_max_bp == 0: assign1 = None elif align1_train_bp == align1_max_bp: assign1 = 'train' elif align1_valid_bp == align1_max_bp: assign1 = 'valid' elif align1_test_bp == align1_max_bp: assign1 = 'test' else: print('Bad logic') exit(1) # increment assign0_sums[(assign0,assign1)] = assign0_sums.get((assign0,assign1),0) + align0_max_bp assign1_sums[(assign0,assign1)] = assign1_sums.get((assign0,assign1),0) + align1_max_bp # sum contigs splits0_bp = {} splits0_bp['train'] = bed_sum(train0_bt) splits0_bp['valid'] = bed_sum(valid0_bt) splits0_bp['test'] = bed_sum(test0_bt) splits1_bp = {} splits1_bp['train'] = bed_sum(train1_bt) splits1_bp['valid'] = bed_sum(valid1_bt) splits1_bp['test'] = bed_sum(test1_bt) leakage_out = open('%s/leakage.txt' % out_dir, 'w') print('Genome0', file=leakage_out) for split0 in ['train','valid','test']: print(' %5s: %10d nt' % (split0, splits0_bp[split0]), file=leakage_out) for split1 in ['train','valid','test',None]: ss_bp = assign0_sums.get((split0,split1),0) print(' %5s: %10d (%.5f)' % (split1, ss_bp, ss_bp/splits0_bp[split0]), file=leakage_out) print('\nGenome1', file=leakage_out) for split1 in ['train','valid','test']: print(' %5s: %10d nt' % (split1, splits1_bp[split1]), file=leakage_out) for split0 in ['train','valid','test',None]: ss_bp = assign1_sums.get((split0,split1),0) print(' %5s: %10d (%.5f)' % (split0, ss_bp, ss_bp/splits1_bp[split1]), file=leakage_out) leakage_out.close()
7,148
def coef_determ(y_sim, y_obs): """ calculate the coefficient of determination :param y_sim: series of simulated values :param y_obs: series of observed values :return: """ assert y_sim.ndim == 1 and y_obs.ndim == 1 and len(y_sim) == len(y_obs) r = np.corrcoef(y_sim, y_obs) r2 = r[0, 1] ** 2 return r2
7,149
async def generate_latest_metrics(client): """Generate the latest metrics and transform the body.""" resp = await client.get(prometheus.API_ENDPOINT) assert resp.status == HTTPStatus.OK assert resp.headers["content-type"] == CONTENT_TYPE_TEXT_PLAIN body = await resp.text() body = body.split("\n") assert len(body) > 3 return body
7,150
def vsphere(r): """volume sphere""" print(4 / 3 * math.pi * r ** 3)
7,151
def carrierchecker_bundles(mcc, mnc, hwid): """ :param mcc: Country code. :type mcc: int :param mnc: Network code. :type mnc: int :param hwid: Device hardware ID. :type hwid: str """ releases = networkutils.available_bundle_lookup(mcc, mnc, hwid) print("\nAVAILABLE BUNDLES:") utilities.lprint(releases)
7,152
def cmd_tags(request): """Список тегов Вывод топа клубов с количеством сообщений для каждого redeye: tags """ tags = list(x.doc for x in (yield objs.Tag.find_sort({'_id': {'$ne': ''}}, [('value', -1)], limit=20))) defer.returnValue(dict(ok=True, format='tags', tags=tags, cache=3600, cache_public=True))
7,153
def test_constructor_loads_info_from_constant(): """Test non-dev mode loads info from SERVERS constant.""" hass = MagicMock(data={}) with patch.dict(cloud.SERVERS, { 'beer': { 'cognito_client_id': 'test-cognito_client_id', 'user_pool_id': 'test-user_pool_id', 'region': 'test-region', 'relayer': 'test-relayer', 'google_actions_sync_url': 'test-google_actions_sync_url', 'subscription_info_url': 'test-subscription-info-url' } }), patch('homeassistant.components.cloud.Cloud._fetch_jwt_keyset', return_value=mock_coro(True)): result = yield from cloud.async_setup(hass, { 'cloud': {cloud.CONF_MODE: 'beer'} }) assert result cl = hass.data['cloud'] assert cl.mode == 'beer' assert cl.cognito_client_id == 'test-cognito_client_id' assert cl.user_pool_id == 'test-user_pool_id' assert cl.region == 'test-region' assert cl.relayer == 'test-relayer' assert cl.google_actions_sync_url == 'test-google_actions_sync_url' assert cl.subscription_info_url == 'test-subscription-info-url'
7,154
def simulate(population: int, n: int, timer: int) -> int: """ Recursively simulate population growth of the fish. Args: population (int): Starting population n (int): Number of days to simulate. timer (int): The reset timer of the fish initialised at 6 or 8 depending on whether it's newborn, and decremented on each round. Returns: int: The population of fish after `n` days """ if n == 0: # It's the start return population if timer == 0: # A fish's timer has reached 0 # create required new fish newborns = simulate(population, n - 1, NEW_FISH_TIMER) current = simulate(population, n - 1, TIMER_START) return current + newborns return simulate(population, n - 1, timer - 1)
7,155
def execute_deeper(source, table1, table2, number_of_pairs, destination, predictionsFileName): """ This method runs deeper on a dataset. """ table1_path = "" table2_path = "" predictions_file_path = "" pred_pairs_path = "" threshold_path = "" if source.endswith("/"): table1_path = source + table1 table2_path = source + table2 threshold_path = source + "threshold.txt" else: table1_path = source + "/" + table1 table2_path = source + "/" + table2 threshold_path = source + "/" + "threshold.txt" if destination.endswith("/"): predictions_file_path = destination + predictionsFileName pred_pairs_path = destination + "pred_pairs_" + number_of_pairs + ".csv" else: predictions_file_path = destination + "/" + predictionsFileName pred_pairs_path = destination + "/" + "pred_pairs_" + number_of_pairs + ".csv" params=[source, table1_path, table2_path, "6", pred_pairs_path, number_of_pairs, predictions_file_path, threshold_path, "1", destination ] print("number of pairs is " + number_of_pairs) print("threshold file is " + threshold_path) # params=["/Users/emansour/elab/DAGroup/DataCivilizer/github/data_civilizer_system/storage/data_sets/deeper/Amazon-GoogleProducts", # "/Users/emansour/elab/DAGroup/DataCivilizer/github/data_civilizer_system/storage/data_sets/deeper/Amazon_full.csv", # "/Users/emansour/elab/DAGroup/DataCivilizer/github/data_civilizer_system/storage/data_sets/deeper/GoogleProducts_full.csv", # "/Users/emansour/elab/DAGroup/DataCivilizer/github/data_civilizer_system/storage/data_sets/deeper/pred_pairs_No.csv", # "10000", # "/Users/emansour/elab/DAGroup/DataCivilizer/github/data_civilizer_system/storage/data_sets/deeper/output/matches.csv", # "/Users/emansour/elab/DAGroup/DataCivilizer/github/data_civilizer_system/storage/data_sets/deeper/threshold.txt", # "/Users/emansour/elab/DAGroup/DataCivilizer/github/data_civilizer_system/storage/data_sets/deeper/output" # ] # tool_path="/Users/emansour/elab/DAGroup/DataCivilizer/github/data_civilizer_system/civilizer_services/deeper_service/DeepER-Lite/" tool_path = "/app/rest/services/deeper_service/DeepER-Lite/" # tool_path = "/app/DeepER-Lite/" # command = [tool_path + "{}/dBoost/dboost/dboost-stdin.py".format(TOOLS_FOLDER), "-F", ",",dataset_path] + dboost_parameters # p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # p.communicate() command = [tool_path+"run-2.sh"] command.extend(params) print(command) # p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # p = subprocess.Popen(command, stdout=subprocess.PIPE).communicate()[0] # p.communicate() # print(p) p = subprocess.Popen(command, stdout=subprocess.PIPE) out, err = p.communicate() # print("out\n" + out) # print("err\n" + err) print("create Clusters") prediction_file = predictions_file_path.replace(".csv", "_0.csv") createClusters(table1_path, table2_path, prediction_file, predictions_file_path)
7,156
def normalize_valign(valign, err): """ Split align into (valign_type, valign_amount). Raise exception err if align doesn't match a valid alignment. """ if valign in (TOP, MIDDLE, BOTTOM): return (valign, None) elif (isinstance(valign, tuple) and len(valign) == 2 and valign[0] == RELATIVE): return valign raise err("valign value %r is not one of 'top', 'middle', " "'bottom', ('relative', percentage 0=left 100=right)" % (valign,))
7,157
def svn_auth_open(*args): """ svn_auth_open(svn_auth_baton_t auth_baton, apr_array_header_t providers, apr_pool_t pool) """ return apply(_core.svn_auth_open, args)
7,158
def create_repository(git): """Create repository""" raise click.ClickException("Not implemented")
7,159
def quote_key(key): """特殊字符'/'转义处理 """ return key.replace('/', '%2F')
7,160
def test_extras_import_mode_strange(new_archive): """Check a mode that probably does not make much sense but is still available (keep original, create new, delete)""" imported_node = import_extras(new_archive) imported_node = modify_extras(new_archive, imported_node, mode_existing=('k', 'c', 'd')) # Check if extras are imported correctly assert imported_node.get_extra('a') == 1 assert imported_node.get_extra('c') == 3 with pytest.raises(AttributeError): # the extra # 'b' should not exist, as the collided extras are deleted imported_node.get_extra('b')
7,161
def download_knbc(target_dir: str): """Downloads the KNBC corpus and extracts files. Args: target_dir: A path to the directory to expand files. """ os.makedirs(target_dir, exist_ok=True) download_file_path = os.path.join(target_dir, 'knbc.tar.bz2') try: urllib.request.urlretrieve(RESOURCE_URL, download_file_path) except urllib.error.HTTPError: print(f'\033[91mResource unavailable: {RESOURCE_URL}\033[0m') raise with tarfile.open(download_file_path, 'r:bz2') as t: t.extractall(path=target_dir)
7,162
def middle(word): """Returns all but the first and last characters of a string.""" return word[1:-1]
7,163
def test_recordmodel(mock_program_dao): """Get a record model instance for each test function.""" dut = mock_program_dao.do_select_all(RAMSTKMissionRecord, _all=False) yield dut # Delete the device under test. del dut
7,164
def surprise_communities(g_original, initial_membership=None, weights=None, node_sizes=None): """ Surprise_communities is a model where the quality function to optimize is: .. math:: Q = m D(q \\parallel \\langle q \\rangle) where :math:`m` is the number of edges, :math:`q = \\frac{\\sum_c m_c}{m}`, is the fraction of internal edges, :math:`\\langle q \\rangle = \\frac{\\sum_c \\binom{n_c}{2}}{\\binom{n}{2}}` is the expected fraction of internal edges, and finally :math:`D(x \\parallel y) = x \\ln \\frac{x}{y} + (1 - x) \\ln \\frac{1 - x}{1 - y}` is the binary Kullback-Leibler divergence. For directed graphs we can multiplying the binomials by 2, and this leaves :math:`\\langle q \\rangle` unchanged, so that we can simply use the same formulation. For weighted graphs we can simply count the total internal weight instead of the total number of edges for :math:`q` , while :math:`\\langle q \\rangle` remains unchanged. :param g_original: a networkx/igraph object :param initial_membership: list of int Initial membership for the partition. If :obj:`None` then defaults to a singleton partition. Deafault None :param weights: list of double, or edge attribute Weights of edges. Can be either an iterable or an edge attribute. Deafault None :param node_sizes: list of int, or vertex attribute Sizes of nodes are necessary to know the size of communities in aggregate graphs. Usually this is set to 1 for all nodes, but in specific cases this could be changed. Deafault None :return: NodeClustering object :Example: >>> from cdlib import algorithms >>> import networkx as nx >>> G = nx.karate_club_graph() >>> coms = algorithms.surprise_communities(G) :References: Traag, V. A., Aldecoa, R., & Delvenne, J.-C. (2015). `Detecting communities using asymptotical surprise. <https://journals.aps.org/pre/abstract/10.1103/PhysRevE.92.022816/>`_ Physical Review E, 92(2), 022816. 10.1103/PhysRevE.92.022816 .. note:: Reference implementation: https://github.com/vtraag/leidenalg """ if ig is None: raise ModuleNotFoundError("Optional dependency not satisfied: install igraph to use the selected feature.") g = convert_graph_formats(g_original, ig.Graph) part = leidenalg.find_partition(g, leidenalg.SurpriseVertexPartition, initial_membership=initial_membership, weights=weights, node_sizes=node_sizes) coms = [g.vs[x]['name'] for x in part] return NodeClustering(coms, g_original, "Surprise", method_parameters={"initial_membership": initial_membership, "weights": weights, "node_sizes": node_sizes})
7,165
def advisory_factory(adv_data, adv_format, logger): """Converts json into a list of advisory objects. :param adv_data: A dictionary describing an advisory. :param adv_format: The target format in ('default', 'ios') :param logger: A logger (for now expecting to be ready to log) :returns advisory instance according to adv_format """ adv_map = {} # Initial fill from shared common model key map: for k, v in ADVISORIES_COMMONS_MAP.items(): adv_map[k] = adv_data[v] if adv_format == constants.DEFAULT_ADVISORY_FORMAT_TOKEN: for k, v in IPS_SIG_MAP.items(): adv_map[k] = adv_data[v] else: # IOS advisory format targeted: for k, v in IOS_ADD_ONS_MAP.items(): if v in adv_data: adv_map[k] = adv_data[v] an_adv = advisory_format_factory_map()[adv_format](**adv_map) logger.debug( "{} Advisory {} Created".format(adv_format, an_adv.advisory_id)) return an_adv
7,166
def _validate_int(value, min, max, type): """Validates a constrained integer value. """ try: ivalue = int(value) if min and max: if ivalue < min or ivalue > max: raise ValueError() except ValueError: err = f"{type} index must be an integer" if min and max: err += f" between {min} and {max}" raise argparse.ArgumentTypeError(err) return ivalue
7,167
def validate_broker(broker_definition): # type: (list) """Validate broker-definition. Set broker-list as a string for admin-conf: 'host:port,host:port'. Keyword arguments: broker_definition -- list containing broker. Pattern per broker: 'host:port'. """ broker_def_list = [] for broker in broker_definition: broker_parts = broker.split(":") if len(broker_parts) == 2: validate_ipv4(broker_parts) if len(broker_parts) > 2: validate_ipv6(broker) if len(broker_parts) < 2: msg = ("Broker-Definition does not seem to be valid: %s" \ " Use following pattern per broker: host:port." \ %(broker) ) fail_module(msg) broker_def_list.append(broker) final_broker_definition = ",".join(broker_def_list) module.params['bootstrap_server'] = final_broker_definition
7,168
def get_azpl(cdec, cinc, gdec, ginc): """ gets azimuth and pl from specimen dec inc (cdec,cinc) and gdec,ginc (geographic) coordinates """ TOL = 1e-4 Xp = dir2cart([gdec, ginc, 1.]) X = dir2cart([cdec, cinc, 1.]) # find plunge first az, pl, zdif, ang = 0., -90., 1., 360. while zdif > TOL and pl < 180.: znew = X[0] * np.sin(np.radians(pl)) + X[2] * np.cos(np.radians(pl)) zdif = abs(Xp[2] - znew) pl += .01 while ang > 0.1 and az < 360.: d, i = dogeo(cdec, cinc, az, pl) ang = angle([gdec, ginc], [d, i]) az += .01 return az - .01, pl - .01
7,169
def read_embroidery(reader, f, settings=None, pattern=None): """Reads fileobject or filename with reader.""" if reader == None: return None if pattern == None: pattern = EmbPattern() if is_str(f): text_mode = False try: text_mode = reader.READ_FILE_IN_TEXT_MODE except AttributeError: pass if text_mode: try: with open(f, "r") as stream: reader.read(stream, pattern, settings) stream.close() except IOError: pass else: try: with open(f, "rb") as stream: reader.read(stream, pattern, settings) stream.close() except IOError: pass else: reader.read(f, pattern, settings) return pattern
7,170
def test_load_configuration(): """ loads the configuration store from it's relevant file. the store has not been loaded yet. """ try: create_config_file('new_settings_load.ini') config_services.load_configuration('new_settings_load') sections = config_services.get_section_names('new_settings_load') assert sections is not None finally: delete_config_file('new_settings_load.ini')
7,171
def load_stdlib_public_names(version: str) -> dict[str, frozenset[str]]: """Load stdlib public names data from JSON file""" if not re.fullmatch(r"\d+\.\d+", version): raise ValueError(f"{version} is not a valid version") try: json_file = Path(__file__).with_name("stdlib_public_names") / ( version + ".json" ) json_text = json_file.read_text(encoding="utf-8") json_obj = json.loads(json_text) return {module: frozenset(names) for module, names in json_obj.items()} except FileNotFoundError: raise ValueError( f"there is no data of stdlib public names for Python version {version}" ) from None
7,172
def deep_q_learning(sess, env, q_estimator, target_estimator, state_processor, num_episodes, experiment_dir, replay_memory_size=500000, replay_memory_init_size=50000, update_target_estimator_every=10000, discount_factor=0.99, epsilon_start=1.0, epsilon_end=0.1, epsilon_decay_steps=500000, batch_size=32, record_video_every=50): """ Q-Learning algorithm for off-policy TD control using Function Approximation. Finds the optimal greedy policy while following an epsilon-greedy policy. Args: sess: Tensorflow Session object env: OpenAI environment q_estimator: Estimator object used for the q values target_estimator: Estimator object used for the targets state_processor: A StateProcessor object num_episodes: Number of episodes to run for experiment_dir: Directory to save Tensorflow summaries in replay_memory_size: Size of the replay memory replay_memory_init_size: Number of random experiences to sampel when initializing the reply memory. update_target_estimator_every: Copy parameters from the Q estimator to the target estimator every N steps discount_factor: Gamma discount factor epsilon_start: Chance to sample a random action when taking an action. Epsilon is decayed over time and this is the start value epsilon_end: The final minimum value of epsilon after decaying is done epsilon_decay_steps: Number of steps to decay epsilon over batch_size: Size of batches to sample from the replay memory record_video_every: Record a video every N episodes Returns: An EpisodeStats object with two numpy arrays for episode_lengths and episode_rewards. """ Transition = namedtuple("Transition", ["state", "action", "reward", "next_state", "done"]) # The replay memory replay_memory = [] # Make model copier object estimator_copy = ModelParametersCopier(q_estimator, target_estimator) # Keeps track of useful statistics stats = plotting.EpisodeStats( episode_lengths=np.zeros(num_episodes), episode_rewards=np.zeros(num_episodes)) # For 'system/' summaries, usefull to check if currrent process looks healthy current_process = psutil.Process() # Create directories for checkpoints and summaries checkpoint_dir = os.path.join(experiment_dir, "checkpoints") checkpoint_path = os.path.join(checkpoint_dir, "model") monitor_path = os.path.join(experiment_dir, "monitor") if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir) if not os.path.exists(monitor_path): os.makedirs(monitor_path) saver = tf.train.Saver() # Load a previous checkpoint if we find one latest_checkpoint = tf.train.latest_checkpoint(checkpoint_dir) if latest_checkpoint: print("Loading model checkpoint {}...\n".format(latest_checkpoint)) saver.restore(sess, latest_checkpoint) # Get the current time step total_t = sess.run(tf.contrib.framework.get_global_step()) # The epsilon decay schedule epsilons = np.linspace(epsilon_start, epsilon_end, epsilon_decay_steps) # The policy we're following policy = make_epsilon_greedy_policy( q_estimator, len(VALID_ACTIONS)) # Populate the replay memory with initial experience print("Populating replay memory...") state = env.reset() state = state_processor.process(sess, state) state = np.stack([state] * 4, axis=2) for i in range(replay_memory_init_size): action_probs = policy(sess, state, epsilons[min(total_t, epsilon_decay_steps-1)]) action = np.random.choice(np.arange(len(action_probs)), p=action_probs) next_state, reward, done, _ = env.step(VALID_ACTIONS[action]) next_state = state_processor.process(sess, next_state) next_state = np.append(state[:,:,1:], np.expand_dims(next_state, 2), axis=2) replay_memory.append(Transition(state, action, reward, next_state, done)) if done: state = env.reset() state = state_processor.process(sess, state) state = np.stack([state] * 4, axis=2) else: state = next_state # Record videos # Add env Monitor wrapper env = Monitor(env, directory=monitor_path, video_callable=lambda count: count % record_video_every == 0, resume=True) for i_episode in range(num_episodes): # Save the current checkpoint saver.save(tf.get_default_session(), checkpoint_path) # Reset the environment state = env.reset() state = state_processor.process(sess, state) state = np.stack([state] * 4, axis=2) loss = None # One step in the environment for t in itertools.count(): # Epsilon for this time step epsilon = epsilons[min(total_t, epsilon_decay_steps-1)] # Maybe update the target estimator if total_t % update_target_estimator_every == 0: estimator_copy.make(sess) print("\nCopied model parameters to target network.") # Print out which step we're on, useful for debugging. print("\rStep {} ({}) @ Episode {}/{}, loss: {}".format( t, total_t, i_episode + 1, num_episodes, loss), end="") sys.stdout.flush() # Take a step action_probs = policy(sess, state, epsilon) action = np.random.choice(np.arange(len(action_probs)), p=action_probs) next_state, reward, done, _ = env.step(VALID_ACTIONS[action]) next_state = state_processor.process(sess, next_state) next_state = np.append(state[:,:,1:], np.expand_dims(next_state, 2), axis=2) # If our replay memory is full, pop the first element if len(replay_memory) == replay_memory_size: replay_memory.pop(0) # Save transition to replay memory replay_memory.append(Transition(state, action, reward, next_state, done)) # Update statistics stats.episode_rewards[i_episode] += reward stats.episode_lengths[i_episode] = t # Sample a minibatch from the replay memory samples = random.sample(replay_memory, batch_size) states_batch, action_batch, reward_batch, next_states_batch, done_batch = map(np.array, zip(*samples)) # Calculate q values and targets q_values_next = target_estimator.predict(sess, next_states_batch) targets_batch = reward_batch + np.invert(done_batch).astype(np.float32) * discount_factor * np.amax(q_values_next, axis=1) # Perform gradient descent update states_batch = np.array(states_batch) loss = q_estimator.update(sess, states_batch, action_batch, targets_batch) if done: break state = next_state total_t += 1 # Add summaries to tensorboard episode_summary = tf.Summary() episode_summary.value.add(simple_value=epsilon, tag="episode/epsilon") episode_summary.value.add(simple_value=stats.episode_rewards[i_episode], tag="episode/reward") episode_summary.value.add(simple_value=stats.episode_lengths[i_episode], tag="episode/length") episode_summary.value.add(simple_value=current_process.cpu_percent(), tag="system/cpu_usage_percent") episode_summary.value.add(simple_value=current_process.memory_percent(memtype="vms"), tag="system/v_memeory_usage_percent") q_estimator.summary_writer.add_summary(episode_summary, i_episode) q_estimator.summary_writer.flush() yield total_t, plotting.EpisodeStats( episode_lengths=stats.episode_lengths[:i_episode+1], episode_rewards=stats.episode_rewards[:i_episode+1]) return stats
7,173
def obs_cb(store): """ callback for observe thread. """ if not store: log.error("obs_cb is broken") return log.info("obs_cb: clear obs_key_cas %s" % store.obs_key_cas) store.obs_key_cas.clear()
7,174
def mask_inside_range(cube, minimum, maximum): """ Mask inside a specific threshold range. Takes a MINIMUM and a MAXIMUM value for the range, and masks off anything that's between the two in the cube data. """ cube.data = np.ma.masked_inside(cube.data, minimum, maximum) return cube
7,175
def s3_client() -> client: """ Returns a boto3 s3 client - configured to point at a specfic endpoint url if provided """ if AWS_RESOURCES_ENDPOINT: return client("s3", endpoint_url=AWS_RESOURCES_ENDPOINT) return client("s3")
7,176
def ts_ac_plot(ts_arr, t_d, dt, p=2): """ Plot autocorrelations, mean += std dev at each lag over a list of time series arrays. Plot in reference to scintillation timescale and time resolution, up to lag p. """ ac_dict = {'lag': [], 'ac': [], 'type': []} p = min(p+1, len(ts_arr[0])) - 1 for i in np.arange(0, p+1): ac_dict['lag'].append(i) ac_dict['ac'].append(stg.func_utils.gaussian(i, 0, t_d / dt / factors.hwem_m)) ac_dict['type'].append('target') j = 0 for ts in ts_arr: ac = autocorr(ts) if j==0: print(ac.shape) j=1 for i in range(0, p+1): ac_dict['lag'].append(i) ac_dict['ac'].append(ac[i]) ac_dict['type'].append('sim') data = pd.DataFrame(ac_dict) # sns.catplot(data=pd.DataFrame(ac_dict), x='lag', y='ac', kind='box',hue='type') ax = sns.lineplot(data=data, x='lag', y='ac', style='type', hue='type', markers=True, dashes=False, ci='sd') # ax.set_xticks(np.arange(0, p+1)) ax.grid() plt.show()
7,177
def tokenize_with_new_mask(orig_text, max_length, tokenizer, orig_labels, orig_re_labels, label_map, re_label_map): """ tokenize a array of raw text and generate corresponding attention labels array and attention masks array """ pad_token_label_id = -100 simple_tokenize_results = [list(tt) for tt in zip( *[simple_tokenize(orig_text[i], tokenizer, orig_labels[i], orig_re_labels[i], label_map, re_label_map, max_length) for i in range(len(orig_text))])] bert_tokens, label_ids, re_label_ids = simple_tokenize_results[0], simple_tokenize_results[1], \ simple_tokenize_results[2] input_ids = [tokenizer.convert_tokens_to_ids(x) for x in bert_tokens] input_ids = pad_sequences(input_ids, maxlen=max_length, dtype="long", truncating="post", padding="post") label_ids = pad_sequences(label_ids, maxlen=max_length, dtype="long", truncating="post", padding="post", value=pad_token_label_id) re_label_ids = pad_sequences(re_label_ids, maxlen=max_length, dtype="long", truncating="post", padding="post", value=pad_token_label_id) attention_masks = [] for seq in input_ids: seq_mask = [float(i > 0) for i in seq] attention_masks.append(seq_mask) attention_masks = np.array(attention_masks) return input_ids, attention_masks, label_ids, re_label_ids
7,178
def zonal_stats_from_raster(vector, raster, bands=None, all_touched=False, custom=None): """ Compute zonal statistics for each input feature across all bands of an input raster. God help ye who supply large non-block encoded rasters or large polygons... By default min, max, mean, standard deviation and sum are computed but the user can also create their own functions to compute custom metrics across the intersecting area for every feature and every band. Functions must accept a 2D masked array extracted from a single band. Should probably be changed to allow the user to compute statistics across all bands. Use `custom={'my_metric': my_metric_func}` to call `my_metric_func` on the intersecting pixels. A key named `my_metric` will be added alongside `min`, `max`, etc. Metrics can also be disabled by doing `custom={'min': None}` to turn off the call to `min`. The `min` key will still be included in the output but will have a value of `None`. While this function will work with any geometry type the input is intended to be polygons. The goal of this function is to be able to take large rasters and a large number of not too giant polygons and be pretty confident that nothing is going to break. There are better methods for collecting statistics if the goal is speed or by optimizing for each datatype. Point layers will work but are not as efficient and should be used with rasterio's `sample()` method, and an initial pass to index points against the raster's blocks. Further optimization could be performed to limit raster I/O for really really large numbers of overlapping polygons but that is outside the intended scope. In order to handle raster larger than available memory and vector datasets containing a large number of features, the minimum bounding box for each feature's geometry is computed and all intersecting raster windows are read. The inverse of the geometry is burned into this subset's mask yielding only the values that intersect the feature. Metrics are then computed against this masked array. Example output: The outer keys are feature ID's { '0': { 'bands': { 1: { 'max': 244, 'mean': 97.771298771710065, 'min': 15, 'std': 44.252917708519028, 'sum': 15689067 } }, }, '1': { 'bands': { 1: { 'max': 240, 'mean': 102.17252754327959, 'min': 14, 'std': 43.650764099201055, 'sum': 26977532 } }, } } Parameters ---------- vector : <fiona feature collection> Vector datasource. raster : <rasterio RasterReader> Raster datasource. window_band : int, optional Specify which band should supply the read windows are extracted from. Ideally the windows are identical across all bands. custom : dict or None, Supply custom functions as `{'name': func}`. bands : int or list or None, optional Bands to compute stats against. Default is all. Returns ------- dict See 'Example output' above. """ if bands is None: bands = list(range(1, raster.count + 1)) elif isinstance(bands, int): bands = [bands] else: bands = sorted(bands) metrics = { 'min': lambda x: x.min(), 'max': lambda x: x.max(), 'mean': lambda x: x.mean(), 'std': lambda x: x.std(), 'sum': lambda x: x.sum() } if custom is not None: metrics.update(**custom) # Make sure the user gave all callable objects or None for name, func in metrics.items(): if func is not None and not hasattr(func, '__call__'): raise click.ClickException( "Custom function `%s' is not callable: %s" % (name, func)) r_x_min, r_y_min, r_x_max, r_y_max = raster.bounds feature_stats = {} for feature in vector: """ rasterize( shapes, out_shape=None, fill=0, out=None, output=None, transform=Affine(1.0, 0.0, 0.0, 0.0, 1.0, 0.0), all_touched=False, default_value=1, dtype=None ) """ stats = {'bands': {}} reproj_geom = asShape(transform_geom( vector.crs, raster.crs, feature['geometry'], antimeridian_cutting=True)) x_min, y_min, x_max, y_max = reproj_geom.bounds if (r_x_min <= x_min <= x_max <= r_x_max) and (r_y_min <= y_min <= y_max <= r_y_max): stats['contained'] = True else: stats['contained'] = False col_min, row_max = ~raster.affine * (x_min, y_min) col_max, row_min = ~raster.affine * (x_max, y_max) window = ((row_min, row_max), (col_min, col_max)) rasterized = rasterize( shapes=[reproj_geom], out_shape=(row_max - row_min, col_max - col_min), fill=1, transform=raster.window_transform(window), all_touched=all_touched, default_value=0, dtype=rio.ubyte ).astype(np.bool) for bidx in bands: stats['bands'][bidx] = {} data = raster.read(indexes=bidx, window=window, boundless=True, masked=True) # This should be a masked array, but a bug requires us to build our own: # https://github.com/mapbox/rasterio/issues/338 if not isinstance(data, np.ma.MaskedArray): data = np.ma.array(data, mask=data == raster.nodata) data.mask += rasterized for name, func in metrics.items(): if func is not None: stats['bands'][bidx][name] = func(data) feature_stats[feature['id']] = stats return feature_stats
7,179
async def test_flow_all_discovered_bridges_exist(hass, aioclient_mock): """Test config flow discovers only already configured bridges.""" aioclient_mock.get(const.API_NUPNP, json=[ {'internalipaddress': '1.2.3.4', 'id': 'bla'} ]) MockConfigEntry(domain='hue', data={ 'host': '1.2.3.4' }).add_to_hass(hass) flow = config_flow.HueFlowHandler() flow.hass = hass result = await flow.async_step_init() assert result['type'] == 'abort'
7,180
def plot_rna(data_merged, id_cell, framesize=(7, 7), path_output=None, ext="png"): """Plot cytoplasm border and RNA spots. Parameters ---------- data_merged : pandas.DataFrame Dataframe with the coordinate of the cell and those of the RNA. id_cell : int ID of the cell to plot. framesize : tuple Size of the frame used to plot with 'plt.figure(figsize=framesize)'. path_output : str Path to save the image (without extension). ext : str or List[str] Extension used to save the plot. If it is a list of strings, the plot will be saved several times. Returns ------- """ # TODO Sanity check of the dataframe # get cloud points cyto = data_merged.loc[id_cell, "pos_cell"] cyto = np.array(cyto) rna = data_merged.loc[id_cell, "RNA_pos"] rna = np.array(rna) # plot plt.figure(figsize=framesize) plt.plot(cyto[:, 1], cyto[:, 0], c="black", linewidth=2) plt.scatter(rna[:, 1], rna[:, 0], c="firebrick", s=50, marker="x") plt.title("Cell id: {}".format(id_cell), fontweight="bold", fontsize=15) plt.tight_layout() save_plot(path_output, ext) plt.show() return
7,181
def RMSE(stf_mat, stf_mat_max): """error defined as RMSE""" size = stf_mat.shape err = np.power(np.sum(np.power(stf_mat - stf_mat_max, 2.0))/(size[0]*size[1]), 0.5) return err
7,182
def update_efo(): """Update experimental factor ontology.""" url = 'https://www.ebi.ac.uk/efo/efo.obo' OboClient.update_resource(path, url, 'efo', remove_prefix=True, allowed_external_ns={'BFO'})
7,183
def get_read_only_permission_codename(model: str) -> str: """ Create read only permission code name. :param model: model name :type model: str :return: read only permission code name :rtype: str """ return f"{settings.READ_ONLY_ADMIN_PERMISSION_PREFIX}_{model}"
7,184
def hours_to_minutes( hours: str ) -> int: """Converts hours to minutes""" return int(hours)*60
7,185
def RenameNotes(windowID): """ Rename selected notetrack. """ slotIndex = cmds.optionMenu(OBJECT_NAMES[windowID][0]+"_SlotDropDown", query=True, select=True) currentIndex = cmds.textScrollList(OBJECT_NAMES[windowID][0]+"_NoteList", query=True, selectIndexedItem=True) if currentIndex != None and len(currentIndex) > 0 and currentIndex[0] >= 1: if cmds.promptDialog(title="Rename NoteTrack in slot", message="Enter new notetrack name:\t\t ") != "Confirm": return userInput = cmds.promptDialog(query=True, text=True) noteName = "".join([c for c in userInput if c.isalnum() or c=="_"]).replace("sndnt", "sndnt#").replace("rmbnt", "rmbnt#") # Remove all non-alphanumeric characters if noteName == "": MessageBox("Invalid note name") return currentIndex = currentIndex[0] noteList = cmds.getAttr(OBJECT_NAMES[windowID][2]+(".notetracks[%i]" % slotIndex)) or "" notes = noteList.split(",") noteInfo = notes[currentIndex-1].split(":") note = int(noteInfo[1]) NoteTrack = userInput # REMOVE NOTE cmds.textScrollList(OBJECT_NAMES[windowID][0]+"_NoteList", edit=True, removeIndexedItem=currentIndex) noteList = cmds.getAttr(OBJECT_NAMES[windowID][2]+(".notetracks[%i]" % slotIndex)) or "" notes = noteList.split(",") del notes[currentIndex-1] noteList = ",".join(notes) cmds.setAttr(OBJECT_NAMES[windowID][2]+(".notetracks[%i]" % slotIndex), noteList, type='string') # REMOVE NOTE noteList = cmds.getAttr(OBJECT_NAMES[windowID][2]+(".notetracks[%i]" % slotIndex)) or "" noteList += "%s:%i," % (NoteTrack, note) # Add Notes to Aidan's list. cmds.setAttr(OBJECT_NAMES[windowID][2]+(".notetracks[%i]" % slotIndex), noteList, type='string') cmds.textScrollList(OBJECT_NAMES[windowID][0]+"_NoteList", edit=True, append=NoteTrack, selectIndexedItem=currentIndex) SelectNote(windowID)
7,186
def core_profiles_summary(ods, time_index=None, fig=None, combine_dens_temps=True, show_thermal_fast_breakdown=True, show_total_density=True, **kw): """ Plot densities and temperature profiles for electrons and all ion species as per `ods['core_profiles']['profiles_1d'][time_index]` :param ods: input ods :param time_index: time slice to plot :param fig: figure to plot in (a new figure is generated if `fig is None`) :param combine_dens_temps: combine species plot of density and temperatures :param show_thermal_fast_breakdown: bool Show thermal and fast components of density in addition to total if available :param show_total_density: bool Show total thermal+fast in addition to thermal/fast breakdown if available :param kw: arguments passed to matplotlib plot statements :return: figure handler """ from matplotlib import pyplot if fig is None: fig = pyplot.figure() if time_index is None: time_index = numpy.arange(len(ods['core_profiles'].time())) if isinstance(time_index, (list, numpy.ndarray)): time = ods['core_profiles'].time() if len(time) == 1: time_index = time_index[0] else: return ods_time_plot(core_profiles_summary, time, ods, time_index, fig=fig, ax={}, combine_dens_temps=combine_dens_temps, show_thermal_fast_breakdown=show_thermal_fast_breakdown, show_total_density=show_total_density, **kw) axs = kw.pop('ax', {}) prof1d = ods['core_profiles']['profiles_1d'][time_index] x = prof1d['grid.rho_tor_norm'] what = ['electrons'] + ['ion[%d]' % k for k in range(len(prof1d['ion']))] names = ['Electrons'] + [prof1d['ion[%d].label' % k] + ' ion' for k in range(len(prof1d['ion']))] r = len(prof1d['ion']) + 1 ax = ax0 = ax1 = None for k, item in enumerate(what): # densities (thermal and fast) for therm_fast in ['', '_thermal', '_fast']: if (not show_thermal_fast_breakdown) and len(therm_fast): continue # Skip _thermal and _fast because the flag turned these details off if (not show_total_density) and (len(therm_fast) == 0): continue # Skip total thermal+fast because the flag turned it off therm_fast_name = { '': ' (thermal+fast)', '_thermal': ' (thermal)' if show_total_density else '', '_fast': ' (fast)', }[therm_fast] density = item + '.density' + therm_fast # generate axes if combine_dens_temps: if ax0 is None: ax = ax0 = cached_add_subplot(fig, axs, 1, 2, 1) else: ax = ax0 = cached_add_subplot(fig, axs, r, 2, (2 * k) + 1, sharex=ax, sharey=ax0) # plot if data is present if item + '.density' + therm_fast in prof1d: uband(x, prof1d[density], label=names[k] + therm_fast_name, ax=ax0, **kw) if k == len(prof1d['ion']): ax0.set_xlabel('$\\rho$') if k == 0: ax0.set_title('Density [m$^{-3}$]') if not combine_dens_temps: ax0.set_ylabel(names[k]) # add plot of measurements if density + '_fit.measured' in prof1d and density + '_fit.rho_tor_norm' in prof1d: uerrorbar(prof1d[density + '_fit.rho_tor_norm'], prof1d[density + '_fit.measured'], ax=ax) # temperatures if combine_dens_temps: if ax1 is None: ax = ax1 = cached_add_subplot(fig, axs, 1, 2, 2, sharex=ax) else: ax = ax1 = cached_add_subplot(fig, axs, r, 2, (2 * k) + 2, sharex=ax, sharey=ax1) # plot if data is present if item + '.temperature' in prof1d: uband(x, prof1d[item + '.temperature'], label=names[k], ax=ax1, **kw) if k == len(prof1d['ion']): ax1.set_xlabel('$\\rho$') if k == 0: ax1.set_title('Temperature [eV]') # add plot of measurements if item + '.temperature_fit.measured' in prof1d and item + '.temperature_fit.rho_tor_norm' in prof1d: uerrorbar(prof1d[item + '.temperature_fit.rho_tor_norm'], prof1d[item + '.temperature_fit.measured'], ax=ax) ax.set_xlim([0, 1]) if ax0 is not None: ax0.set_ylim([0, ax0.get_ylim()[1]]) if ax1 is not None: ax1.set_ylim([0, ax1.get_ylim()[1]]) return axs
7,187
def migrate_source_attribute(attr, to_this, target_file, regex): """Updates __magic__ attributes in the source file""" change_this = re.compile(regex, re.S) new_file = [] found = False with open(target_file, "r") as fp: lines = fp.readlines() for line in lines: if line.startswith(attr): found = True line = re.sub(change_this, to_this, line) new_file.append(line) if found: with open(target_file, "w") as fp: fp.writelines(new_file)
7,188
def sir_model(): """ this returns a density dependent population process of an SIR model """ ddpp = rmf.DDPP() ddpp.add_transition([-1, 1, 0], lambda x: x[0]+2*x[0]*x[1]) ddpp.add_transition([0, -1, +1], lambda x: x[1]) ddpp.add_transition([1, 0, -1], lambda x: 3*x[2]**3) return ddpp
7,189
def read_cmupd(strip_stress=False, apostrophe="'"): """Read the CMU-Pronunciation Dictionary Parameters ---------- strip_stress : bool Remove stress from pronunciations (default ``False``). apostrophe : str | bool Character to replace apostrophe with in keys (e.g., "COULDN'T"; default is to keep apostrophe; set to ``False`` to split entries with apostrophes into pre- and post-apostrophy components). Returns ------- cmu : dict {str: list of str} Dictionary mapping words (all caps) to lists of pronunciations. """ path = download('http://svn.code.sf.net/p/cmusphinx/code/trunk/cmudict/cmudict-0.7b', 'cmudict-0.7b.txt') out = defaultdict(set) for line in path.open('rb'): m = re.match(rb"^([\w']+)(?:\(\d\))? ([\w ]+)$", line) if m: k, v = m.groups() out[k.decode()].add(v.decode()) # remove apostrophes from keys if apostrophe != "'": keys = [key for key in out if "'" in key] if apostrophe is False: for key in keys: values = out.pop(key) # hard-coded exceptions if key in IGNORE: continue elif key.count("'") > 1: continue elif key in PUNC_WORD_SUB: out[PUNC_WORD_SUB[key]].update(values) continue a_index = key.index("'") # word-initial or -final apostrophy if a_index == 0 or a_index == len(key) - 1: if a_index == 0: key_a = key[1:] else: key_a = key[:-1] out[key_a].update(values) continue # word-medial apostrophy key_a, key_b = key.split("'") for value in values: if key_b in POST_FIXES: if key.endswith("N'T") and value.endswith("N"): value_a = value value_b = None else: value_a, value_b = value.rsplit(' ', 1) assert value_b in POST_FIXES[key_b] elif key_a in PRE_FIXES: value_a, value_b = value.split(' ', 1) assert value_a in PRE_FIXES[key_a] else: raise RuntimeError(" %r," % key) for k, v in ((key_a, value_a), (key_b, value_b)): if v is not None: out[k].add(v) elif isinstance(apostrophe, str): for key in keys: out[key.replace("'", apostrophe)].update(out.pop(key)) else: raise TypeError(f"apostrophe={apostrophe!r}") # remove stress from pronunciations if strip_stress: out = {word: {' '.join(STRIP_STRESS_MAP[p] for p in pronunciation.split()) for pronunciation in pronunciations} for word, pronunciations in out.items()} return out
7,190
def validate(loader, model, logger_test, samples_idx_list, evals_dir): """ Evaluate the model on dataset of the loader """ softmax = torch.nn.Softmax(dim=1) model.eval() # put model to evaluation mode confusion_mtrx_df_val_dmg = pd.DataFrame(columns=['img_idx', 'class', 'true_pos', 'true_neg', 'false_pos', 'false_neg', 'total']) confusion_mtrx_df_val_bld = pd.DataFrame(columns=['img_idx', 'class', 'true_pos', 'true_neg', 'false_pos', 'false_neg', 'total']) confusion_mtrx_df_val_dmg_building_level = pd.DataFrame(columns=['img_idx', 'class', 'true_pos', 'true_neg', 'false_pos', 'false_neg', 'total']) with torch.no_grad(): for img_idx, data in enumerate(tqdm(loader)): # assume batch size is 1 c = data['pre_image'].size()[0] h = data['pre_image'].size()[1] w = data['pre_image'].size()[2] x_pre = data['pre_image'].reshape(1, c, h, w).to(device=device) x_post = data['post_image'].reshape(1, c, h, w).to(device=device) y_seg = data['building_mask'].to(device=device) y_cls = data['damage_mask'].to(device=device) scores = model(x_pre, x_post) # compute accuracy for segmenation model on pre_ images preds_seg_pre = torch.argmax(softmax(scores[0]), dim=1) # modify damage prediction based on UNet arm predictions for c in range(0,scores[2].shape[1]): scores[2][:,c,:,:] = torch.mul(scores[2][:,c,:,:], preds_seg_pre) preds_cls = torch.argmax(softmax(scores[2]), dim=1) path_pred_mask = data['preds_img_dir'] +'.png' logging.info('save png image for damage level predictions: ' + path_pred_mask) im = Image.fromarray(preds_cls.cpu().numpy()[0,:,:].astype(np.uint8)) if not os.path.exists(os.path.split(data['preds_img_dir'])[0]): os.makedirs(os.path.split(data['preds_img_dir'])[0]) im.save(path_pred_mask) logging.info(f'saved image size: {preds_cls.size()}') # compute building-level confusion metrics pred_polygons_and_class, label_polygons_and_class = get_label_and_pred_polygons_for_tile_mask_input(y_cls.cpu().numpy().astype(np.uint8), path_pred_mask) results, list_preds, list_labels = _evaluate_tile(pred_polygons_and_class, label_polygons_and_class, allowed_classes, 0.1) total_objects = results[-1] for label_class in results: if label_class != -1: true_pos_cls = results[label_class]['tp'] if 'tp' in results[label_class].keys() else 0 true_neg_cls = results[label_class]['tn'] if 'tn' in results[label_class].keys() else 0 false_pos_cls = results[label_class]['fp'] if 'fp' in results[label_class].keys() else 0 false_neg_cls = results[label_class]['fn'] if 'fn' in results[label_class].keys() else 0 confusion_mtrx_df_val_dmg_building_level = confusion_mtrx_df_val_dmg_building_level.append({'img_idx':img_idx, 'class':label_class, 'true_pos':true_pos_cls, 'true_neg':true_neg_cls, 'false_pos':false_pos_cls, 'false_neg':false_neg_cls, 'total':total_objects}, ignore_index=True) # compute comprehensive pixel-level comfusion metrics confusion_mtrx_df_val_dmg = compute_confusion_mtrx(confusion_mtrx_df_val_dmg, img_idx, labels_set_dmg, preds_cls, y_cls, y_seg) confusion_mtrx_df_val_bld = compute_confusion_mtrx(confusion_mtrx_df_val_bld, img_idx, labels_set_bld, preds_seg_pre, y_seg, []) # add viz results to logger if img_idx in samples_idx_list: prepare_for_vis(img_idx, logger_test, model, device, softmax) return confusion_mtrx_df_val_dmg, confusion_mtrx_df_val_bld, confusion_mtrx_df_val_dmg_building_level
7,191
def my_eval(inputstring, seq, xvalues=None, yvalues=None): """ Evaluate a string as an expression to make a data set. This routine attempts to evaluate a string as an expression. It uses the python "eval" function. To guard against bad inputs, only numpy, math and builtin functions can be used in the transformation. Parameters ---------- inputstring a string that defines the new data set seq : a numpy vector of floating point or integer values, nominally a sequence of values when the data creation option is used, which could be another numpy array in the transformation case xvalues : optionally, the x data values in a set, a numpy floating point vector yvalues : optionally, the y data values in a set, a numpy floating point vector Returns ------- values : a new numpy vector of floating point values calculated from the input numpy arrays and the string defining the function; or None if there is an issue Note: the three numpy arrays "seq", "xvalues", and "yvalues" need to be one dimensional and of the same lengths The python "eval" command is used here. To avoid issues with this being used to run arbitrary commands, only the __builtin__, math, and numpy packages are available to the eval command upon execution. The assumption is that math and numpy have been imported in the main code (and that numpy is not abbreviated as "np" at import). """ sh1 = seq.shape try: sh2 = xvalues.shape except AttributeError: sh2 = seq.shape try: sh3 = yvalues.shape except AttributeError: sh3 = seq.shape if (sh1 != sh2) or (sh2 != sh3) or (len(sh1) > 1): return None # check the input string for command elements that could cause issues if ('import' in inputstring) or ('os.' in inputstring) or \ ('eval' in inputstring) or ('exec' in inputstring) or \ ('shutil' in inputstring): return None str1 = inputstring.replace('np.', 'numpy.') try: # get the global environment, extract the three items allowed here global1 = globals() global2 = {} global2['__builtins__'] = global1['__builtins__'] global2['math'] = global1['math'] global2['numpy'] = global1['numpy'] # define local variables, s, x, and y; only these will be # available in eval if they are actually defined in the call.... local1 = {} s = numpy.copy(seq) local1['seq'] = s if xvalues is not None: x = numpy.copy(xvalues) local1['x'] = x if yvalues is not None: y = numpy.copy(yvalues) local1['y'] = y values = eval(str1, global2, local1) return values except Exception: return None
7,192
def readlines(filepath): """ read lines from a textfile :param filepath: :return: list[line] """ with open(filepath, 'rt') as f: lines = f.readlines() lines = map(str.strip, lines) lines = [l for l in lines if l] return lines
7,193
def process_images(): """ TODO """ return downloader(request.args.get('img_url'))
7,194
def batch_lambda_handler(event, lambda_context): """Entry point for the batch Lambda function. Args: event: [dict] Invocation event. If 'S3ContinuationToken' is one of the keys, the S3 bucket will be enumerated beginning with that continuation token. lambda_context: [LambdaContext] object with .get_remaining_time_in_millis(). Returns: [int] The number of enumerated S3 keys. """ LOGGER.info('Invoked with event %s', json.dumps(event)) s3_enumerator = S3BucketEnumerator( os.environ['S3_BUCKET_NAME'], event.get('S3ContinuationToken')) sqs_batcher = SQSBatcher(os.environ['SQS_QUEUE_URL'], int(os.environ['OBJECTS_PER_MESSAGE'])) # As long as there are at least 10 seconds remaining, enumerate S3 objects into SQS. num_keys = 0 while lambda_context.get_remaining_time_in_millis() > 10000 and not s3_enumerator.finished: keys = s3_enumerator.next_page() num_keys += len(keys) for key in keys: sqs_batcher.add_key(key) # Send the last batch of keys. sqs_batcher.finalize() # If the enumerator has not yet finished but we're low on time, invoke this function again. if not s3_enumerator.finished: LOGGER.info('Invoking another batcher') LAMBDA_CLIENT.invoke( FunctionName=os.environ['BATCH_LAMBDA_NAME'], InvocationType='Event', # Asynchronous invocation. Payload=json.dumps({'S3ContinuationToken': s3_enumerator.continuation_token}), Qualifier=os.environ['BATCH_LAMBDA_QUALIFIER'] ) return num_keys
7,195
def get_gpu_memory_map(): """Get the current gpu usage. Returns ------- usage: dict Keys are device ids as integers. Values are memory usage as integers in MB. """ result = subprocess.check_output( [ 'nvidia-smi', '--query-gpu=memory.free', '--format=csv,nounits,noheader' ]) # Convert lines into a dictionary gpu_memory = [int(x) for x in result.strip().split(b'\n')] gpu_memory_map = dict(zip(range(len(gpu_memory)), gpu_memory)) return gpu_memory_map
7,196
def n_tuple(n): """Factory for n-tuples.""" def custom_tuple(data): if len(data) != n: raise TypeError( f'{n}-tuple requires exactly {n} items ' f'({len(data)} received).' ) return tuple(data) return custom_tuple
7,197
def test_silhouette(): """ Testing silhouette score, using make_clusters and corresponding labels to test error bounds. """ clusters, labels = make_clusters(scale=0.2, n=500) # start ss = Silhouette() # get scores for each clabel in clusters get_scores =ss.score(clusters, labels) # check bounds assert get_scores.all() >= -1 and get_scores.all() <= 1
7,198
def novel_normalization(data, base): """Initial data preparation of CLASSIX.""" if base == "norm-mean": # self._mu, self._std = data.mean(axis=0), data.std() _mu = data.mean(axis=0) ndata = data - _mu _scl = ndata.std() ndata = ndata / _scl elif base == "pca": _mu = data.mean(axis=0) ndata = data - _mu # mean center rds = norm(ndata, axis=1) # distance of each data point from 0 _scl = np.median(rds) # 50% of data points are within that radius ndata = ndata / _scl # now 50% of data are in unit ball elif base == "norm-orthant": # self._mu, self._std = data.min(axis=0), data.std() _mu = data.min(axis=0) ndata = data - _mu _scl = ndata.std() ndata = ndata / _scl else: # self._mu, self._std = data.mean(axis=0), data.std(axis=0) # z-score _mu, _scl = 0, 1 # no normalization ndata = (data - _mu) / _scl return ndata, (_mu, _scl)
7,199