content
stringlengths
22
815k
id
int64
0
4.91M
def rand_email(domain=None): """Generate a random zone name :return: a random zone name e.g. example.org. :rtype: string """ domain = domain or rand_zone_name() return 'example@%s' % domain.rstrip('.')
5,358,000
def wordcount_for_reddit(data, search_word): """Return the number of times a word has been used.""" count = 0 for result in data: # do something which each result from scrape for key in result: stringed_list = str(result[key]) text_list = stringed_list.split() fo...
5,358,001
def openeo_to_eodatareaders(process_graph_json_in: Union[dict, str], job_data: str, process_defs: Union[dict, list, str], vrt_only: bool = False, existing_node_ids: List[Tuple] = None) \ -> Tuple[List[Tuple[str, List[str], Optional[str], List[str], str]],...
5,358,002
def main(): """ This function is executed automatically when the module is run directly. """ hats = [] # Define the channel list for each HAT device chans = [ {0, 1}, {0, 1} ] # Define the options for each HAT device options = [ OptionFlags.EXTTRIGGER, ...
5,358,003
def calc_precision(gnd_assignments, pred_assignments): """ gnd_clusters should be a torch tensor of longs, containing the assignment to each cluster assumes that cluster assignments are 0-based, and no 'holes' """ precision_sum = 0 assert len(gnd_assignments.size()) == 1 assert len(pred...
5,358,004
def scheduler_job_output_route(): """receive output from assigned job""" try: jsonschema.validate(request.json, schema=sner.agent.protocol.output) job_id = request.json['id'] retval = request.json['retval'] output = base64.b64decode(request.json['output']) except (jsonschema...
5,358,005
def __get_app_package_path(package_type, app_or_model_class): """ :param package_type: :return: """ models_path = [] found = False if isinstance(app_or_model_class, str): app_path_str = app_or_model_class elif hasattr(app_or_model_class, '__module__'): app_path_str = ap...
5,358,006
def generate_colors(history, config): """ This is some old code to generate colors for the ray plotting in _add_ray_history. For the moment I am just saving the old code here, but this will not work with the new history dictionary. (Only minor adjustments are neccessary to make it work, but th...
5,358,007
def dict_from_payload(base64_input: str, fport: int = None): """ Decodes a base64-encoded binary payload into JSON. Parameters ---------- base64_input : str Base64-encoded binary payload fport: int FPort as provided in the metad...
5,358,008
def pack(circles, x, y, padding=2, exclude=[]): """ Circle-packing algorithm. Groups the given list of Circle objects around (x,y) in an organic way. """ # Ported from Sean McCullough's Processing code: # http://www.cricketschirping.com/processing/CirclePacking1/ # See also: http://en.wiki.m...
5,358,009
def test_call_bluesky(daq): """ These are things that bluesky uses. Let's check them. """ logger.debug('test_call_bluesky') daq.describe() daq.describe_configuration() daq.stage() daq.begin(duration=10) # unstage should end the run and we don't time out daq.unstage()
5,358,010
def handle(req): """POST""" im = Image.open(BytesIO(req.files[list(req.files.keys())[0]].body)) w, h = im.size im2 = ImageOps.mirror(im.crop((0, 0, w / 2, h))) im.paste(im2, (int(w / 2), 0)) io = BytesIO() im.save(io, format='PNG') return req.Response( body=io.getvalue(), mime_...
5,358,011
def read_sachs_all(folder_path): """Reads all the sachs data specified in the folder_path. Args: folder_path: str specifying the folder containing the sachs data Returns: An np.array containing all the sachs data """ sachs_data = list() # Divides the Sachs dataset into environments. for _, fil...
5,358,012
def test_axes_map(): """ map from Axes([aaa, bbb]) to Axes([zzz, bbb]) via AxesMap {aaa: zzz} """ a = ng.make_axis(1, name='aaa') b = ng.make_axis(2, name='bbb') z = ng.make_axis(1, name='zzz') axes_before = ng.make_axes([a, b]) axes_after = ng.make_axes([z, b]) axes_map = AxesMap(...
5,358,013
def populate_job_directories(): """ -function to populate or update job directory tree with job scripts that are located in /Setup_and_Config """ JobStreams, Replicates, BaseDirNames, JobBaseNames, Runs, \ nJobStreams, nReplicates, nBaseNames = check_job_structure() mcf = rea...
5,358,014
def user_permitted_tree(user): """Generate a dictionary of the representing a folder tree composed of the elements the user is allowed to acccess. """ # Init user_tree = {} # Dynamically collect permission to avoid hardcoding # Note: Any permission to an element is the same as read permiss...
5,358,015
def upgrade(): """ Run upgrade """ # ### commands auto generated by Alembic - please adjust! ### op.drop_index('ix_domain_proxy_logs_cbsd_serial_number', table_name='domain_proxy_logs') op.drop_index('ix_domain_proxy_logs_created_date', table_name='domain_proxy_logs') op.drop_index('ix_domai...
5,358,016
def __save_roc(y_true, y_pred, output_dir): """ Creates an ROC curve with AUC for the model :param y_true: The actual phenotypes for the test data :param y_pred: The predicted phenotypes for the test data :param output_dir: The directory to save the ROC curve in """ fpr, tpr, thresholds = ro...
5,358,017
def extract_failure(d): """ Returns the failure object the given deferred was errback'ed with. If the deferred has result, not a failure a `ValueError` is raised. If the deferred has no result yet a :class:`NotCalledError` is raised. """ if not has_result(d): raise NotCalledError() e...
5,358,018
def convert_where_clause(clause: dict) -> str: """ Convert a dictionary of clauses to a string for use in a query Parameters ---------- clause : dict Dictionary of clauses Returns ------- str A string representation of the clauses """ out = "{" for key in c...
5,358,019
def updatereqs(): """Update services using requirements.txt and requirements.sh""" commands.updatereqs()
5,358,020
def clear(): """ Deletes the cache. """ cprint('Clearing cache', 'yellow') shutil.rmtree(_cache_path, ignore_errors=True)
5,358,021
def all_metadata_async(): """Retrieves all available metadata for an instance async""" loop = trollius.get_event_loop() res = loop.run_until_complete(call()) return res
5,358,022
def median_std_from_ma(data: np.ma, axis=0): """On the assumption that there are bit-flips in the *data*, attempt to find a value that might represent the standard deviation of the 'real' data. The *data* object must be a numpy masked array. The value of *axis* determines which way the data are ha...
5,358,023
def __check_value_range(x: int) -> bool: """ Checks if integer is in valid value range to be a coordinate for Tic-Tac-Toe. """ if x < 1 or x > 3: print(__standard_error_text + "Coordinates have to be between 1 and 3.\n") return False return True
5,358,024
def find_option(opt): """ This function checks for option defined with optcode; it could be implemented differently - by checking entries in world.cliopts """ # received msg from client must not be changed - make a copy of it tmp = world.climsg[world.clntCounter].copy() # 0 - ether, 1 - ipv...
5,358,025
def generic_add_model_components( m, d, reserve_zone_param, reserve_zone_set, reserve_generator_set, generator_reserve_provision_variable, total_reserve_provision_expression, ): """ Generic treatment of reserves. This function creates model components related to a particular rese...
5,358,026
def return_all_content(content): """Help function to return untruncated stripped content.""" return mark_safe(str(content).replace('><', '> <')) if content else None
5,358,027
def get_trailing_returns(uid): """ Get trailing return chart """ connection = pymysql.connect(host=DB_SRV, user=DB_USR, password=DB_PWD, db=DB_NAME, charset='utf8mb4', ...
5,358,028
def bitsNotSet(bitmask, maskbits): """ Given a bitmask, returns True where any of maskbits are set and False otherwise. Parameters ---------- bitmask : ndarray Input bitmask. maskbits : ndarray Bits to check if set in the bitmask """ goodLocs...
5,358,029
def plot(foo, x, y): """x, y are tuples of 3 values: xmin, xmax, xnum""" np_foo = np.vectorize(foo) x_space = np.linspace(*x) y_space = np.linspace(*y) xx, yy = np.meshgrid(x_space, y_space) xx = xx.flatten() yy = yy.flatten() zz = np_foo(xx, yy) num_x = x[-1] num_y = y[-1] p...
5,358,030
def _StructPackEncoder(wire_type, format): """Return a constructor for an encoder for a fixed-width field. Args: wire_type: The field's wire type, for encoding tags. format: The format string to pass to struct.pack(). """ value_size = struct.calcsize(format) def SpecificEncoder(field_number, ...
5,358,031
def transition_temperature(wavelength): """ To get temperature of the transition in K Wavelength in micros T = h*f / kB """ w = u.Quantity(wavelength, u.um) l = w.to(u.m) c = _si.c.to(u.m / u.s) h = _si.h.to(u.eV * u.s) kb = _si.k_B.to(u.eV / u.K) f = c/l t = h*f/kb r...
5,358,032
def truncate_string(string: str, max_length: int) -> str: """ Truncate a string to a specified maximum length. :param string: String to truncate. :param max_length: Maximum length of the output string. :return: Possibly shortened string. """ if len(string) <= max_length: return strin...
5,358,033
def geoinfo_from_ip(ip: str) -> dict: # pylint: disable=invalid-name """Looks up the geolocation of an IP address using ipinfo.io Example ipinfo output: { "ip": "1.1.1.1", "hostname": "one.one.one.one", "anycast": true, "city": "Miami", "region": "Florida", "country": "...
5,358,034
async def test_camera_image( hass: HomeAssistant, mock_entry: MockEntityFixture, simple_camera: tuple[Camera, str], ): """Test retrieving camera image.""" mock_entry.api.get_camera_snapshot = AsyncMock() await async_get_image(hass, simple_camera[1]) mock_entry.api.get_camera_snapshot.asser...
5,358,035
def mpileup2acgt(pileup, quality, depth, reference, qlimit=53, noend=False, nostart=False): """ This function was written by Francesco Favero, from: sequenza-utils pileup2acgt URL: https://bitbucket.org/sequenza_tools/sequenza-utils original code were protected under GPLv3 license...
5,358,036
def normalize_missing(xs): """Normalize missing values to avoid string 'None' inputs. """ if isinstance(xs, dict): for k, v in xs.items(): xs[k] = normalize_missing(v) elif isinstance(xs, (list, tuple)): xs = [normalize_missing(x) for x in xs] elif isinstance(xs, basestri...
5,358,037
def ensure_command_line_tools_are_installed(command): """ Determine if the Xcode command line tools are installed. If they are not installed, an exception is raised; in addition, a OS dialog will be displayed prompting the user to install Xcode. :param command: The command that needs to perform th...
5,358,038
def ini_inventory(nhosts=10): """Return a .INI representation of inventory""" output = list() inv_list = generate_inventory(nhosts) for group in inv_list.keys(): if group == '_meta': continue # output host groups output.append('[%s]' % group) for host in inv...
5,358,039
def get_invalid_bunny_revival_dungeons(): """ Dungeon regions that can't be bunny revived from without superbunny state. """ yield 'Tower of Hera (Bottom)' yield 'Swamp Palace (Entrance)' yield 'Turtle Rock (Entrance)' yield 'Sanctuary'
5,358,040
def get_crp_constrained_partition_counts(Z, Cd): """Compute effective counts at each table given dependence constraints. Z is a dictionary mapping customer to table, and Cd is a list of lists encoding the dependence constraints. """ # Compute the effective partition. counts = defaultdict(int) ...
5,358,041
def create_doc(): """Test basic layer creation and node creation.""" # Stupid tokenizer tokenizer = re.compile(r"[a-zA-Z]+|[0-9]+|[^\s]") doc = Document() main_text = doc.add_text("main", "This code was written in Lund, Sweden.") # 0123456789012345678901234567890...
5,358,042
def jissue_get_chunked(jira_in, project, issue_max_count, chunks=100): """ This method is used to get the issue list with references, in case the number of issues is more than 1000 """ result = [] # step and rest simple calc step = issue_max_count / chunks rest = issue_max_count %...
5,358,043
def negative_height_check(height): """Check the height return modified if negative.""" if height > 0x7FFFFFFF: return height - 4294967296 return height
5,358,044
def turn_off_plotting(namespace=globals()): """Call turn_off_plotting(globals()) to turn off all plotting.""" use(namespace['plt'], namespace, True)
5,358,045
def test_basic_parse(): """Test parsing a basic expression.""" instructions = parse(tokenise('obj allow user edit')) assert len(instructions) == 1 assert instructions == [('obj', 'allow', 'user', 'edit')]
5,358,046
def main(): """ Main function """ args=get_args() file_args = args.file print(args.num) if args.num: file_num = args.num else: file_num=10 for fh in file_args: num_lines = 0 print(f"{fh.name}") for line in fh: y = fh.readline() ...
5,358,047
def get_visemenet(model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create VisemeNet model with specific parameters. Parameters: ---------- model_name : str or None, default None Model nam...
5,358,048
def linked_gallery_view(request, obj_uuid): """ View For Permalinks """ gallery = get_object_or_404(Gallery, uuid=obj_uuid) images = gallery.images.all().order_by(*gallery.display_sort_string) paginator = Paginator(images, gallery.gallery_pagination_count) page = request.GET.get('page') ...
5,358,049
def _gm_cluster_assign_id(gm_list, track_id, num_tracks, weight_threshold, z_dim, max_id, max_iteration=1000): """The cluster algorithm that assign a new ID to the track Args: gm_list (:obj:`list`): List of ``GaussianComponent`` representing current multi-target PH...
5,358,050
def get_bprop_scatter_nd(self): """Generate bprop for ScatterNd""" op = P.GatherNd() def bprop(indices, x, shape, out, dout): return zeros_like(indices), op(dout, indices), zeros_like(shape) return bprop
5,358,051
def myHullNumber() -> int: """ะ’ะพะทะฒั€ะฐั‰ะฐะตั‚ ะฑะพั€ั‚ะพะฒะพะน ะฝะพะผะตั€ ั€ะพะฑะพั‚ะฐ."""
5,358,052
def dates(bot, mask, target, args): """Show the planned dates within the next days %%dates """ config = dates_configuration(bot) now = datetime.utcnow().replace(hour=0, minute=0, second=0, ...
5,358,053
def progress_update_r(**kwargs): """ Receiver to update a progressbar """ index = kwargs.get('index') if index: update_pbar(index)
5,358,054
def get_md5(location: str, ignore_hidden_files: bool=True) -> Optional[str]: """ Gets an MD5 checksum of the file or directory at the given location. :param location: location of file or directory :param ignore_hidden_files: whether hidden files should be ignored when calculating an checksum for a direc...
5,358,055
def set_output_image_folder(folder: str) -> None: """ Service that sets up the location of image output folder :param folder: location to set :return: None """ config_main.APPL_SAVE_LOCATION = folder log_setup_info_to_console('IMAGE FOLDER OUTPUT:{}'.format(os.path.join(os.getcwd(), config_...
5,358,056
def delete_policy_rule(policy_key, key, access_token): """ Deletes a policy rule with the given key. Returns the response JSON. See http://localhost:8080/docs#/Policy/delete_rule_api_v1_policy__policy_key__rule__rule_key__delete """ return requests.delete( f"{FIDESOPS_URL}/api/v1/polic...
5,358,057
def knn_search_parallel(data, K, qin=None, qout=None, tree=None, t0=None, eps=None, leafsize=None, copy_data=False): """ find the K nearest neighbours for data points in data, using an O(n log n) kd-tree, exploiting all logical processors on the computer. if eps <= 0, it returns the distance to the ...
5,358,058
def find_absolute_reference( target: str, domain: str, remote_url: urllib.parse.ParseResult, https_mode: _constants.HTTPSMode = _constants.DEFAULT_HTTPS_MODE, base: typing.Optional[urllib.parse.ParseResult] = None ) -> typing.Optional[str]: """ Transform the partly define...
5,358,059
def compute_vectors_from_coordinates( x: np.ndarray, y: np.ndarray, fps: int = 1 ) -> Tuple[Vector, Vector, Vector, Vector, np.array]: """ Given the X and Y position at each frame - Compute vectors: i. velocity vector ii. unit tangent iii. unit norm ...
5,358,060
def get_now(pair): """ Return last info for crypto currency pair :param pair: ex: btc-ltc :return: """ info = {'marketName': pair, 'tickInterval': 'oneMin'} return requests.get('https://bittrex.com/Api/v2.0/pub/market/GetLatestTick', params=info).json()
5,358,061
def resize_and_convert_images_to_png(): """ For each file in the folders: Convert to a .PNG file, preserve file size Label it something computer-processable """ print("Running resize_and_convert_images_to_png()") current_directory = './Deep Learning Plant Classifier' # first p...
5,358,062
def fixture_buildchain_template_context() -> Any: """Emulate .in template context for buildchain.""" buildchain_path = paths.REPO_ROOT / "buildchain" sys.path.insert(0, str(buildchain_path)) # pylint: disable=import-error,import-outside-toplevel from buildchain import versions # pylint: enable=...
5,358,063
def test_no_optional_attrs(): """Test loading DAG with no optional attributes.""" obj = OptionalAttrs("go-basic.obo", None) obj.chk_no_optattrs() obj = OptionalAttrs("go-basic.obo", []) obj.chk_no_optattrs() obj = OptionalAttrs("go-basic.obo", set([])) obj.chk_no_optattrs()
5,358,064
def hsv(h: float, s: float, v: float) -> int: """Convert HSV to RGB. :param h: Hue (0.0 to 1.0) :param s: Saturation (0.0 to 1.0) :param v: Value (0.0 to 1.0) """ return 0xFFFF
5,358,065
def transform2json(source, target): """ Transform bahaviors file in tsv to json for later evaluation Args: TODO source: target: """ behaviors = pd.read_table( source, header=None, names=['uid', 'time', 'clicked_news', 'impression']) f = open(target...
5,358,066
def make_exponential_mask(img, locations, radius, alpha, INbreast=False): """Creating exponential proximity function mask. Args: img (np.array, 2-dim): the image, only it's size is important locations (np.array, 2-dim): array should be (n_locs x 2) in size and each row should corres...
5,358,067
def loadTileSources(entryPointName='large_image.source', sourceDict=AvailableTileSources): """ Load all tilesources from entrypoints and add them to the AvailableTileSources dictionary. :param entryPointName: the name of the entry points to load. :param sourceDict: a dictionary to populate with the...
5,358,068
def delete(client, url: str, payload: dict) -> Tuple[dict, bool]: """Make DELETE requests to K8s (see `k8s_request`).""" resp, code = request(client, 'DELETE', url, payload, headers=None) err = (code not in (200, 202)) if err: logit.error(f"{code} - DELETE - {url} - {resp}") return (resp, er...
5,358,069
def f(x): """The objective is defined as the cost + a per-demographic penalty for each demographic not reached.""" n = len(x) assert n == n_venues reached = np.zeros(n_demographics, dtype=int) cost = 0.0 for xi, ri, ci in zip(x, r, c): if xi: reached = reached | ri # ...
5,358,070
def clamp(minVal, val, maxVal): """Clamp a `val` to be no lower than `minVal`, and no higher than `maxVal`.""" return max(minVal, min(maxVal, val))
5,358,071
def _remove_discussion_tab(course, user_id): """ Remove the discussion tab for the course. user_id is passed to the modulestore as the editor of the xblock. """ course.tabs = [tab for tab in course.tabs if not tab.type == 'discussion'] modulestore().update_item(course, user_id)
5,358,072
def generate_primes(start): """ generate primes in increasing order, starting from the number start. >>> generator = generate_primes(2) >>> [generator.next() for _ in xrange(10)] # first 10 primes [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] >>> generator = generate_primes(100) >>> # first 10 prim...
5,358,073
def get_closest_spot( lat: float, lng: float, area: config.Area ) -> t.Optional[config.Spot]: """Return closest spot if image taken within 100 m""" if not area.spots: return None distances = [ (great_circle((spot.lat, spot.lng), (lat, lng)).meters, spot) for spot in area.spots ...
5,358,074
def drawBezier( page: Page, p1: point_like, p2: point_like, p3: point_like, p4: point_like, color: OptSeq = None, fill: OptSeq = None, dashes: OptStr = None, width: float = 1, morph: OptStr = None, closePath: bool = False, lineCap: int = 0, lineJoin: int = 0, over...
5,358,075
def product(numbers): """Return the product of the numbers. >>> product([1,2,3,4]) 24 """ return reduce(operator.mul, numbers, 1)
5,358,076
def load_ref_system(): """ Returns l-phenylalanine as found in the IQMol fragment library. All credit to https://github.com/nutjunkie/IQmol """ return psr.make_system(""" N 0.7060 -1.9967 -0.0757 C 1.1211 -0.6335 -0.4814 C 0.6291 0.4897 ...
5,358,077
def parse_dependency_file(filename): """Parse a data file containing dependencies. The input file is the following csv format: name,minerals,gas,build time,dependencies command center,400,0,100, orbital command,150,0,35,command center|barracks Notice that the "dependencies" column...
5,358,078
def main(): """ there are four cubes with concrete colors on their sides and the goal is to place each cube in one row that way that along the row each side presents four different colors """ # ----------- ----------- ----------- ----------- ----------- ----------- # ...
5,358,079
def range_with_bounds(start: int, stop: int, interval: int) -> List[int]: """Return list""" result = [int(val) for val in range(start, stop, interval)] if not isclose(result[-1], stop): result.append(stop) return result
5,358,080
def insert(cursor, name, value): """ Insert data into CrateDB with a current timestamp. """ cursor.execute("""INSERT INTO sensordata (ts, name, value) VALUES (?, ?, ?)""", (timestamp_ms(), name, value))
5,358,081
def iou_score(box1, box2): """Returns the Intersection-over-Union score, defined as the area of the intersection divided by the intersection over the union of the two bounding boxes. This measure is symmetric. Args: box1: The coordinates for box 1 as a list of points box2: The coordinat...
5,358,082
def _actually_on_chip(ra, dec, obs_md): """ Take a numpy array of RA in degrees, a numpy array of Decin degrees and an ObservationMetaData and return a boolean array indicating which of the objects are actually on a chip and which are not """ out_arr = np.array([False]*len(ra)) d_ang = 2.11 ...
5,358,083
def outlier_dataset(seed=None) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: """Generates Outliers dataset, containing 10'000 inliers and 50 outliers Args: seed: random seed for generating points Returns: Tuple containing the inlier features, inlier labels, outlier ...
5,358,084
def posts(request, payload={}, short_id=None): """ Posts endpoint of the example.com public api Request with an id parameter: /public_api/posts/1qkx8 POST JSON in the following format: POST /public_api/posts/ {"ids":["1qkx8","ma6fz"]} """ Metrics.api_comment.record(re...
5,358,085
def compute_bleu(reference_corpus, translation_corpus, max_order=4, smooth=False): """Computes BLEU score of translated segments against one or more references. Args: reference_corpus: list of lists of references for each translation. Each ...
5,358,086
def rf_agg_local_mean(tile_col): """Compute the cellwise/local mean operation between Tiles in a column.""" return _apply_column_function('rf_agg_local_mean', tile_col)
5,358,087
def Shot(project, name): """ ์ƒท ์ •๋ณด๋ฅผ ๊ฐ€์ง€๊ณ  ์˜ค๋Š” ํ•จ์ˆ˜. (๋”•์…”๋„ˆ๋ฆฌ, err)๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค. """ restURL = "http://10.0.90.251/api/shot?project=%s&name=%s" % (project, name) try: data = json.load(urllib2.urlopen(restURL)) except: return {}, "RestAPI์— ์—ฐ๊ฒฐํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค." if "error" in data: return {}, data["error"] return data["data"], No...
5,358,088
def inversion_double(in_array): """ Get the input boolean array along with its element-wise logical not beside it. For error correction. >>> inversion_double(np.array([1,0,1,1,1,0,0,1], dtype=np.bool)) array([[ True, False, True, True, True, False, False, True], [False, True, False, Fal...
5,358,089
def query_to_csv(engine, host, user, port, password, database, query, headers=False, out_type='stdout', destination_file=None, delimiter=',', quotechar='"', print_info=1000): """ Run a query and store the result to a CSV file """ # Get SQL connection connection = get_connection( engine=engine, ...
5,358,090
def test_list_roles(requests_mock): """ Tests synapse-list-users command function. """ from Synapse import Client, list_roles_command mock_response = util_load_json('test_data/list_roles.json') requests_mock.get('https://test.com/api/v1/auth/roles', json=mock_response) mock_roles = util_loa...
5,358,091
def test_expands_blank_panes(): """Expand blank config into full form. Handle ``NoneType`` and 'blank':: # nothing, None, 'blank' 'panes': [ None, 'blank' ] # should be blank 'panes': [ 'shell_command': [] ] Blank strings:: panes: [ ''...
5,358,092
def solution(N): """ This is a fairly simple task. What we need to do is: 1. Get string representation in binary form (I love formatted string literals) 2. Measure biggest gap of zeroes (pretty self explanatory) """ # get binary representation of number binary_repr = f"{N:b}" # in...
5,358,093
def version(verbose: bool = False) -> None: """Show version information""" if not verbose: console.print(idom.__version__) else: table = Table() table.add_column("Package") table.add_column("Version") table.add_column("Language") table.add_row("idom", str(id...
5,358,094
def distributed_compute_expectations( building_blocks: Tuple[cw.ComplexDeviceArray], operating_axes: Tuple[Tuple[int]], pbaxisums: Tuple[Tuple[cw.ComplexDeviceArray]], pbaxisums_operating_axes: Tuple[Tuple[Tuple[int]]], pbaxisum_coeffs: Tuple[Tuple[float]], num_discretes: int, ) -> ShardedDevice...
5,358,095
def write_to_pubsub(data): """ :param data: :return: """ try: if data["lang"] == "en": publisher.publish(topic_path, data=json.dumps({ "text": data["text"], "user_id": data["user_id"], "id": data["id"], "posted_at":...
5,358,096
def extractStudents(filename): """ Pre: The list in xls file is not empty Post: All students are extract from file Returns students list """ list = [] try: # open Excel file wb = xlrd.open_workbook(str(filename)) except IOError: print ("Oops...
5,358,097
def dmenu_select(num_lines, prompt="Entries", inp=""): """Call dmenu and return the selected entry Args: num_lines - number of lines to display prompt - prompt to show inp - bytes string to pass to dmenu via STDIN Returns: sel - string """ cmd = dmenu_cmd(num_lines, prompt) ...
5,358,098
def clean_ip(ip): """ Cleans the ip address up, useful for removing leading zeros, e.g.:: 1234:0:01:02:: -> 1234:0:1:2:: 1234:0000:0000:0000:0000:0000:0000:000A -> 1234::a 1234:0000:0000:0000:0001:0000:0000:0000 -> 1234:0:0:0:1:: 0000:0000:0000:0000:0001:0000:0000:0000 -> ::1:0:...
5,358,099