content
stringlengths
22
815k
id
int64
0
4.91M
def email_manage(request, email_pk, action): """Set the requested email address as the primary. Can only be requested by the owner of the email address.""" email_address = get_object_or_404(EmailAddress, pk=email_pk) if not email_address.user == request.user and not request.user.is_staff: messages.error(request, "You are not authorized to manage this email address") # if not email_address.is_verified(): # messages.error(request, "Email '%s' needs to be verified first." % email_address.email) if action == "set_primary": email_address.set_primary() messages.success(request, "'%s' is now marked as your primary email address." % email_address.email) elif action == "delete": email_address.delete() messages.success(request, "'%s' has been removed." % email_address.email) if 'HTTP_REFERER' in request.META: return redirect(request.META['HTTP_REFERER']) else: return redirect(reverse('member:profile:view', kwargs={'username': email_address.user.username}))
5,345,700
def get_container_service_api_version(): """Get zun-api-version with format: 'container X.Y'""" return 'container ' + CONTAINER_SERVICE_MICROVERSION
5,345,701
def prepare_config(config_path=None, schema_path=None, config=None, schema=None, base_path=None) -> Munch: """ Takes in paths to config and schema files. Validates the config against the schema, normalizes the config, parses gin and converts the config to a Munch. """ # Load up the config if config is None: assert config_path is not None, 'Please pass in either config or config_path.' assert config_path.endswith('.yaml'), 'Must use a YAML file for the config.' config = yaml.load(open(config_path), Loader=yaml.FullLoader) # If the config is a Quinfig object, just grab the __dict__ for convenience if isinstance(config, Quinfig): config = config.__dict__ # Convert config to Munch: iffy ensures that the Munch fn is only applied to mappings config = walk_values_rec(iffy(is_mapping, lambda c: Munch(**c)), config) # Load up the schema if schema is None: if schema_path is not None: assert schema_path.endswith('.yaml'), 'Must use a YAML file for the config.' schema = yaml.load(open(schema_path), Loader=yaml.FullLoader) if schema is not None: # Allow gin configuration at any level of nesting: put a gin tag at every level of the schema schema = autoexpand_schema(schema) # Validate the config against the schema validate_config(config, schema) # Normalize the config if not base_path: base_path = os.path.dirname(os.path.abspath(config_path)) if config_path else '' else: base_path = os.path.abspath(base_path) config = normalize_config(config, schema, base_path=base_path) # Convert config to Munch: iffy ensures that the Munch fn is only applied to mappings config = walk_values_rec(iffy(is_mapping, lambda c: Munch(**c)), config) # Parse and load the gin configuration nested_gin_dict_parser(config) return config
5,345,702
def setup_tab_complete() -> None: """Set up the readline library to hook into our command completer""" readline.set_completer_delims("") if sys.platform != "win32": readline.set_completion_display_matches_hook(completer.match_command_hook) readline.set_completer(completer.CommandCompleter(commands.COMMAND_REGISTRY).completer) readline.parse_and_bind("tab: complete") readline.parse_and_bind("set show-all-if-ambiguous on") readline.parse_and_bind("set bell-style none")
5,345,703
def invalidate_view_cache(view_name, args=[], namespace=None, key_prefix=None): """ This function allows you to invalidate any view-level cache. view_name: view function you wish to invalidate or it's named url pattern args: any arguments passed to the view function namepace: if an application namespace is used, pass that key prefix: for the @cache_page decorator for the function (if any) """ from django.utils.cache import get_cache_key from django.core.cache import cache # create a fake request object request = HttpRequest() # Loookup the request path: if namespace: view_name = namespace + ":" + view_name request.path = reverse(view_name, args=args) # get cache key, expire if the cached item exists: key = get_cache_key(request, key_prefix=key_prefix) if key: if cache.get(key): cache.set(key, None, 0) return True return False
5,345,704
def compute_ray_features_segm_2d(seg_binary, position, angle_step=5., smooth_coef=0, edge='up'): """ compute ray features vector , shift them to be starting from larges and smooth_coef them by gauss filter (from given point the close distance to boundary) :param ndarray seg_binary: np.array<height, width> :param tuple(int,int) position: integer position in the segmentation :param float angle_step: angular step for ray features :param str edge: pointing to the up of down edge of an boundary :param int smooth_coef: smoothing the final ray features :return list(float): ray distances .. seealso:: :func:`imsegm.descriptors.compute_ray_features_segm_2d_vectors` .. note:: for more examples, see unittests >>> seg_empty = np.zeros((100, 150), dtype=bool) >>> compute_ray_features_segm_2d(seg_empty, (50, 75), 90) # doctest: +ELLIPSIS array([-1., -1., -1., -1.]...) >>> from skimage import draw >>> seg = np.ones((100, 150), dtype=bool) >>> x, y = draw.circle(50, 75, 40, shape=seg.shape) >>> seg[x, y] = False >>> np.round(compute_ray_features_segm_2d(seg, (50, 75), 45)) # doctest: +ELLIPSIS array([ 40., 41., 40., 41., 40., 41., 40., 41.]...) >>> np.round(compute_ray_features_segm_2d(seg, (60, 40), 30, smooth_coef=1)).tolist() [66.0, 52.0, 32.0, 16.0, 8.0, 5.0, 5.0, 8.0, 16.0, 33.0, 53.0, 67.0] >>> ray_fts = compute_ray_features_segm_2d(seg, (40, 60), 20) >>> np.round(ray_fts).tolist() # doctest: +NORMALIZE_WHITESPACE [54.0, 57.0, 59.0, 55.0, 51.0, 44.0, 38.0, 31.0, 27.0, 24.0, 22.0, 22.0, 23.0, 26.0, 29.0, 35.0, 42.0, 49.0] """ assert seg_binary.ndim == len(position), \ 'Segmentation dim of %r and position (%i) does not match' \ % (seg_binary.ndim, len(position)) seg_binary = seg_binary.astype(bool) position = tuple(map(int, position)) fn_compute = cython_ray_features_seg2d if USE_CYTHON else numpy_ray_features_seg2d ray_dist = fn_compute(seg_binary, position, angle_step, edge) if smooth_coef is not None and smooth_coef > 0: ray_dist = gaussian_filter1d(ray_dist, smooth_coef) return ray_dist
5,345,705
def test_bind_physical_segment_without_hpb_conflict( f5_mech_driver, context, agent_hpb_bridge_mappings, vlan_segment): """Test the proper behaviour when a HPB segment physical name is configured The HPB configuration item is in the agent config but the physical network name is different from any of the bridge mapping networks. Pass if no binding is performed, we are not binding HPB ports at this time to avoid conflict with the HPB mechanism driver. """ retval = f5_mech_driver.try_to_bind_segment_for_agent( context, vlan_segment, agent_hpb_bridge_mappings) assert retval context.set_binding.assert_called_with('seg-uuid', 'other', {})
5,345,706
def visualize_bbox(img, bbox, class_name, color=(255, 0, 0) , thickness=2): """Visualizes a single bounding box on the image""" BOX_COLOR = (255, 0, 0) # Red TEXT_COLOR = (255, 255, 255) # White x_min, y_min, x_max, y_max = bbox cv2.rectangle(img, (x_min, y_min), (x_max, y_max), color=color, thickness=thickness) ((text_width, text_height), _) = cv2.getTextSize(class_name, cv2.FONT_HERSHEY_SIMPLEX, 0.35, 1) cv2.rectangle(img, (x_min, y_min - int(1.3 * text_height)), (x_min + text_width, y_min), BOX_COLOR, -1) cv2.putText( img, text=class_name, org=(x_min, y_min - int(0.3 * text_height)), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.35, color=TEXT_COLOR, lineType=cv2.LINE_AA, ) return img
5,345,707
def mock_light(): """Mock UniFi Protect Camera device.""" data = json.loads(load_fixture("sample_light.json", integration=DOMAIN)) return Light.from_unifi_dict(**data)
5,345,708
def randomize_bulge_i(N, M, bp='G', target='none', ligand='theo'): """ Replace the upper stem with the aptamer and randomize the bulge to connect it to the lower stem. This is a variant of the rb library with two small differences. First, the nucleotides flanking the aptamer are not randomized and are instead guaranteed to base pair. The default base pair is GC. However, note that to be consistent with rb, this base pair is considered part of the linker, and is included in the N and M arguments. So rbi/4/8 only randomizes 10 positions. Second, the library is based off the Dang scaffold. Most extended upper stem is replaced with the aptamer, but the CG base pair in the lower stem remains. Parameters ---------- N: int The length of the linker on the 5' side of the aptamer. This length includes a non-randomized base pair immediately adjacent to the aptamer. M: int The length of the linker on the 3' side of the aptamer. This length includes a non-randomized base pair immediately adjacent to the aptamer. bp: 'ACGU' Not implemented, but this would be a good interface for changing the static base pair. Right now to base pair is hard-coded to be GC. """ sgrna = on(target=target) sgrna['bulge/5'].attachment_sites = 0, sgrna['bulge/3'].attachment_sites = 4, sgrna.attach( random_insert(ligand, N, M, flags='g'), 'bulge/5', 0, 'bulge/3', 4, ) return sgrna
5,345,709
def JSparser(contents: str) -> str: """ Is supposed to replace URLs in JS. Arguments: contents: JS string Returns: Input JS string """ # TODO: URL replacement return contents
5,345,710
def refolder(data_folder, targ_folder, train_fraction=0.8, val_fraction=0.2, test_fraction=0.0, remove_original=False): """ Rearranging files under source folder (data_folder) with class subfolders into train/val/test folders under target fold (targ_folder) Arguments: """ r=data_folder classes=[f for f in os.listdir(r) if os.path.isdir(os.path.join(r,f))] print('1 step') if os.path.isdir(targ_folder): shutil.rmtree(targ_folder) os.mkdir(targ_folder) print('step 2') sub_folder=os.path.join(targ_folder, 'train') os.mkdir(sub_folder) for c in classes: os.mkdir(os.path.join(sub_folder,c)) sub_folder=os.path.join(targ_folder, 'val') os.mkdir(sub_folder) for c in classes: os.mkdir(os.path.join(sub_folder,c)) if test_fraction!=0: sub_folder=os.path.join(targ_folder, 'test') os.mkdir(sub_folder) for c in classes: os.mkdir(os.path.join(sub_folder,c)) for c in classes: files=glob.glob(os.path.join(r,c,"*")) random.shuffle(files) train_n=int(len(files)*train_fraction) for f in files[:train_n]: filename = os.path.basename(f) copyfile(f, os.path.join(targ_folder,'train', c,filename)) if test_fraction==0: for f in files[train_n:]: filename = os.path.basename(f) copyfile(f, os.path.join(targ_folder,'val', c,filename)) elif test_fraction!=0: val_n=int(len(files)*val_fraction) for f in files[train_n:(train_n+val_n)]: filename = os.path.basename(f) copyfile(f, os.path.join(targ_folder,'val', c,filename)) for f in files[(train_n+val_n):]: filename = os.path.basename(f) copyfile(f, os.path.join(targ_folder,'test', c,filename)) if remove_original==True: shutil.rmtree(data_folder)
5,345,711
def parse_identifier(db, identifier): """Parse the identifier and return an Identifier object representing it. :param db: Database session :type db: sqlalchemy.orm.session.Session :param identifier: String containing the identifier :type identifier: str :return: Identifier object :rtype: Optional[core.model.identifier.Identifier] """ parsed_identifier = None try: result = Identifier.parse_urn(db, identifier) if result is not None: parsed_identifier, _ = result except Exception: logging.error( f"An unexpected exception occurred during parsing identifier {identifier}" ) return parsed_identifier
5,345,712
def wrap_name(dirname, figsize): """Wrap name to fit in subfig.""" fontsize = plt.rcParams["font.size"] # 1/120 = inches/(fontsize*character) num_chars = int(figsize / fontsize * 72) return textwrap.fill(dirname, num_chars)
5,345,713
def resolve_shape(tensor, rank=None, scope=None): """Fully resolves the shape of a Tensor. Use as much as possible the shape components already known during graph creation and resolve the remaining ones during runtime. Args: tensor: Input tensor whose shape we query. rank: The rank of the tensor, provided that we know it. scope: Optional name scope. Returns: shape: The full shape of the tensor. """ with tf.name_scope(scope, 'resolve_shape', [tensor]): if rank is not None: shape = tensor.get_shape().with_rank(rank).as_list() else: shape = tensor.get_shape().as_list() if None in shape: shape_dynamic = tf.shape(tensor) for i in range(len(shape)): if shape[i] is None: shape[i] = shape_dynamic[i] return shape
5,345,714
def gradient_clip(gradients, max_gradient_norm): """Clipping gradients of a model.""" clipped_gradients, gradient_norm = tf.clip_by_global_norm( gradients, max_gradient_norm) gradient_norm_summary = [tf.summary.scalar("grad_norm", gradient_norm)] gradient_norm_summary.append( tf.summary.scalar("clipped_gradient", tf.global_norm(clipped_gradients))) return clipped_gradients, gradient_norm_summary
5,345,715
def get_sha_from_ref(repo_url, reference): """ Returns the sha corresponding to the reference for a repo :param repo_url: location of the git repository :param reference: reference of the branch :returns: utf-8 encoded string of the SHA found by the git command """ # Using subprocess instead of convoluted git libraries. # Any rc != 0 will be throwing an exception, so we don't have to care out = subprocess.check_output( ["git", "ls-remote", "--exit-code", repo_url, reference] ) # out is a b'' type string always finishing up with a newline # construct list of (ref,sha) refs = [ (line.split(b"\t")[1], line.split(b"\t")[0]) for line in out.split(b"\n") if line != b"" and b"^{}" not in line ] if len(refs) > 1: raise ValueError( "More than one ref for reference %s, please be more explicit %s" % (reference, refs) ) return refs[0][1].decode("utf-8")
5,345,716
def test_cross_entropy(): """ Test cross_entropy. """ cross_entropy = CrossEntropy() loc = Tensor([1.0], dtype=dtype.float32) scale = Tensor([1.0], dtype=dtype.float32) diff = cross_entropy(loc, scale) tol = 1e-6 assert (np.abs(diff.asnumpy() - np.zeros(diff.shape)) < tol).all()
5,345,717
def list_species(category_id): """ List all the species for the specified category :return: A list of Species instances """ with Session.begin() as session: species = session.query(Species)\ .filter(Species.categoryId == category_id)\ .order_by(db.asc(Species.name))\ .all() return species
5,345,718
def shut_down_thread_pool(): """Shuts down the thread pool.""" logger.info('Shutting down thread pool...') _executor.shutdown()
5,345,719
def test_state_is_immutable(subject: StateStore) -> None: """It should treat the state as immutable.""" result_1 = subject.state subject.handle_action(PlayAction()) result_2 = subject.state assert result_1 is not result_2
5,345,720
def get_motif_proteins(meme_db_file): """ Hash motif_id's to protein names using the MEME DB file """ motif_protein = {} for line in open(meme_db_file): a = line.split() if len(a) > 0 and a[0] == 'MOTIF': if a[2][0] == '(': motif_protein[a[1]] = a[2][1:a[2].find(')')] else: motif_protein[a[1]] = a[2] return motif_protein
5,345,721
def get_files(search_glob): """ Returns all files matching |search_glob|. """ recursive_glob = '**' + os.path.sep if recursive_glob in search_glob: if sys.version_info >= (3, 5): result = iglob(search_glob, recursive=True) else: # Polyfill for recursive glob pattern matching added in Python 3.5. result = get_files_recursive(*search_glob.split(recursive_glob)) else: result = iglob(search_glob) # Sort the result for consistency across platforms. return sorted(result)
5,345,722
def test_cloud(credential, Cloud): # noqa: N803 """ Test cloud. Test cloud """ assert(credential.username == '[email protected]') assert(credential.password == 'test_password') cloud = Cloud(credential.username, credential.password) assert(cloud)
5,345,723
def main(): # pragma: no cover """ A wrapper for the program entrypoint that formats uncaught exceptions in a crash report template. """ if IS_DEBUG: # allow exceptions to raised when debugging run() else: # wrap exceptions in crash report under normal operation try: run() except SystemExit: raise except: tty.crash_report()
5,345,724
def pixellate_bboxes(im, bboxes, cell_size=(5,6), expand_per=0.0): """Pixellates ROI using Nearest Neighbor inerpolation :param im: (numpy.ndarray) image BGR :param bbox: (BBox) :param cell_size: (int, int) pixellated cell size :returns (numpy.ndarray) BGR image """ if not bboxes: return im elif not type(bboxes) == list: bboxes = list(bboxes) for bbox in bboxes: if expand_per > 0: bbox = bbox.expand_per(expand_per) x1,y1,x2,y2 = bbox.xyxy_int im_roi = im[y1:y2, x1:x2] h,w,c = im_roi.shape # pixellate im_roi = cv.resize(im_roi, cell_size, interpolation=cv.INTER_NEAREST) im_roi = cv.resize(im_roi, (w,h), interpolation=cv.INTER_NEAREST) im[y1:y2, x1:x2] = im_roi return im
5,345,725
def clear_cache(raw_keys: list, user_id: int = None) -> None: """ Remove cache records relevant to handled keys. Parameters ---------- raw_keys: Cache keys. user_id: User id. """ for key in raw_keys: remove_cache_record(key, user_id)
5,345,726
def rename_windows_service_display(install_id: str) -> None: """Changes the name of the service displayed in services.msc.""" print(f'sc config GlassFish_{install_id} DisplayName = "GlassFish ID_{install_id}"') subprocess.call(f'sc config GlassFish_{install_id} DisplayName= "GlassFish_ID_{install_id}"', shell=True)
5,345,727
def run_local(ctx, limit: float, **kwargs): """Runs benchmarks locally.""" run(ctx, machine_producer.LocalMachineProducer(limit=limit), **kwargs)
5,345,728
def in_ipython() -> bool: """try to detect whether we are in an ipython shell, e.g., a jupyter notebook""" ipy_module = sys.modules.get("IPython") if ipy_module: return bool(ipy_module.get_ipython()) else: return False
5,345,729
def StepToGeom_MakeHyperbola2d_Convert(*args): """ :param SC: :type SC: Handle_StepGeom_Hyperbola & :param CC: :type CC: Handle_Geom2d_Hyperbola & :rtype: bool """ return _StepToGeom.StepToGeom_MakeHyperbola2d_Convert(*args)
5,345,730
def create_dict(local=None, field=None, **kwargs): """ 以字典的形式从局部变量locals()中获取指定的变量 :param local: dict :param field: str[] 指定需要从local中读取的变量名称 :param kwargs: 需要将变量指定额外名称时使用 :return: dict """ if field is None or local is None: return {} result = {k: v for k, v in local.items() if k in field} result.update(**kwargs) return result
5,345,731
def sum_list_for_datalist(list): """ DB에 저장할 때, 기준일로부터 과거 데이터가 존재하지 않을 경우에는 0을 return 한다. :param list: :return: float or int """ mysum = 0 for i in range(0, len(list)): if list[i] == 0: return 0 mysum = mysum + list[i] return mysum
5,345,732
def elu(x, alpha=1.): """Exponential linear unit. Arguments: x {tensor} -- Input float tensor to perform activation. alpha {float} -- A scalar, slope of negative section. Returns: tensor -- Output of exponential linear activation """ return x * (x > 0) + alpha * (tf.math.exp(x) - 1.) * (x < 0)
5,345,733
def coalesce(*args): """ Compute the first non-null value(s) from the passed arguments in left-to-right order. This is also known as "combine_first" in pandas. Parameters ---------- *args : variable-length value list Examples -------- >>> import ibis >>> expr1 = None >>> expr2 = 4 >>> result = ibis.coalesce(expr1, expr2, 5) Returns ------- coalesced : type of first provided argument """ return ops.Coalesce(args).to_expr()
5,345,734
def get_analysis(poem, operations, rhyme_analysis=False, alternative_output=False): """ View for /analysis that perform an analysis of poem running the different operations on it. :param poem: A UTF-8 encoded byte string with the text of the poem :param operations: List of strings with the operations to be performed: - "scansion": Performs scansion analysis - "enjambment": Performs enjambment detection :param rhyme_analysis: Whether or not rhyme analysis is to be performed :return: Response object with a dict with a key for each operation and its analysis or a serialized version of it """ analysis = analyze(poem.decode('utf-8'), operations, rhyme_analysis, alternative_output) mime = connexion.request.headers.get("Accept") # serialization = serialize(analysis, mime) return Response(json.dumps(analysis), mimetype=mime)
5,345,735
def export( ctx, cli_obj, db, photos_library, keyword, person, album, folder, uuid, uuid_from_file, title, no_title, description, no_description, uti, ignore_case, edited, external_edit, favorite, not_favorite, hidden, not_hidden, shared, not_shared, from_date, to_date, verbose_, update, dry_run, export_as_hardlink, touch_file, overwrite, export_by_date, skip_edited, skip_bursts, skip_live, skip_raw, person_keyword, album_keyword, keyword_template, description_template, current_name, sidecar, only_photos, only_movies, burst, not_burst, live, not_live, download_missing, dest, exiftool, portrait, not_portrait, screenshot, not_screenshot, slow_mo, not_slow_mo, time_lapse, not_time_lapse, hdr, not_hdr, selfie, not_selfie, panorama, not_panorama, has_raw, directory, filename_template, edited_suffix, place, no_place, no_extended_attributes, label, deleted, deleted_only, ): """ Export photos from the Photos database. Export path DEST is required. Optionally, query the Photos database using 1 or more search options; if more than one option is provided, they are treated as "AND" (e.g. search for photos matching all options). If no query options are provided, all photos will be exported. By default, all versions of all photos will be exported including edited versions, live photo movies, burst photos, and associated RAW images. See --skip-edited, --skip-live, --skip-bursts, and --skip-raw options to modify this behavior. """ global VERBOSE VERBOSE = True if verbose_ else False if not os.path.isdir(dest): sys.exit(f"DEST {dest} must be valid path") # sanity check input args exclusive = [ (favorite, not_favorite), (hidden, not_hidden), (any(title), no_title), (any(description), no_description), (only_photos, only_movies), (burst, not_burst), (live, not_live), (portrait, not_portrait), (screenshot, not_screenshot), (slow_mo, not_slow_mo), (time_lapse, not_time_lapse), (hdr, not_hdr), (selfie, not_selfie), (panorama, not_panorama), (export_by_date, directory), (export_as_hardlink, exiftool), (any(place), no_place), (deleted, deleted_only), ] if any(all(bb) for bb in exclusive): click.echo("Incompatible export options", err=True) click.echo(cli.commands["export"].get_help(ctx), err=True) return # initialize export flags # by default, will export all versions of photos unless skip flag is set (export_edited, export_bursts, export_live, export_raw) = [ not x for x in [skip_edited, skip_bursts, skip_live, skip_raw] ] # verify exiftool installed an in path if exiftool: try: _ = get_exiftool_path() except FileNotFoundError: click.echo( "Could not find exiftool. Please download and install" " from https://exiftool.org/", err=True, ) ctx.exit(2) isphoto = ismovie = True # default searches for everything if only_movies: isphoto = False if only_photos: ismovie = False # load UUIDs if necessary and append to any uuids passed with --uuid if uuid_from_file: uuid_list = list(uuid) # Click option is a tuple uuid_list.extend(load_uuid_from_file(uuid_from_file)) uuid = tuple(uuid_list) # below needed for to make CliRunner work for testing cli_db = cli_obj.db if cli_obj is not None else None db = get_photos_db(*photos_library, db, cli_db) if db is None: click.echo(cli.commands["export"].get_help(ctx), err=True) click.echo("\n\nLocated the following Photos library databases: ", err=True) _list_libraries() return # open export database and assign copy/link/unlink functions export_db_path = os.path.join(dest, OSXPHOTOS_EXPORT_DB) # check that export isn't in the parent or child of a previously exported library other_db_files = find_files_in_branch(dest, OSXPHOTOS_EXPORT_DB) if other_db_files: click.echo( "WARNING: found other export database files in this destination directory branch. " + "This likely means you are attempting to export files into a directory " + "that is either the parent or a child directory of a previous export. " + "Proceeding may cause your exported files to be overwritten.", err=True, ) click.echo( f"You are exporting to {dest}, found {OSXPHOTOS_EXPORT_DB} files in:" ) for other_db in other_db_files: click.echo(f"{other_db}") click.confirm("Do you want to continue?", abort=True) if dry_run: export_db = ExportDBInMemory(export_db_path) # echo = functools.partial(click.echo, err=True) # fileutil = FileUtilNoOp(verbose=echo) fileutil = FileUtilNoOp else: export_db = ExportDB(export_db_path) fileutil = FileUtil photos = _query( db=db, keyword=keyword, person=person, album=album, folder=folder, uuid=uuid, title=title, no_title=no_title, description=description, no_description=no_description, ignore_case=ignore_case, edited=edited, external_edit=external_edit, favorite=favorite, not_favorite=not_favorite, hidden=hidden, not_hidden=not_hidden, missing=None, # missing -- won't export these but will warn user not_missing=None, shared=shared, not_shared=not_shared, isphoto=isphoto, ismovie=ismovie, uti=uti, burst=burst, not_burst=not_burst, live=live, not_live=not_live, cloudasset=False, not_cloudasset=False, incloud=False, not_incloud=False, from_date=from_date, to_date=to_date, portrait=portrait, not_portrait=not_portrait, screenshot=screenshot, not_screenshot=not_screenshot, slow_mo=slow_mo, not_slow_mo=not_slow_mo, time_lapse=time_lapse, not_time_lapse=not_time_lapse, hdr=hdr, not_hdr=not_hdr, selfie=selfie, not_selfie=not_selfie, panorama=panorama, not_panorama=not_panorama, has_raw=has_raw, place=place, no_place=no_place, label=label, deleted=deleted, deleted_only=deleted_only, ) results_exported = [] if photos: if export_bursts: # add the burst_photos to the export set photos_burst = [p for p in photos if p.burst] for burst in photos_burst: burst_set = [p for p in burst.burst_photos if not p.ismissing] photos.extend(burst_set) num_photos = len(photos) # TODO: photos or photo appears several times, pull into a separate function photo_str = "photos" if num_photos > 1 else "photo" click.echo(f"Exporting {num_photos} {photo_str} to {dest}...") start_time = time.perf_counter() # though the command line option is current_name, internally all processing # logic uses original_name which is the boolean inverse of current_name # because the original code used --original-name as an option original_name = not current_name results_new = [] results_updated = [] results_skipped = [] results_exif_updated = [] if verbose_: for p in photos: results = export_photo( photo=p, dest=dest, verbose_=verbose_, export_by_date=export_by_date, sidecar=sidecar, update=update, export_as_hardlink=export_as_hardlink, overwrite=overwrite, export_edited=export_edited, original_name=original_name, export_live=export_live, download_missing=download_missing, exiftool=exiftool, directory=directory, filename_template=filename_template, no_extended_attributes=no_extended_attributes, export_raw=export_raw, album_keyword=album_keyword, person_keyword=person_keyword, keyword_template=keyword_template, description_template=description_template, export_db=export_db, fileutil=fileutil, dry_run=dry_run, touch_file=touch_file, edited_suffix=edited_suffix, ) results_exported.extend(results.exported) results_new.extend(results.new) results_updated.extend(results.updated) results_skipped.extend(results.skipped) results_exif_updated.extend(results.exif_updated) else: # show progress bar with click.progressbar(photos) as bar: for p in bar: results = export_photo( photo=p, dest=dest, verbose_=verbose_, export_by_date=export_by_date, sidecar=sidecar, update=update, export_as_hardlink=export_as_hardlink, overwrite=overwrite, export_edited=export_edited, original_name=original_name, export_live=export_live, download_missing=download_missing, exiftool=exiftool, directory=directory, filename_template=filename_template, no_extended_attributes=no_extended_attributes, export_raw=export_raw, album_keyword=album_keyword, person_keyword=person_keyword, keyword_template=keyword_template, description_template=description_template, export_db=export_db, fileutil=fileutil, dry_run=dry_run, touch_file=touch_file, edited_suffix=edited_suffix, ) results_exported.extend(results.exported) results_new.extend(results.new) results_updated.extend(results.updated) results_skipped.extend(results.skipped) results_exif_updated.extend(results.exif_updated) stop_time = time.perf_counter() # print summary results if update: photo_str_new = "photos" if len(results_new) != 1 else "photo" photo_str_updated = "photos" if len(results_new) != 1 else "photo" photo_str_skipped = "photos" if len(results_skipped) != 1 else "photo" photo_str_exif_updated = ( "photos" if len(results_exif_updated) != 1 else "photo" ) click.echo( f"Exported: {len(results_new)} {photo_str_new}, " + f"updated: {len(results_updated)} {photo_str_updated}, " + f"skipped: {len(results_skipped)} {photo_str_skipped}, " + f"updated EXIF data: {len(results_exif_updated)} {photo_str_exif_updated}" ) else: photo_str = "photos" if len(results_exported) != 1 else "photo" click.echo(f"Exported: {len(results_exported)} {photo_str}") click.echo(f"Elapsed time: {(stop_time-start_time):.3f} seconds") else: click.echo("Did not find any photos to export") export_db.close()
5,345,736
def main(): """Main method to run with GUI""" global projectpath gui = GUI() gui.mainloop() projectpath = ""
5,345,737
def UpdateRC(bash_completion, path_update, rc_path, bin_path, sdk_root): """Update the system path to include bin_path. Args: bash_completion: bool, Whether or not to do bash completion. If None, ask. path_update: bool, Whether or not to do bash completion. If None, ask. rc_path: str, The path to the rc file to update. If None, ask. bin_path: str, The absolute path to the directory that will contain Cloud SDK binaries. sdk_root: str, The path to the Cloud SDK root. """ host_os = platforms.OperatingSystem.Current() if host_os == platforms.OperatingSystem.WINDOWS: if path_update is None: path_update = console_io.PromptContinue( prompt_string='Update %PATH% to include Cloud SDK binaries?') if path_update: _UpdatePathForWindows(bin_path) return completion_rc_path = os.path.join(sdk_root, 'completion.bash.inc') path_rc_path = os.path.join(sdk_root, 'path.bash.inc') if bash_completion is None: if path_update is None: # Ask only one question if both were not set. path_update = console_io.PromptContinue( prompt_string=('\nModify profile to update your $PATH ' 'and enable bash completion?')) bash_completion = path_update else: bash_completion = console_io.PromptContinue( prompt_string=('\nModify profile to enable bash completion?')) elif path_update is None: path_update = console_io.PromptContinue( prompt_string=('\nModify profile to update your $PATH?')) if not bash_completion: print("""\ Source [{completion_rc_path}] in your profile to enable bash completion for gcloud. """.format(completion_rc_path=completion_rc_path)) if not path_update: print("""\ Source [{path_rc_path}] in your profile to add the Google Cloud SDK command line tools to your $PATH. """.format(path_rc_path=path_rc_path)) if not bash_completion and not path_update: return if not rc_path: # figure out what file to edit if host_os == platforms.OperatingSystem.LINUX: if c_gce.Metadata().connected: file_name = '.bash_profile' else: file_name = '.bashrc' elif host_os == platforms.OperatingSystem.MACOSX: file_name = '.bash_profile' elif host_os == platforms.OperatingSystem.CYGWIN: file_name = '.bashrc' elif host_os == platforms.OperatingSystem.MSYS: file_name = '.profile' else: file_name = '.bashrc' rc_path = os.path.expanduser(os.path.join('~', file_name)) rc_path_update = console_io.PromptResponse(( 'The Google Cloud SDK installer will now prompt you to update an rc ' 'file to bring the Google Cloud CLIs into your environment.\n\n' 'Enter path to an rc file to update, or leave blank to use ' '[{rc_path}]: ').format(rc_path=rc_path)) if rc_path_update: rc_path = os.path.expanduser(rc_path_update) if os.path.exists(rc_path): with open(rc_path) as rc_file: rc_data = rc_file.read() cached_rc_data = rc_data else: rc_data = '' cached_rc_data = '' if path_update: path_comment = r'# The next line updates PATH for the Google Cloud SDK.' path_subre = re.compile(r'\n*'+path_comment+r'\n.*$', re.MULTILINE) path_line = "{comment}\nsource '{path_rc_path}'\n".format( comment=path_comment, path_rc_path=path_rc_path) filtered_data = path_subre.sub('', rc_data) rc_data = '{filtered_data}\n{path_line}'.format( filtered_data=filtered_data, path_line=path_line) if bash_completion: complete_comment = r'# The next line enables bash completion for gcloud.' complete_subre = re.compile(r'\n*'+complete_comment+r'\n.*$', re.MULTILINE) complete_line = "{comment}\nsource '{rc_path}'\n".format( comment=complete_comment, rc_path=completion_rc_path) filtered_data = complete_subre.sub('', rc_data) rc_data = '{filtered_data}\n{complete_line}'.format( filtered_data=filtered_data, complete_line=complete_line) if cached_rc_data == rc_data: print('No changes necessary for [{rc}].'.format(rc=rc_path)) return if os.path.exists(rc_path): rc_backup = rc_path+'.backup' print('Backing up [{rc}] to [{backup}].'.format( rc=rc_path, backup=rc_backup)) shutil.copyfile(rc_path, rc_backup) with open(rc_path, 'w') as rc_file: rc_file.write(rc_data) print("""\ [{rc_path}] has been updated. Start a new shell for the changes to take effect. """.format(rc_path=rc_path))
5,345,738
def get_detail_root(): """ Get the detail storage path in the git project """ return get_root() / '.detail'
5,345,739
def sample_data(_, val, sampling_strategy=spec.SamplingStrategy.UNDERSAMPLE, side=0): """Function called in a Beam pipeline that performs sampling using Python's random module on an input key:value pair, where the key is the class label and the values are the data points to sample. Note that the key is discarded.""" if sampling_strategy == spec.SamplingStrategy.UNDERSAMPLE: random_sample_data = random.sample(val, side) elif sampling_strategy == spec.SamplingStrategy.OVERSAMPLE: random_sample_data = random.choices(val, k=side) else: raise ValueError("Invalid value for sampling_strategy variable!") for item in random_sample_data: yield item
5,345,740
def solve(strs, m, n): """ 2D 0-1 knapsack """ def count(s): m, n = 0, 0 for c in s: if c == "0": m += 1 elif c == "1": n += 1 return m, n dp = [] for _ in range(m + 1): dp.append([0] * (n + 1)) for s in strs: mi, ni = count(s) for j in range(m, mi - 1, -1): # reverse! for k in range(n, ni - 1, -1): # reverse! dp[j][k] = max(dp[j][k], dp[j - mi][k - ni] + 1) return dp[m][n]
5,345,741
def bk_category_chosen_category(): """Returns chosen category for creating bk_category object.""" return "Bread"
5,345,742
def apply_weights( events, total_num=1214165.85244438, # for chips_1200 nuel_frac=0.00003202064566, # for chips_1200 anuel_frac=0.00000208200747, # for chips_1200 numu_frac=0.00276174709613, # for chips_1200 anumu_frac=0.00006042213136, # for chips_1200 cosmic_frac=0.99714372811940, # for chips_1200 osc_file_name="./inputs/oscillations/matter_osc_cp_zero.root", verbose=False, ): """Calculate and apply the 'weight' column to scale events to predicted numbers. Args: events (pd.DataFrame): events dataframe to append weights to total_num (float): total number of expected events in a year nuel_frac (float): fraction of events from nuel anuel_frac (float): fraction of events from anuel numu_frac (float): fraction of events from numu anumu_frac (float): fraction of events from anumu cosmic_frac (float): fractions of events from cosmics osc_file_name (str): Oscillation data file name verbose (bool): should we print the weight summary? Returns: pd.DataFrame: events dataframe with weights """ def apply_scale_weight(event, w_nuel, w_anuel, w_numu, w_anumu, w_cosmic): """Add the correct weight to each event. Args: event (dict): pandas event(row) dict w_nuel: nuel weight w_anuel: anuel weight w_numu: numu weight w_anumu: anumu weight w_cosmic: cosmic weight """ if ( event[data.MAP_NU_TYPE["name"]] == 0 and event[data.MAP_SIGN_TYPE["name"]] == 0 and event[data.MAP_COSMIC_CAT["name"]] == 0 and event["t_sample_type"] == 0 ): # Beam nuel return w_nuel elif ( event[data.MAP_NU_TYPE["name"]] == 0 and event[data.MAP_SIGN_TYPE["name"]] == 0 and event[data.MAP_COSMIC_CAT["name"]] == 0 and event["t_sample_type"] == 1 ): # Appeared nuel return 1 elif ( event[data.MAP_NU_TYPE["name"]] == 0 and event[data.MAP_SIGN_TYPE["name"]] == 1 and event[data.MAP_COSMIC_CAT["name"]] == 0 and event["t_sample_type"] == 0 ): # Beam anuel return w_anuel elif ( event[data.MAP_NU_TYPE["name"]] == 1 and event[data.MAP_SIGN_TYPE["name"]] == 0 and event[data.MAP_COSMIC_CAT["name"]] == 0 and event["t_sample_type"] == 0 ): # Beam numu return w_numu elif ( event[data.MAP_NU_TYPE["name"]] == 1 and event[data.MAP_SIGN_TYPE["name"]] == 1 and event[data.MAP_COSMIC_CAT["name"]] == 0 and event["t_sample_type"] == 0 ): # Beam anumu return w_anumu elif event[data.MAP_COSMIC_CAT["name"]] == 1 and event["t_sample_type"] == 2: return w_cosmic else: return 0 def apply_osc_weight(event, numu_survival_prob, nuel_osc): """Add the correct weight to each event. Args: event (dict): pandas event(row) dict numu_survival_prob (np.array): numu survival probability array nuel_osc (np.array): numu appearance scaled probability array """ if ( event[data.MAP_NU_TYPE["name"]] == 0 and event[data.MAP_SIGN_TYPE["name"]] == 0 and event[data.MAP_COSMIC_CAT["name"]] == 0 and event["t_sample_type"] == 0 ): # Beam nuel return event["w"] if ( event[data.MAP_NU_TYPE["name"]] == 0 and event[data.MAP_SIGN_TYPE["name"]] == 0 and event[data.MAP_COSMIC_CAT["name"]] == 0 and event["t_sample_type"] == 1 ): # Appeared nuel nu_energy = math.floor(event["t_nu_energy"] / 100) if nu_energy > 99: nu_energy = 99 if nuel_osc[nu_energy] == 0.0: return event["w"] else: return nuel_osc[nu_energy] * event["w"] elif ( event[data.MAP_NU_TYPE["name"]] == 0 and event[data.MAP_SIGN_TYPE["name"]] == 1 and event[data.MAP_COSMIC_CAT["name"]] == 0 and event["t_sample_type"] == 0 ): # beam anuel return event["w"] elif ( event[data.MAP_NU_TYPE["name"]] == 1 and event[data.MAP_SIGN_TYPE["name"]] == 0 and event[data.MAP_COSMIC_CAT["name"]] == 0 and event["t_sample_type"] == 0 ): # Beam numu nu_energy = math.floor(event["t_nu_energy"] / 100) if nu_energy > 99: nu_energy = 99 return numu_survival_prob[nu_energy] * event["w"] elif ( event[data.MAP_NU_TYPE["name"]] == 1 and event[data.MAP_SIGN_TYPE["name"]] == 1 and event[data.MAP_COSMIC_CAT["name"]] == 0 and event["t_sample_type"] == 0 ): # Beam anumu nu_energy = math.floor(event["t_nu_energy"] / 100) if nu_energy > 99: nu_energy = 99 return numu_survival_prob[nu_energy] * event["w"] elif event[data.MAP_COSMIC_CAT["name"]] == 1 and event["t_sample_type"] == 2: return event["w"] else: return 0 np.seterr(divide="ignore", invalid="ignore") tot_nuel = events[ (events[data.MAP_NU_TYPE["name"]] == 0) & (events[data.MAP_SIGN_TYPE["name"]] == 0) & (events[data.MAP_COSMIC_CAT["name"]] == 0) & (events["t_sample_type"] == 0) ].shape[0] tot_anuel = events[ (events[data.MAP_NU_TYPE["name"]] == 0) & (events[data.MAP_SIGN_TYPE["name"]] == 1) & (events[data.MAP_COSMIC_CAT["name"]] == 0) & (events["t_sample_type"] == 0) ].shape[0] tot_numu = events[ (events[data.MAP_NU_TYPE["name"]] == 1) & (events[data.MAP_SIGN_TYPE["name"]] == 0) & (events[data.MAP_COSMIC_CAT["name"]] == 0) & (events["t_sample_type"] == 0) ].shape[0] tot_anumu = events[ (events[data.MAP_NU_TYPE["name"]] == 1) & (events[data.MAP_SIGN_TYPE["name"]] == 1) & (events[data.MAP_COSMIC_CAT["name"]] == 0) & (events["t_sample_type"] == 0) ].shape[0] tot_cosmic = events[events[data.MAP_COSMIC_CAT["name"]] == 1].shape[0] if tot_nuel == 0: w_nuel = 0.0 else: w_nuel = (1.0 / tot_nuel) * (nuel_frac * total_num) if tot_anuel == 0: w_anuel = 0.0 else: w_anuel = (1.0 / tot_anuel) * (anuel_frac * total_num) if tot_numu == 0: w_numu = 0.0 else: w_numu = (1.0 / tot_numu) * (numu_frac * total_num) if tot_anumu == 0: w_anumu = 0.0 else: w_anumu = (1.0 / tot_anumu) * (anumu_frac * total_num) if tot_cosmic == 0: w_cosmic = 0.0 else: w_cosmic = (1.0 / tot_cosmic) * (cosmic_frac * total_num) if verbose: print( "Weights: ({},{:.5f}), ({},{:.5f}), ({},{:.5f}), ({},{:.5f}), ({},{:.5f})".format( tot_nuel, w_nuel, tot_anuel, w_anuel, tot_numu, w_numu, tot_anumu, w_anumu, tot_cosmic, w_cosmic, ) ) events["w"] = events.apply( apply_scale_weight, axis=1, args=(w_nuel, w_anuel, w_numu, w_anumu, w_cosmic), ) # Now we need to apply the oscillation probability weights osc_file = uproot.open(osc_file_name) # We need to scale the nuel events so they simulate the appearance spectra numu_ev = events[ # Get the unoscillated numu beam events (events[data.MAP_NU_TYPE["name"]] == 1) & (events[data.MAP_SIGN_TYPE["name"]] == 0) & (events[data.MAP_COSMIC_CAT["name"]] == 0) & (events["t_sample_type"] == 0) ] nuel_ev = events[ # Get the nuel events generated with the numu flux (events[data.MAP_NU_TYPE["name"]] == 0) & (events[data.MAP_SIGN_TYPE["name"]] == 0) & (events[data.MAP_COSMIC_CAT["name"]] == 0) & (events["t_sample_type"] == 1) ] numu_e_h = np.histogram( numu_ev["t_nu_energy"] / 100, bins=100, range=(0, 100), weights=numu_ev["w"], ) nuel_e_h = np.histogram( nuel_ev["t_nu_energy"] / 100, bins=100, range=(0, 100), weights=nuel_ev["w"], ) nuel_osc = (numu_e_h[0] * osc_file["hist_mue"].values) / nuel_e_h[0] # Apply a weight to every event events["w"] = events.apply( apply_osc_weight, axis=1, args=( osc_file["hist_mumu"].values, nuel_osc, ), ) return events
5,345,743
def on_collections_deleted(event): """Some collections were deleted, delete records.""" storage = event.request.registry.storage permission = event.request.registry.permission for change in event.impacted_objects: collection = change["old"] bucket_id = event.payload["bucket_id"] parent_id = utils.instance_uri( event.request, "collection", bucket_id=bucket_id, id=collection["id"] ) storage.delete_all(resource_name=None, parent_id=parent_id, with_deleted=False) storage.purge_deleted(resource_name=None, parent_id=parent_id) permission.delete_object_permissions(parent_id + "/*")
5,345,744
def search_google(search_term): """This function will open google.com on firefox, then search for anything on google""" with webdriver.Firefox() as driver: driver.get("https://www.google.com") assert "Google" in driver.title # if the window loaded title is Google then continue below query_element = driver.find_element_by_name('q') query_element.send_keys(search_term) query_element.submit() sleep(10)
5,345,745
def _pipe_line_with_colons(colwidths, colaligns): """Return a horizontal line with optional colons to indicate column's alignment (as in `pipe` output format).""" segments = [_pipe_segment_with_colons(a, w) for a, w in zip(colaligns, colwidths)] return "|" + "|".join(segments) + "|"
5,345,746
def evaluarcalc(): """Evalua a través de un AFD una expresión numérica a ingresar """ if setanalizador() == False: return analizador.CadenaSigma = input("Ingrese la expresión a evaluar: ") analizador.resetattributes() ansyntax = Evaluador(analizador) if ansyntax.inieval(): print("Expresión sintácticamente correcta.\nResultado:", ansyntax.result) else: print("Expresión sintácticamente INCORRECTA")
5,345,747
def print_stats(hw_name: str = '', task_name: str = ''): """Prints user's progress on completing the course tasks. Parameters ---------- hw_name : str, optional A course homework about which the statistics was requested. task_name : str, optional A homework task about which the statistics was requested. """ stats = _get_stats() if not hw_name and not task_name: for hw_name in stats: print(f'{hw_name}: {_decorate(list(stats[hw_name].values()))}') for task_name in stats[hw_name]: print(f' - {task_name}: {_decorate(stats[hw_name][task_name])}') return if hw_name: if hw_name not in stats: raise ValueError(f'Invalid homework name was provided: {hw_name}!') if task_name: if task_name not in stats[hw_name]: raise ValueError( f'Invalid task name was provided: {task_name}!' ) print( f'{hw_name} - {task_name}:', _decorate(stats[hw_name][task_name]), ) return print(f'{hw_name}: {_decorate(list(stats[hw_name].values()))}') for task_name in stats[hw_name]: print(f' - {task_name}: {_decorate(stats[hw_name][task_name])}') return if task_name: for hw_name in stats: if task_name in stats[hw_name]: print( f'{hw_name} - {task_name}:', _decorate(stats[hw_name][task_name]), ) return raise ValueError(f'Invalid task name was provided: {task_name}!')
5,345,748
def convert_to_dates(start, end): """ CTD - Convert two strings to datetimes in format 'xx:xx' param start: String - First string to convert param end: String - Second string to convert return: datetime - Two datetimes """ start = datetime.strptime(start, "%H:%M") end = datetime.strptime(end, "%H:%M") if end < start: end += timedelta(days=1) return start, end
5,345,749
def flipud(m): """ Flips the entries in each column in the up/down direction. Rows are preserved, but appear in a different order than before. Args: m (Tensor): Input array. Returns: Tensor. Raises: TypeError: If the input is not a tensor. Supported Platforms: ``GPU`` ``CPU`` Example: >>> import mindspore.numpy as np >>> A = np.arange(8.0).reshape((2,2,2)) >>> output = np.flipud(A) >>> print(output) [[[4. 5.] [6. 7.]] [[0. 1.] [2. 3.]]] """ return flip(m, 0)
5,345,750
def get_book_url(tool_name, category): """Get the link to the help documentation of the tool. Args: tool_name (str): The name of the tool. category (str): The category of the tool. Returns: str: The URL to help documentation. """ prefix = "https://jblindsay.github.io/wbt_book/available_tools" url = "{}/{}.html#{}".format(prefix, category, tool_name) return url
5,345,751
def demo_long_lived_cluster(): """ Shows how to create a long-lived cluster that waits after all steps are run so that more steps can be run. At the end of the demo, the cluster is optionally terminated. """ print('-'*88) print(f"Welcome to the Amazon EMR long-lived cluster demo.") print('-'*88) prefix = 'demo-long-emr' s3_resource = boto3.resource('s3') iam_resource = boto3.resource('iam') emr_client = boto3.client('emr') ec2_resource = boto3.resource('ec2') # Set up resources for the demo. bucket_name = f'{prefix}-{time.time_ns()}' script_file_name = 'pyspark_top_product_keyword.py' script_key = f'scripts/{script_file_name}' bucket = setup_bucket(bucket_name, script_file_name, script_key, s3_resource) job_flow_role, service_role = \ create_roles(f'{prefix}-ec2-role', f'{prefix}-service-role', iam_resource) security_groups = create_security_groups(prefix, ec2_resource) print("Wait for 10 seconds to give roles and profiles time to propagate...") time.sleep(10) max_tries = 5 while True: try: cluster_id = emr_basics.run_job_flow( f'{prefix}-cluster', f's3://{bucket_name}/logs', True, ['Hadoop', 'Hive', 'Spark'], job_flow_role, service_role, security_groups, [], emr_client) print(f"Running job flow for cluster {cluster_id}...") break except ClientError as error: max_tries -= 1 if max_tries > 0 and \ error.response['Error']['Code'] == 'ValidationException': print("Instance profile is not ready, let's give it more time...") time.sleep(10) else: raise status_poller( "Waiting for cluster, this typically takes several minutes...", 'WAITING', lambda: emr_basics.describe_cluster(cluster_id, emr_client)['Status']['State'], ) add_top_product_step( '20', 'Books', 'fire', cluster_id, bucket, script_key, emr_client) add_top_product_step( '20', 'Grocery', 'cheese', cluster_id, bucket, script_key, emr_client) review_bucket_folders = s3_resource.meta.client.list_objects_v2( Bucket='demo-reviews-pds', Prefix='parquet/', Delimiter='/', MaxKeys=100) categories = [ cat['Prefix'].split('=')[1][:-1] for cat in review_bucket_folders['CommonPrefixes']] while True: while True: input_cat = input( f"Your turn! Possible categories are: {categories}. Which category " f"would you like to search (enter 'none' when you're done)? ") if input_cat.lower() == 'none' or input_cat in categories: break elif input_cat not in categories: print(f"Sorry, {input_cat} is not an allowed category!") if input_cat.lower() == 'none': break else: input_keyword = input("What keyword would you like to search for? ") input_count = input("How many items would you like to list? ") add_top_product_step( input_count, input_cat, input_keyword, cluster_id, bucket, script_key, emr_client) # Clean up demo resources (if you want to). remove_everything = input( f"Do you want to terminate the cluster and delete the security roles, " f"groups, bucket, and all of its contents (y/n)? ") if remove_everything.lower() == 'y': emr_basics.terminate_cluster(cluster_id, emr_client) status_poller( "Waiting for cluster to terminate.", 'TERMINATED', lambda: emr_basics.describe_cluster(cluster_id, emr_client)['Status'][ 'State'] ) delete_security_groups(security_groups) delete_roles([job_flow_role, service_role]) delete_bucket(bucket) else: print( f"Remember that running Amazon EMR clusters and objects kept in an " f"Amazon S3 bucket can incur charges against your account.") print("Thanks for watching!")
5,345,752
def save_xyz_filehandle(X, symbols, handle, text="", format_str="% .11E"): """ Write coordinates and symbols to given file handle. Args: X: coordinates (can also append velocities or whatever) symbols: atomic symbols handle: file handle to write to text: Helper text in second line format_str: formatting for coordinates to write """ Xsh = np.shape(X) handle.write("%d\n" % Xsh[0]) handle.write(text) handle.write("\n") for i in range(Xsh[0]): handle.write(symbols[i]) for j in range(Xsh[1]): handle.write("\t") handle.write(format_str % X[i, j]) handle.write("\n")
5,345,753
def read_csv(file_name='data.csv'): """Returns a list of dicts from a csv file.""" # Your code goes here pass
5,345,754
def test_records(db, test_data): """Load test records.""" result = [] for r in test_data: result.append(create_record(r)) db.session.commit() yield result
5,345,755
def game_hash(s): """Generate hash-based identifier for a game account based on the text of the game. """ def int_to_base(n): alphabet = "BCDFGHJKLMNPQRSTVWXYZ" base = len(alphabet) if n < base: return alphabet[n] return int_to_base(n // base) + alphabet[n % base] return int_to_base( int(hashlib.sha1(s.encode('utf-8')).hexdigest(), 16) )[-7:]
5,345,756
def thumbnail_url(bbox, layers, qgis_project, style=None, internal=True): """Internal function to generate the URL for the thumbnail. :param bbox: The bounding box to use in the format [left,bottom,right,top]. :type bbox: list :param layers: Name of the layer to use. :type layers: basestring :param qgis_project: The path to the QGIS project. :type qgis_project: basestring :param style: Layer style to choose :type style: str :param internal: Flag to switch between public url and internal url. Public url will be served by Django Geonode (proxified). :type internal: bool :return: The WMS URL to fetch the thumbnail. :rtype: basestring """ x_min, y_min, x_max, y_max = bbox # We calculate the margins according to 10 percent. percent = 10 delta_x = (x_max - x_min) / 100 * percent delta_x = math.fabs(delta_x) delta_y = (y_max - y_min) / 100 * percent delta_y = math.fabs(delta_y) # We apply the margins to the extent. margin = [ y_min - delta_y, x_min - delta_x, y_max + delta_y, x_max + delta_x ] # Call the WMS. bbox = ','.join([str(val) for val in margin]) query_string = { 'SERVICE': 'WMS', 'VERSION': '1.1.1', 'REQUEST': 'GetMap', 'BBOX': bbox, 'SRS': 'EPSG:4326', 'WIDTH': '250', 'HEIGHT': '250', 'MAP': qgis_project, 'LAYERS': layers, 'STYLE': style, 'FORMAT': 'image/png', 'TRANSPARENT': 'true', 'DPI': '96', 'MAP_RESOLUTION': '96', 'FORMAT_OPTIONS': 'dpi:96' } qgis_server_url = qgis_server_endpoint(internal) url = Request('GET', qgis_server_url, params=query_string).prepare().url return url
5,345,757
def evaluate_prediction_power(df, num_days=1): """" Applies a shift to the model for the number of days given, default to 1, and feed the data to a linear regression model. Evaluate the results using score and print it. """ scores = {} print "Num days: {}".format(range(num_days)) for i in range(num_days): X,y = get_xy(df, num_days=i) regressor = learn(X,y) scores[i] = regressor.score(X,y) return scores
5,345,758
def get_select_file_dialog_dir(): """" Return the directory that should be displayed by default in file dialogs. """ directory = CONF.get('main', 'select_file_dialog_dir', get_home_dir()) directory = directory if osp.exists(directory) else get_home_dir() return directory
5,345,759
def exercise9(): """ Write a Python program to display the examination schedule. (extract the date from exam_st_date). exam_st_date = (11, 12, 2014) Sample Output : The examination will start from : 11 / 12 / 2014 """ exam_st_date = (11, 12, 2014) string_date = datetime.date(year=exam_st_date[2], month=exam_st_date[1], day=exam_st_date[0]) print('The date is: %s' % (string_date.strftime("%d/%m/%Y"))) return
5,345,760
def get_photo_filesystem_path(photos_basedir, album_name, filename): """ Gets location of photo on filesystem, e.g.: /some/dir/album/photo.jpg :param album_name: :param filename: :return: """ return os.path.join(photos_basedir, get_photo_filesystem_relpath(album_name, filename))
5,345,761
def _validate_detect_criteria( ext_detect_criteria: Mapping[str, _DetectQueryMapping], ext_communication_types: Collection[Type[Any]], package_name: str) -> None: """Validates the extension detection criteria. Args: ext_detect_criteria: Detection criteria to validate, where mapping keys are communication type names, and values are detection query mappings for each communication type. ext_communication_types: Communication types exported by the package. package_name: Name of the package providing the extensions. Raises: PackageRegistrationError: Detection criteria are invalid. """ extension_comm_type_names = [comm_type.__name__ for comm_type in ext_communication_types] for comm_type_name, query_dict in ext_detect_criteria.items(): for query_name, query in query_dict.items(): base_error = ("Unable to register query {} for communication type {!r}. " .format(query_name, comm_type_name)) if not isinstance(query_name, detect_criteria.QueryEnum): raise errors.PackageRegistrationError( base_error + "Detection query keys must be {} instances.".format( detect_criteria.QueryEnum.__name__), package_name=package_name) if (not callable(query) or tuple(inspect.getfullargspec(query).args) != _EXPECTED_QUERY_ARGS): extra_error = ("Detection queries must be callable functions which " "accept {} arguments: {}." .format(len(_EXPECTED_QUERY_ARGS), _EXPECTED_QUERY_ARGS)) raise errors.PackageRegistrationError(base_error + extra_error, package_name=package_name) if comm_type_name not in extensions.detect_criteria: if comm_type_name not in extension_comm_type_names: raise errors.PackageRegistrationError( "Unable to register detection criteria for communication type " f"{comm_type_name!r} as it has not been exported by the package.", package_name=package_name) else: redefined_queries = list( extensions.detect_criteria[comm_type_name].keys() & query_dict.keys()) if redefined_queries: raise errors.PackageRegistrationError( f"Detection queries {redefined_queries} for communication type " f"{comm_type_name!r} are already defined in GDM.", package_name=package_name)
5,345,762
def test_prepare_source(source): """Test the ``PseudoPotentialData.prepare_source`` method for valid input.""" assert isinstance(PseudoPotentialData.prepare_source(source), io.BytesIO) if isinstance(source, io.BytesIO): # If we pass a bytestream, we should get the exact same back assert PseudoPotentialData.prepare_source(source) is source
5,345,763
def getAdminData(self): """ Deliver admin content of module alarms (ajax) :return: rendered template as string or json dict """ if request.args.get('action') == 'upload': if request.files: ufile = request.files['uploadfile'] fname = os.path.join(current_app.config.get('PATH_TMP'), ufile.filename) ufile.save(fname) scheduler.add_job(processFile, args=[current_app.config.get('PATH_TMP'), ufile.filename]) # schedule operation return "" elif request.args.get('action') == 'uploadchecker': if request.files: ufile = request.files['uploadfile'] if not os.path.exists('%s/emonitor/modules/alarms/inc/%s' % (current_app.config.get('PROJECT_ROOT'), ufile.filename)): ufile.save('%s/emonitor/modules/alarms/inc/%s' % (current_app.config.get('PROJECT_ROOT'), ufile.filename)) try: cls = imp.load_source('emonitor.modules.alarms.inc', 'emonitor/modules/alarms/inc/%s' % ufile.filename) if isinstance(getattr(cls, cls.__all__[0])(), AlarmFaxChecker): return "ok" except: pass os.remove('%s/emonitor/modules/alarms/inc/%s' % (current_app.config.get('PROJECT_ROOT'), ufile.filename)) return babel.gettext(u'admin.alarms.checkernotvalid') return "" elif request.args.get('action') == 'uploaddefinition': """ add alarmtype with given config for uploadfile """ alarmtype = AlarmType.buildFromConfigFile(request.files['uploadfile']) if not alarmtype: db.session.rollback() return babel.gettext(u'admin.alarms.incorrecttypedefinition') db.session.add(alarmtype) db.session.commit() return "ok" elif request.args.get('action') == 'gettypedefinition': """ export alarmtype definition as cfg-file """ alarmtype = AlarmType.getAlarmTypes(request.args.get('alarmtype')) if alarmtype: return Response(alarmtype.getConfigFile(), mimetype="application/x.download; charset=utf-8") else: return None elif request.args.get('action') == 'getkeywords': """ send list with all keywords of alarmtype """ for f in [f for f in os.listdir('%s/emonitor/modules/alarms/inc/' % current_app.config.get('PROJECT_ROOT')) if f.endswith('.py')]: if f == request.args.get('checker'): cls = imp.load_source('emonitor.modules.alarms.inc', 'emonitor/modules/alarms/inc/%s' % f) cls = getattr(cls, cls.__all__[0])() return {u'keywords': "\n".join(cls.getDefaultConfig()[u'keywords']), u'variables': cls.getDefaultConfig()[u'translations'], u'attributes': cls.getDefaultConfig()[u'attributes']} return "" elif request.args.get('action') == 'alarmsforstate': alarms = Alarm.getAlarms(state=int(request.args.get('state'))) return render_template('admin.alarms_alarm.html', alarms=alarms) elif request.args.get('action') == 'alarmsarchive': for id in request.args.get('alarmids').split(','): Alarm.changeState(int(id), 3) return "" elif request.args.get('action') == 'savefieldorder': # change order of fields fields = [] deptid = '0' for f in request.args.get('order').split(','): t, deptid, name = f.split('.') fields.append(name) if int(deptid): for dbfield in AlarmField.getAlarmFields(dept=deptid): dbfield.position = fields.index(dbfield.fieldtype) db.session.commit() return "" elif request.args.get('action') == 'addreport': f = request.files['template'] fname = "{}.{}".format(random.random(), f.filename.split('.')[-1]) fpath = '{}alarmreports/{}'.format(current_app.config.get('PATH_DATA'), fname[2:]) f.save(fpath) if f.filename.endswith('pdf'): fields = getFormFields(fpath) content = render_template('admin.alarms.report_fields.html', filepath='{}alarmreports/{}'.format(current_app.config.get('PATH_DATA'), fname[2:]), fileinfo=getPDFInformation(fpath), fields=fields, multi=max(fields.values()) > 1) else: content = "" fields = [] return {'filename': fname, 'content': content} elif request.args.get('action') == 'reportdetails': return render_template('admin.alarms.report_details.html', report=AlarmReport.getReports(id=request.args.get('reportid')), reporttype=AlarmReport.getReportTypes(request.args.get('template')), departments=request.args.get('departments')) elif request.args.get('action') == 'reportfieldlookup': ret = OrderedDict() ret['basic'] = [] # add basic information from AFBasic class for f in AFBasic().getFields(): ret['basic'].append({'id': f.name, 'value': f.id}) alarmfields = {} for alarmfield in AlarmField.getAlarmFields(): if str(alarmfield.dept) not in request.args.get('departments').split(','): continue if alarmfield.fieldtype not in alarmfields: alarmfields[alarmfield.fieldtype] = [] alarmfields[alarmfield.fieldtype].append(alarmfield) l = "" for alarmfield in list(chain.from_iterable([f for f in alarmfields.values() if len(f) == len(request.args.get('departments').split(','))])): if '%s' % alarmfield.name not in ret: ret['%s' % alarmfield.name] = [{'id': '%s-list' % alarmfield.fieldtype, 'value': '%s (%s)' % (alarmfield.name, babel.gettext('admin.alarms.list'))}] for f in alarmfield.getFields(): if f.getLabel().strip() not in ["", '<leer>']: # dismiss empty values if f.name[0] != ' ': value = '%s' % babel.gettext(f.getLabel()) l = value else: # add name of kategory value = '%s > %s' % (l, babel.gettext(f.getLabel())) ret['%s' % alarmfield.name].append({'id': '%s-%s' % (alarmfield.fieldtype, f.id), 'value': value}) return ret
5,345,764
def join_collections(sql_query: sql.SQLQuery) -> QueryExpression: """Join together multiple collections to return their documents in the response. Params: ------- sql_query: SQLQuery object with information about the query params. Returns: -------- An FQL query expression for joined and filtered documents. """ tables = sql_query.tables order_by = sql_query.order_by from_table = tables[0] to_table = tables[-1] table_with_columns = next(table for table in tables if table.has_columns) if ( order_by is not None and order_by.columns[0].table_name != table_with_columns.name ): raise exceptions.NotSupportedError( "Fauna uses indexes for both joining and ordering of results, " "and we currently can only sort the principal table " "(i.e. the one whose columns are being selected or modified) in the query. " "You can sort on a column from the principal table, query one table at a time, " "or remove the ordering constraint." ) if not any(sql_query.filter_groups): raise exceptions.NotSupportedError( "Joining tables without cross-table filters via the WHERE clause is not supported. " "Selecting columns from multiple tables is not supported either, " "so there's no performance gain from joining tables without cross-table conditions " "for filtering query results." ) assert from_table.left_join_table is None intersection_queries = [] for filter_group in sql_query.filter_groups: intersection_query = q.intersection( *[ _build_intersecting_query(filter_group, None, table, direction) for table, direction in [(from_table, "right"), (to_table, "left")] ] ) intersection_queries.append(intersection_query) return q.union(*intersection_queries)
5,345,765
def querylist(query, encoding='utf-8', errors='replace'): """Split the query component into individual `name=value` pairs and return a list of `(name, value)` tuples. """ if query: qsl = [query] else: return [] if isinstance(query, bytes): QUERYSEP = (b';', b'&') EQ = b'=' else: QUERYSEP = ';&' EQ = '=' for sep in QUERYSEP: qsl = [s for qs in qsl for s in qs.split(sep) if s] items = [] for qs in qsl: parts = qs.partition(EQ) name = uridecode_safe_plus(parts[0], encoding, errors) if parts[1]: value = uridecode_safe_plus(parts[2], encoding, errors) else: value = None items.append((name, value)) return items
5,345,766
def plot_timeseries(ax, id_ax, data, xticks, xlabel='', ylabel='', label='', logx=False, logy=False, zorder=10, linespecs=None): """Plots timeseries data with error bars.""" if logx: ax[id_ax].set_xscale('log') if logy: ax[id_ax].set_yscale('log') if linespecs: kwargs = {'color': linespecs['color']} else: kwargs = {} # Seaborn's bootstrapped confidence intervals were used in the original paper se = scipy.stats.sem(data, axis=0) ax[id_ax].fill_between(xticks, data.mean(0)-se, data.mean(0)+se, zorder=zorder, alpha=0.2, **kwargs) ax[id_ax].plot(xticks, data.mean(0), label=label, zorder=zorder, **kwargs) # There may be multiple lines on the current axis, some from previous calls to # plot_timeseries, so reference just the latest if linespecs: ax[id_ax].get_lines()[-1].set_dashes([5, 5]) ax[id_ax].get_lines()[-1].set_linestyle(linespecs['linestyle']) ax[id_ax].set(xlabel=xlabel, ylabel=ylabel) ax[id_ax].set_axisbelow(True) ax[id_ax].grid(True) for _, spine in ax[id_ax].spines.items(): spine.set_zorder(-1)
5,345,767
def rotate_space_123(angles): """Returns the direction cosine matrix relating a reference frame B rotated relative to reference frame A through the x, y, then z axes of reference frame A (spaced fixed rotations). Parameters ---------- angles : numpy.array or list or tuple, shape(3,) Three angles (in units of radians) that specify the orientation of a new reference frame with respect to a fixed reference frame. The first angle is a pure rotation about the x-axis, the second about the y-axis, and the third about the z-axis. All rotations are with respect to the initial fixed frame, and they occur in the order x, then y, then z. Returns ------- R : numpy.matrix, shape(3,3) Three dimensional rotation matrix about three different orthogonal axes. Notes ----- R = |c2 * c3 s1 * s2 * c3 - s3 * c1 c1 * s2 * c3 + s3 * s1| |c2 * s3 s1 * s2 * s3 + c3 * c1 c1 * s2 * s3 - c3 * s1| |-s2 s1 * c2 c1 * c2 | where s1, s2, s3 = sine of the first, second and third angles, respectively c1, c2, c3 = cosine of the first, second and third angles, respectively So the unit vector b1 in the B frame can be expressed in the A frame (unit vectors a1, a2, a3) with: b1 = c2 * c3 * a1 + c2 * s3 * a2 - s2 * a3 Thus a vector vb which is expressed in frame B can be expressed in A by pre-multiplying by R: va = R * vb """ cx = np.cos(angles[0]) sx = np.sin(angles[0]) cy = np.cos(angles[1]) sy = np.sin(angles[1]) cz = np.cos(angles[2]) sz = np.sin(angles[2]) Rz = np.mat([[ cz,-sz, 0], [ sz, cz, 0], [ 0, 0, 1]]) Ry = np.mat([[ cy, 0, sy], [ 0, 1, 0], [-sy, 0, cy]]) Rx = np.mat([[ 1, 0, 0], [ 0, cx, -sx], [ 0, sx, cx]]) return Rz * Ry * Rx
5,345,768
def parse_arguments(): """Parse and return the command line argument dictionary object """ parser = ArgumentParser("CIFAR-10/100 Training") _verbosity = "INFO" parser.add_argument( "-v", "--verbosity", type=str.upper, choices=logging._nameToLevel.keys(), default=_verbosity, metavar="VERBOSITY", help="output verbosity: {} (default: {})".format( " | ".join(logging._nameToLevel.keys()), _verbosity ), ) parser.add_argument("--manual-seed", type=int, help="manual seed integer") _mode = "train" parser.add_argument( "-m", "--mode", type=str.lower, default=_mode, choices=["train", "evaluate", "profile"], help=f"script execution mode (default: {_mode})", ) _tw_file = "tw.log" parser.add_argument( "-t", "--tensorwatch-log", type=str, default=_tw_file, help=f"tensorwatch log filename (default: {_tw_file})", ) parser.add_argument( "--gpu-id", default="0", type=str, help="id(s) for CUDA_VISIBLE_DEVICES" ) # Dataset Options d_op = parser.add_argument_group("Dataset") d_op.add_argument( "-d", "--dataset", default="cifar10", type=str.lower, choices=("cifar10", "cifar100"), ) avail_cpus = min(4, len(os.sched_getaffinity(0))) d_op.add_argument( "-w", "--workers", default=avail_cpus, type=int, metavar="N", help=f"number of data-loader workers (default: {avail_cpus})", ) # Architecture Options a_op = parser.add_argument_group("Architectures") _architecture = "alexnet" a_op.add_argument( "-a", "--arch", metavar="ARCH", default=_architecture, choices=MODEL_ARCHS.keys(), help="model architecture: {} (default: {})".format( " | ".join(MODEL_ARCHS.keys()), _architecture ), ) _depth = 29 a_op.add_argument( "--depth", type=int, default=_depth, help=f"Model depth (default: {_depth})" ) _block_name = "basicblock" _block_choices = ["basicblock", "bottleneck"] a_op.add_argument( "--block-name", type=str.lower, default=_block_name, choices=_block_choices, help=f"Resnet|Preresnet building block: (default: {_block_name}", ) _cardinality = 8 a_op.add_argument( "--cardinality", type=int, default=_cardinality, help=f"Resnext cardinality (group) (default: {_cardinality})", ) _widen_factor = 4 a_op.add_argument( "--widen-factor", type=int, default=_widen_factor, help=f"Resnext|WRT widen factor, 4 -> 64, 8 -> 128, ... (default: {_widen_factor})", ) _growth_rate = 12 a_op.add_argument( "--growth-rate", type=int, default=_growth_rate, help=f"DenseNet growth rate (default: {_growth_rate}", ) _compression_rate = 2 a_op.add_argument( "--compressionRate", type=int, default=_compression_rate, help=f"DenseNet compression rate (theta) (default: {_compression_rate}", ) # Optimization Options o_op = parser.add_argument_group("Optimizations") _epochs = 300 o_op.add_argument( "--epochs", default=_epochs, type=int, metavar="N", help=f"number of epochs to run (default: {_epochs})", ) _epoch_start = 0 o_op.add_argument( "--start-epoch", default=_epoch_start, type=int, metavar="N", help=f"epoch start number (default: {_epoch_start})", ) _train_batch = 128 o_op.add_argument( "--train-batch", default=_train_batch, type=int, metavar="N", help=f"train batchsize (default: {_train_batch})", ) _test_batch = 100 o_op.add_argument( "--test-batch", default=_test_batch, type=int, metavar="N", help=f"test batchsize (default: {_test_batch})", ) _lr = 0.1 o_op.add_argument( "--lr", "--learning-rate", default=_lr, type=float, metavar="LR", help=f"initial learning rate (default: {_lr})", ) _dropout = 0 o_op.add_argument( "--drop", "--dropout", default=_dropout, type=float, metavar="Dropout", help=f"Dropout ratio (default: {_dropout})", ) _schedule = [150, 225] o_op.add_argument( "--schedule", type=int, nargs="+", default=_schedule, help=f"Decrease LR at these epochs (default: {_schedule})", ) _gamma = 0.1 o_op.add_argument( "--gamma", type=float, default=_gamma, help=f"LR is multiplied by gamma on schedule (default: {_gamma})", ) _momentum = 0.9 o_op.add_argument( "--momentum", default=_momentum, type=float, metavar="M", help=f"momentum (default: {_momentum})", ) _wd = 5e-4 o_op.add_argument( "--weight-decay", "--wd", default=_wd, type=float, metavar="W", help=f"weight decay (default: {_wd})", ) # Checkpoint Options c_op = parser.add_argument_group("Checkpoints") _checkpoint = "checkpoint" c_op.add_argument( "-c", "--checkpoint", default=_checkpoint, type=str, metavar="PATH", help=f"path to save checkpoint (default: {_checkpoint})", ) return vars(parser.parse_args())
5,345,769
def iree_lit_test_suite( name, cfg = "//iree:lit.cfg.py", tools = None, env = None, **kwargs): """A thin wrapper around lit_test_suite with some opinionated settings. See the base lit_test for more details on argument meanings. Args: name: name for the test suite. cfg: string. lit config file. tools: label_list. tools that should be included on the PATH. llvm-symbolizer is added by default. env: string_dict. Environment variables available to the test at runtime. FILECHECK_OPTS=--enable-var-scope is added if FILECHECK_OPTS is not already set. **kwargs: additional keyword args to forward to the underyling lit_test_suite. """ tools = tools or [] env = env or {} # Always include llvm-symbolizer so we get useful stack traces. Maybe it # would be better to force everyone to do this explicitly, but since # forgetting wouldn't cause the test to fail, only make debugging harder # when it does, I think better to hardcode it here. llvm_symbolizer = "@llvm-project//llvm:llvm-symbolizer" if llvm_symbolizer not in tools: tools.append(llvm_symbolizer) filecheck_env_var = "FILECHECK_OPTS" if filecheck_env_var not in env: env[filecheck_env_var] = "--enable-var-scope" lit_test_suite( name = name, cfg = cfg, tools = tools, env = env, **kwargs )
5,345,770
def get_tac_resource(url): """ Get the requested resource or update resource using Tacoma account :returns: http response with content in xml """ response = None response = TrumbaTac.getURL(url, {"Accept": "application/xml"}) _log_xml_resp("Tacoma", url, response) return response
5,345,771
def cosweightlat(darray, lat1, lat2): """Calculate the weighted average for an [:,lat] array over the region lat1 to lat2 """ # flip latitudes if they are decreasing if (darray.lat[0] > darray.lat[darray.lat.size -1]): print("flipping latitudes") darray = darray.sortby('lat') region = darray.sel(lat=slice(lat1, lat2)) weights=np.cos(np.deg2rad(region.lat)) regionw = region.weighted(weights) regionm = regionw.mean("lat") return regionm
5,345,772
def _GetSoftMaxResponse(goal_embedding, scene_spatial): """Max response of an embeddings across a spatial feature map. The goal_embedding is multiplied across the spatial dimensions of the scene_spatial to generate a heatmap. Then the spatial softmax-pooled value of this heatmap is returned. If the goal_embedding and scene_spatial are aligned to the same space, then _GetSoftMaxResponse returns larger values if the object is present in the scene, and smaller values if the object is not. Args: goal_embedding: A batch x D tensor embedding of the goal image. scene_spatial: A batch x H x W x D spatial feature map tensor. Returns: max_heat: A tensor of length batch. max_soft: The max value of the softmax (ranges between 0 and 1.0) """ batch, dim = goal_embedding.shape reshaped_query = tf.reshape(goal_embedding, (int(batch), 1, 1, int(dim))) scene_heatmap = tf.reduce_sum(tf.multiply(scene_spatial, reshaped_query), axis=3, keep_dims=True) scene_heatmap_flat = tf.reshape(scene_heatmap, (batch, -1)) max_heat = tf.reduce_max(scene_heatmap_flat, axis=1) scene_softmax = tf.nn.softmax(scene_heatmap_flat, axis=1) max_soft = tf.reduce_max(scene_softmax, axis=1) return max_heat, max_soft
5,345,773
async def reddit_imgscrape(ctx, url): """ Randomly selects an image from a subreddit corresponding to a json url and sends it to the channel. Checks for permissions, NSFW-mode. Params: (commands.Context): context (str): json url """ current_channel = ctx.message.channel author = ctx.message.author try: await ctx.trigger_typing() rand_post = _get_rand_post(url) # RedditPost object embed, rand_url = await _create_embed(ctx, rand_post) if not permissions.can_attach(ctx): await current_channel.send('I cannot upload images/GIFs here ;w;') elif not permissions.is_nsfw(ctx) and rand_post.get_nsfw(): await current_channel.send(f'L-lewd {author.name}! NSFW commands go in NSFW channels!! >///<') else: try: if _is_image(rand_url): bio = BytesIO(await http.get(rand_url, res_method='read')) extension = rand_url.split('.')[-1] await current_channel.send(embed=embed) await current_channel.send(file=discord.File(bio, filename=f'image.{extension}')) else: await current_channel.send(embed=embed) await current_channel.send(rand_url) except KeyError: await current_channel.send('That didn\'t work ;o; please try the command again.') except: await current_channel.send("Something went wrong, but I'm not sure what. Please slow down and try again")
5,345,774
def summarize_star(star): """return one line summary of star""" if star.find('name').text[-2] == ' ': name = star.find('name').text[-1] else: name = ' ' mass = format_star_mass_str(star) radius = format_star_radius_str(star) temp = format_body_temp_str(star) metallicity = format_star_metal_str(star) return u'{} {} {:>8} {:>8} {:>8} {:>8} {:>8} {}'.format(name, format_spectral_name(star), mass, radius, '', '', temp, metallicity)
5,345,775
def call_cnvs(input_file, mapping_quality, bam_file, output_directory, fasta_reference): """ Call CNVS questions """ cnv_output_script = os.path.join(output_directory, input_file.samples_name) cnv_analysis_script = "samtools view -q {0} -S {1} | " + SPLITREADBEDTOPE + " -i stdin | grep -v telo | " +SPLITTERTOBREAKPOINT + " -i stdin -s 0 -r {2} -o {3}" cnv_analysis_script = cnv_analysis_script.format(mapping_quality, bam_file, fasta_reference, cnv_output_script) subprocess.check_call(cnv_analysis_script,shell=True)
5,345,776
def to_unicode(text, encoding='utf8', errors='strict'): """Convert a string (bytestring in `encoding` or unicode), to unicode.""" if isinstance(text, unicode): return text return unicode(text, encoding, errors=errors)
5,345,777
def shipping_hide_if_one(sender, form=None, **kwargs): """Makes the widget for shipping hidden if there is only one choice.""" choices = form.fields['shipping'].choices if len(choices) == 1: form.fields['shipping'] = forms.CharField(max_length=30, initial=choices[0][0], widget=forms.HiddenInput(attrs={'value' : choices[0][0]})) form.shipping_hidden = True form.shipping_description = choices[0][1] else: form.shipping_hidden = False
5,345,778
def parse_pipfile(): """Reads package requirements from Pipfile.""" cfg = ConfigParser() cfg.read("Pipfile") dev_packages = [p.strip('"') for p in cfg["dev-packages"]] relevant_packages = [ p.strip('"') for p in cfg["packages"] if "nested-dataclasses" not in p ] return relevant_packages, dev_packages
5,345,779
def print_dist(d, height=12, pch="o", show_number=False, title=None): """ Printing a figure of given distribution Parameters ---------- d: dict, list a dictionary or a list, contains pairs of: "key" -> "count_value" height: int number of maximum lines for the graph pch : str shape of the bars in the plot, e.g 'o' Return ------ str """ LABEL_COLOR = ['cyan', 'yellow', 'blue', 'magenta', 'green'] MAXIMUM_YLABEL = 4 try: if isinstance(d, Mapping): d = d.items() orig_d = [(str(name), int(count)) for name, count in d] d = [(str(name)[::-1].replace('-', '|').replace('_', '|'), count) for name, count in d] labels = [[c for c in name] for name, count in d] max_labels = max(len(name) for name, count in d) max_count = max(count for name, count in d) min_count = min(count for name, count in d) except Exception as e: raise ValueError('`d` must be distribution dictionary contains pair of: ' 'label_name -> disitribution_count, error: "%s"' % str(e)) # ====== create figure ====== # # draw height, 1 line for minimum bar, 1 line for padding the label, # then the labels nb_lines = int(height) + 1 + 1 + max_labels unit = (max_count - min_count) / height fig = "" # ====== add unit and total ====== # fig += ctext("Unit: ", 'red') + \ '10^%d' % max(len(str(max_count)) - MAXIMUM_YLABEL, 0) + ' ' fig += ctext("Total: ", 'red') + \ str(sum(count for name, count in d)) + '\n' # ====== add the figure ====== # for line in range(nb_lines): value = max_count - unit * line # draw the y_label if line % 2 == 0 and line <= int(height): # value fig += ctext( ('%' + str(MAXIMUM_YLABEL) + 's') % str(int(value))[:MAXIMUM_YLABEL], color='red') else: # blank fig += ' ' * MAXIMUM_YLABEL fig += '|' if line <= int(height) else ' ' # draw default line if line == int(height): fig += ''.join([ctext(pch + ' ', color=LABEL_COLOR[i % len(LABEL_COLOR)]) for i in range(len(d))]) # draw seperator for the label elif line == int(height) + 1: fig += '-' * (len(d) * 2) # draw the labels elif line > int(height) + 1: for i, lab in enumerate(labels): fig += ctext(' ' if len(lab) == 0 else lab.pop(), LABEL_COLOR[i % len(LABEL_COLOR)]) + ' ' # draw the histogram else: for i, (name, count) in enumerate(d): fig += ctext(pch if count - value >= 0 else ' ', LABEL_COLOR[i % len(LABEL_COLOR)]) + ' ' # new line fig += '\n' # ====== add actual number of necessary ====== # maximum_fig_length = MAXIMUM_YLABEL + 1 + len(orig_d) * 2 if show_number: line_length = 0 name_fmt = '%' + str(max_labels) + 's' for name, count in orig_d: n = len(name) + len(str(count)) + 4 text = ctext(name_fmt % name, 'red') + ': %d ' % count if line_length + n >= maximum_fig_length: fig += '\n' line_length = n else: line_length += n fig += text # ====== add title ====== # if title is not None: title = ctext('"%s"' % str(title), 'red') padding = ' ' n = (maximum_fig_length - len(title) // 2) // 2 - len(padding) * 3 fig = '=' * n + padding + title + padding + '=' * n + '\n' + fig return fig[:-1]
5,345,780
def test_payload_with_address_invalid_length(api_server_test_instance): """ Encoded addresses must have the right length. """ invalid_address = "0x61c808d82a3ac53231750dadc13c777b59310b" # g at the end is invalid channel_data_obj = { "partner_address": invalid_address, "token_address": "0xEA674fdDe714fd979de3EdF0F56AA9716B898ec8", "settle_timeout": 10, } request = grequests.put( api_url_for(api_server_test_instance, "channelsresource"), json=channel_data_obj ) response = request.send().response assert_response_with_error(response, HTTPStatus.BAD_REQUEST)
5,345,781
def Per_sequence_quality_scores (file_path,output_dire, module): """ Read Per sequence quality scores contents from a fastqc file and parses to output file. Returns a list of data used to plot quality graph. Data and genereted graphs are saved to output directory as png image file and plain text. Acceptes three Aguments :- file_path = File name of fastqc output_dire = Output Folder | directory name module = Fastqc module name """ # opening fastqc data fastqc_data = open(file_path, 'r') # list to store Per Sequence Quality Scores data = [] # creating start/stop switch to read data for specific module read_line = 'stop' for line in fastqc_data: #line.strip("\n\r") if line.startswith('>>Per sequence quality scores'): read_line = 'start' head = line pass elif line.startswith(">>END_MODULE"): read_line = 'stop' # once the netxt module is reached it break the loop and stop reading lines elif line.startswith('>>Per base sequence content'): break elif read_line == 'start': data.append(line) # Here it's creating directory and the try and except will raise any error except if the file exist. try: os.makedirs(output_dire) except OSError as exception: if exception.errno != errno.EEXIST: raise # creating file path for both image and text file output if module == "ALL": output_path_dire_txt = os.path.join(cwd, "PSQS", 'Per_sequence_quality_scores.txt') output_path_dire_img = os.path.join(cwd, "PSQS", 'Per_sequence_quality_scores.png') else: output_path_dire_txt = os.path.join(cwd, output_dire, 'Per_sequence_quality_scores.txt') output_path_dire_img = os.path.join(cwd, output_dire, 'Per_sequence_quality_scores.png') data.insert(0,head)#insert header before writing fw = open(output_path_dire_txt, 'w' ) fw.write("\n".join(data)) fw.close() fastqc_data.close() #load per sequence quality scores data to numpy dataframe df = np.loadtxt(data, dtype='float', usecols = [0,1], skiprows=2) df1 = pd.DataFrame(df, columns= ['Quality', 'Count']) quality =df1.iloc[:,0] count = df1.iloc[:,1] count = count.astype('int64') plt.figure(figsize=(20,10)) plt.plot(quality,count, c = 'b') plt.xticks(np.arange(0, int(max(quality)+ 2))) plt.grid(which='major', linestyle='--', linewidth='0.5', color='green') plt.title('Quality score distribution over all sequences') plt.xlabel("Mean Sequence Quality (Phred Score)") ax=plt.gca() ax.ticklabel_format(axis='y', style='plain', scilimits=(0,0), useOffset=None, useLocale=None, useMathText=None) plt.savefig(output_path_dire_img, format='png', dpi=300) plt.draw() #plt.show() plt.close() return data
5,345,782
def make_lfd_settings_package(lfd_settings_name): """ Makes the lfd_settings package. Makes the lfd_settings package with settings.py files with the same subpackage and module structure as the lfd package. Only makes subpackages and modules for which the corresponding one in the lfd package has a settings.py file. """ lfd_name = os.path.dirname(lfd.__file__) make_settings_tree(lfd_name, lfd_settings_name)
5,345,783
def import_manager(inputs=None, import_type=None, **kwargs): """ This module manages import of the device(s) :param inputs: (dict) A dictionary of user provided inputs :param import_type: (str) device import type "single" or "bulk" :param kwargs: (kwargs) Key value pair :returns: (str) import status """ populate_config() # ==================== SINGLE DEVICE IMPORT ======================================== if import_type == "single": click.secho(f"[!] Attention: ", fg="yellow", nl=False) click.secho(f"Claiming single device does not support ", nl=False, fg="red") click.secho(f"day0 template configurations!", fg="red") if click.confirm(text=f"[-] Proceed?", abort=True): import_single_device(configs=dnac_configs, data=inputs) # =================== IMPORT IN BULK ============================================== elif import_type == "bulk": if "device_catalog" not in kwargs: device_catalog_dir = os.path.join( all_configs["common"]["base_directory"], "catalog" ) device_catalog_file = os.path.join(device_catalog_dir, "DeviceImport.csv") click.secho( f"[*] Looking for device catalog file in [{device_catalog_file}].....", fg="cyan", ) else: device_catalog_file = kwargs.get("device_catalog") device_import_in_bulk(configs=dnac_configs, import_file=device_catalog_file) else: click.secho(f"Invalid import type!", fg="red") sys.exit(1)
5,345,784
def count_primes(num): """ Write a function that returns the number of prime numbers that exist up to and including a given number :param num: int :return: int """ count = 0 lower = int(input()) upper = int(input()) for num in range(lower, upper + 1): if num > 1: for i in range(2, num): if (num % i) == 0: break else: count += 1 return count
5,345,785
def get_redis() -> Iterator[Redis]: """获取redis操作对象 每一个请求处理完毕后会关闭当前连接,不同的请求使用不同的连接 """ # 检查间隔(health_check_interval)的含义: # 当连接在health_check_interval秒内没有使用下次使用时需要进行健康检查。 # 在内部是通过发送ping命令来实现 r = Redis(connection_pool=_redis_pool, health_check_interval=30) try: yield r finally: r.close()
5,345,786
def run_experiment(config): """ Run the experiment. Args: config: The configuration dictionary. Returns: The experiment result. """ return None
5,345,787
def read_notification(notification_id): """Marks a notification as read.""" notification = Notification.query.get_or_404(notification_id) if notification.recipient_email != current_user.email: abort(401) notification.is_read = True db.session.add(notification) db.session.commit() return NO_PAYLOAD
5,345,788
def grayscale_blur(image): """ Convert image to gray and blur it. """ image_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY) image_gray = cv.blur(image_gray, (3, 3)) return image_gray
5,345,789
def calculate_stream_hmac(stream, hmac_key): """Calculate a stream's HMAC code with the given key.""" stream.seek(0) hash_hmac = hmac.new(bytearray(hmac_key, "utf-8"), digestmod=HASH_FUNCTION) while True: buf = stream.read(4096) if not buf: break hash_hmac.update(buf) return hash_hmac.hexdigest()
5,345,790
def find(name, dir_path="." , p="r"): """ find(name: string, dirpath="." , p="r") name: the name to find dirpath: find in this directory p = r recursive find sub dirs """ files = ls(dir_path, p) ans = [] for fn in files: head, tail = os.path.split(fn) dis = normal_leven(tail, name) ans.append((dis, fn)) ans.sort() ans = ans[0:5] if len(ans) > 0 and ans[0][0] == 0: return [ans[0][1]] return list(map(lambda x:x[1], ans))
5,345,791
def test_bad_file(): """Dies on bad file""" bad = random_string() rv, out = getstatusoutput(f'{prg} -f {bad}') assert rv != 0 assert re.search(f"No such file or directory: '{bad}'", out)
5,345,792
def convert_tac(ThreeAddressCode): """Reads three adress code generated from parser and converts to TAC for codegen; generates the three_addr_code along with leaders; populates generate symbol table as per three_addr_code""" for i in range(ThreeAddressCode.length()): three_addr_instr = ThreeAddressCode.code[i] three_addr_instr = [str(i+1)] + three_addr_instr three_addr_code.add_line(three_addr_instr) if len(three_addr_instr) != 5: print("Incorrect size for the following instruction: ") print(three_addr_instr) return -1 if three_addr_instr[0] == '': print("Line number not given in the following instruction: ") print(three_addr_instr) return -1 import re if re.search(r'\D', three_addr_instr[0]) != None: print("Invalid line number given in the following instruction: ") print(three_addr_instr) return -1 leader_generating_if_instr = [] leader_generating_if_instr += ['ifgotoeq'] leader_generating_if_instr += ['ifgotoneq'] leader_generating_if_instr += ['ifgotolt'] leader_generating_if_instr += ['ifgotolteq'] leader_generating_if_instr += ['ifgotogt'] leader_generating_if_instr += ['ifgotogteq'] if three_addr_instr[1] in leader_generating_if_instr: three_addr_code.add_leader(three_addr_code.length()) leader_generating_other_instr = ['label'] if three_addr_instr[1] in leader_generating_if_instr: three_addr_code.add_leader(three_addr_code.length()-1) leader_generating_other_instr = [] leader_generating_other_instr += ['goto'] leader_generating_other_instr += ['break'] leader_generating_other_instr += ['continue'] if three_addr_instr[1] in leader_generating_other_instr: three_addr_code.add_leader(three_addr_code.length()) three_addr_code.leaders = sorted(three_addr_code.leaders, key=int) return three_addr_code
5,345,793
def is_english_score(bigrams, word): """Calculate the score of a word.""" prob = 1 for w1, w2 in zip("!" + word, word + "!"): bigram = f"{w1}{w2}" if bigram in bigrams: prob *= bigrams[bigram] # / float(bigrams['total'] + 1) else: print("%s not found" % bigram) prob *= 1 # / float(bigrams['total'] + 1) return prob
5,345,794
def modify_logistic_circuit(): """ Preprocess new format to remove v_tree id """ with open('../benchmarks/mnist.circuit_985', 'r') as f: lines= f.readlines() lines_m=[] for idx, i in enumerate(lines): if i[0] == 'T' or i[0] == 'F' or i[0] == 'D': i= i.split(' ') del i[2] seperator= ' ' i = seperator.join(i) lines_m.append(i) with open('../benchmarks/mnist_985.txt', 'w+') as f: f.writelines(lines_m)
5,345,795
def cat(fname, fallback=_DEFAULT, binary=True): """Return file content. fallback: the value returned in case the file does not exist or cannot be read binary: whether to open the file in binary or text mode. """ try: with open_binary(fname) if binary else open_text(fname) as f: return f.read().strip() except IOError: if fallback != _DEFAULT: return fallback raise
5,345,796
def _get_from_url(url): """ Note: url is in format like this(following OQMD RESTful API) and the result format should be set to json: http://oqmd.org/oqmdapi/formationenergy?fields=name,entry_id,delta_e&filter=stability=0&format=json Namely url should be in the form supported by OQMD RESTful API """ os.system("mkdir -p /tmp/pymatflow/third") #os.system("wget \"%s\" -O /tmp/pymatflow/third/oqmd_restful_api_results.json" % (url)) #os.system("curl \"%s\" -Lo /tmp/pymatflow/third/oqmd_restful_api_results.json" % (url)) # silent output of curl os.system("curl \"%s\" -s -Lo /tmp/pymatflow/third/oqmd_restful_api_results.json" % (url)) with open("/tmp/pymatflow/third/oqmd_restful_api_results.json", 'r') as fin: out = json.loads(fin.read()) return out
5,345,797
def createStringObject(string): """ Given a string (either a ``str`` or ``unicode``), create a :class:`ByteStringObject<ByteStringObject>` or a :class:`TextStringObject<TextStringObject>` to represent the string. """ if isinstance(string, string_type): return TextStringObject(string) elif isinstance(string, bytes_type): try: if string.startswith(codecs.BOM_UTF16_BE): retval = TextStringObject(string.decode("utf-16")) retval.autodetect_utf16 = True return retval else: # This is probably a big performance hit here, but we need to # convert string objects into the text/unicode-aware version if # possible... and the only way to check if that's possible is # to try. Some strings are strings, some are just byte arrays. retval = TextStringObject(decodePdfDocEncoding(string)) retval.autodetect_pdfdocencoding = True return retval except UnicodeDecodeError: return ByteStringObject(string) else: raise TypeError("createStringObject() should have str or unicode arg")
5,345,798
def _get_windows_network_adapters(): """Get the list of windows network adapters.""" import win32com.client wbem_locator = win32com.client.Dispatch('WbemScripting.SWbemLocator') wbem_service = wbem_locator.ConnectServer('.', 'root\cimv2') wbem_network_adapters = wbem_service.InstancesOf('Win32_NetworkAdapter') network_adapters = [] for adapter in wbem_network_adapters: if (adapter.NetConnectionStatus == 2 or adapter.NetConnectionStatus == 7): adapter_name = adapter.NetConnectionID mac_address = adapter.MacAddress.lower() config = adapter.associators_( 'Win32_NetworkAdapterSetting', 'Win32_NetworkAdapterConfiguration')[0] ip_address = '' subnet_mask = '' if config.IPEnabled: ip_address = config.IPAddress[0] subnet_mask = config.IPSubnet[0] #config.DefaultIPGateway[0] network_adapters.append({'name': adapter_name, 'mac-address': mac_address, 'ip-address': ip_address, 'subnet-mask': subnet_mask}) return network_adapters
5,345,799