content
stringlengths
22
815k
id
int64
0
4.91M
def xxyy_basis_rotation(pairs, clean_xxyy=False): """Generate the measurement circuits.""" all_ops = [] for a, b in pairs: if clean_xxyy: all_ops += [ cirq.rz(-np.pi * 0.25).on(a), cirq.rz(np.pi * 0.25).on(b), cirq.ISWAP.on(a, b)**0.5 ...
5,321,100
def partitions_class_attribute(data_points, attr_index): """Partitions data points using a given class attribute. Data points with the same class label are combined into a partition. :param data_points: List of tuples representing the data points. :param attr_index: Index of the attribute inside the tup...
5,321,101
def set_crop_to_volume(volume, bb_min, bb_max, sub_volume): """ set a subregion to an nd image. :param volume: volume image :param bb_min: box region minimum :param bb_max: box region maximum : """ dim = len(bb_min) out = volume if(dim == 2): out[np.ix_(range(bb_min[0], b...
5,321,102
def display_image_grid(bounding_pts,image,skip_dilate=True,size = 2.5): """ construct a grid from the padded images and create the entire grid displays the image returns an image and list of all the digit images """ if not skip_dilate: list_digits = [draw_block(i[0],i[1],image.copy(),ski...
5,321,103
def generate_random_name(): """Generate a random name to use as a handle for a job.""" return "".join(random.choice(string.ascii_lowercase) for j in range(8))
5,321,104
def _compile_explicit_relpath(verb): """Decline to map any explicit relpath to verb""" assert ("/" in verb) or ("." in verb) if os.path.exists(verb): how = _compile_log_error( "bash.py: warning: {}: No such file or directory in bash path".format(verb) ) return how ...
5,321,105
def test_qm_2019_sss_6_imported(): """Sample test, will always pass so long as import statement worked""" assert "qm_2019_sss_6" in sys.modules
5,321,106
def get_commands(): """ Returns a list of command names. This works by looking for commands inside crichtoncli.commands. The list is in the format [command_name]. Items from this list can then be used in calls to load_command_class(command_name). The list is cached on the first call a...
5,321,107
def import_skymodel_from_hdf5(filename): """Import a Skymodel from HDF5 format :param filename: :return: SkyModel """ with h5py.File(filename, 'r') as f: ncomponents = f.attrs['number_skycomponents'] components = [convert_hdf_to_skycomponent(f['skycomponent%d' % i]) ...
5,321,108
def _get_initial_ktensor(init, X, rank, random_state, scale_norm=True): """ Parameters ---------- init : str Specifies type of initializations ('randn', 'rand') X : ndarray Tensor that the decomposition is fit to. rank : int Rank of decomposition random_state : Random...
5,321,109
def grabocka_params_to_shapelet_size_dict(n_ts, ts_sz, n_classes, l, r): """Compute number and length of shapelets. This function uses the heuristic from [1]_. Parameters ---------- n_ts: int Number of time series in the dataset ts_sz: int Length of time series in the dataset ...
5,321,110
def gslib(FileName, deli=' ', useTab=False, numIgLns=0, pdo=None): """ Description ----------- Reads a GSLIB file format to a vtkTable. The GSLIB file format has headers lines followed by the data as a space delimited ASCI file (this filter is set up to allow you to choose any single character delimiter...
5,321,111
def precision_recall( similarity_melted_df: pd.DataFrame, replicate_groups: List[str], k: int, ) -> pd.DataFrame: """ Determine the precision and recall at k for all unique replicate groups based on a predefined similarity metric (see cytominer_eval.transform.metric_melt) Arguments: similarity_...
5,321,112
def validate_index(n: int, ind: int, command: str): """ Simple function to validate existence of index within in the model repository. Args: n (int): length of indices ind (int): selected index command (str): name of command for "tailored" help message """ # ensure index e...
5,321,113
def search_page(request): """Page with search results.""" def _articles_filter(name): """Delete articles in product names Arguments: name {str} -- Name or generic name of product """ exclude = ("de", "des", "au", "aux", 'en', "le", "la", "les", "e...
5,321,114
def calculate_sa_expected_feature_counts(pi, mdp, epsilon=0.0001): """return dictionary of feature counts associated with each (s,a) pair""" sa_fcounts = dict() #compute feature expectations per state fcounts = calculate_expected_feature_counts(pi, mdp, epsilon) #(s,a) feature expectations are \phi(...
5,321,115
def _copy_data(input_data, output_data): """ Copies the data from output_data[corr_strings] into input_data[element_table]. This function handles that some corr_strings are not in output_data.keys() and copies all columns which exists in both, output_data[corr_strings] and input_data[element_table]....
5,321,116
def _default_filtered_keywords(namespace, attr): """Enable all keywords to be shown by default.""" setattr(namespace, attr, set(objects.KEYWORDS.values()))
5,321,117
def xmlToTag(tag): """The opposite of tagToXML()""" if tag == "OS_2": return "OS/2" if len(tag) == 8: return identifierToTag(tag) else: return tag + " " * (4 - len(tag)) return tag
5,321,118
def translate(num_list, transl_dict): """ Translates integer list to number word list (no error handling!) Args: num_list: list with interger items. transl_dict: dictionary with integer keys and number word values. Returns: list of strings which are the translated numbers into word...
5,321,119
def inject_global(node: Node, global_key: str, inject_key: Any): """Resolves passed dependency and stores it to node's globals""" value = resolve(inject_key) set_global(node, global_key, value)
5,321,120
def _1d_overlap_filter(x, n_h, n_edge, phase, cuda_dict, pad, n_fft): """Do one-dimensional overlap-add FFT FIR filtering.""" # pad to reduce ringing x_ext = _smart_pad(x, (n_edge, n_edge), pad) n_x = len(x_ext) x_filtered = np.zeros_like(x_ext) n_seg = n_fft - n_h + 1 n_segments = int(np.c...
5,321,121
def LED(state): """this is the arduino function that controls how the LED bulb with respect to what the webserver says""" if state == True: arduino.write(b'1') print('the arduino is in the ON state') return True else: arduino.write(b'0') print('the arduino is in the O...
5,321,122
def noise_mean(corr, scale_factor = 1., mode = "corr"): """Computes the scalled mean noise from the correlation data estimator. This is the delta parameter for weighted normalization. Parameters ---------- corr: (ndarray,) Correlation function (or difference function) model. ...
5,321,123
def get_python(uid): """Returns location of virtualenv python binary given UID""" return get_venv_folder(uid) + '/bin/python'
5,321,124
def shap_visuals(modelname, sample, keyrow): """ Parameters ---------- model : string A model with parameters already selected and fit modeltype : string Identificationof pretermined models sample : int The number of values to use in the random sample from X_test key...
5,321,125
def login(): """View of login to the backstage""" if current_user.is_authenticated: return redirect(url_for('admin.index')) form = LoginForm() if form.validate_on_submit(): admin = Administrator.query \ .filter_by(name=form.name.data).first() if admin is not None and...
5,321,126
def vgg_retinanet(num_classes, backbone='vgg16', inputs=None, modifier=None, **kwargs): """ Constructs a retinanet model using a vgg backbone. Args num_classes: Number of classes to predict. backbone: Which backbone to use (one of ('vgg16', 'vgg19')). inputs: The inputs to the network (...
5,321,127
def fetchWorkflowsSpec(config, listOfWfs): """ Fetch the workload of a list of workflows. Filter out only a few usefull keys """ if isinstance(listOfWfs, basestring): listOfWfs = [listOfWfs] wfDBReader = RequestDBReader(config.AnalyticsDataCollector.centralRequestDBURL, ...
5,321,128
def rel_error(x, y): """ Returns relative error """ assert x.shape == y.shape, "tensors do not have the same shape. %s != %s" \ % (x.shape, y.shape) return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))
5,321,129
def wrap_ddp(cls): """Return wrapper class for the torch.DDP and apex. Delegete getattr to the inner module. """ class _Wrap(cls): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def __getattr__(self, name): wrapped_module = super().__getat...
5,321,130
def mortgage_max(buyer_dsr): """ Calculates maximum loan available to offer based on buyer's proposed downpayment and downpayment percent ... Returns ------- loan : float Returns maximum available loan to be offered """ downpayment_percent = 0 min_downpayment = 0 try: ...
5,321,131
def generate_newsletter(cal_dict): """ Given a JSON formatted calendar dictionary, make the text for a fascinating newsletter. """ sorted_items = organize_events_by_day( cal_dict['items'], config.NEWSLETTER_MAX_DAYS, ) # pprint.pprint(sorted_items) template_loader...
5,321,132
def request_api(request, # type: Request path, # type: Str method="GET", # type: Str data=None, # type: Optional[Union[JSON, Str]] headers=None, # type: Optional[HeadersType] cookies=None, ...
5,321,133
def unit_vector(vector): """ Returns the unit vector of the vector. """ div = np_norm(vector) if div == 0.0: return vector return vector / div
5,321,134
def save_files(images): """ Save encoded image to image file on local machine. Image is decoded and saved as JPEG file with UUID name in "imstore" directory. :param images: encoded image string (string) :return: file name of stored image (string) """ import uuid import base64 import...
5,321,135
def _generate_nsa_options(query): """ >>> _generate_nsa_options("NM_000551.3") [('refseq', 'NM_000551.3')] >>> _generate_nsa_options("ENST00000530893.6") [('ensembl', 'ENST00000530893.6')] >>> _generate_nsa_options("gi:123456789") [('gi', '123456789')] >>> _generate_nsa_options("01234...
5,321,136
def feature_evaluation(X: pd.DataFrame, y: pd.Series, output_path: str = ".") -> NoReturn: """ Create scatter plot between each feature and the response. - Plot title specifies feature name - Plot title specifies Pearson Correlation between feature and response - Plot saved under given f...
5,321,137
def close_conn(conn = None, cur = None): """ Close and commit changes of conn """ try: cur.close() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.commit() conn.close() print('Database connec...
5,321,138
def identify_place_type(place_type): """ Identifies the type of the given geoname. It first inferes the type from the metadata file, then identifies using regular expressions. """ if re.search("Lieu", place_type): if re.search("RUE$", place_type): return 11 elif re.search...
5,321,139
def InterferenceDict(data_list): """Creates an interferenceReturns a double dict from a list of lat,lng, interferences.""" if not isinstance(data_list, list): data_list = [data_list] result = {} for lat, lon, data in data_list: if lat not in result: result[lat] = {} result[lat][lon] = data return...
5,321,140
def load_test_data(columns: pd.Index, filename: str) -> Tuple[pd.Series, pd.DataFrame]: """ loads test data, proccesses it in a similar manner to the train data and return it as pandas df. :param columns: column names of the traininst set the model was fitted on :param filename: csv of data to load ...
5,321,141
def check_ancestors(page): """ First, check if the page's parent is one for which we want to index the direct children of (constants.SEARCH_CHILDREN_OF) If that's not the case, check all ancestors for any page we want all descendants of (constants.SEARCH_DESCENDANTS_OF) If there's a match in t...
5,321,142
def tobin(data, width): """ """ data_str = bin(data & (2**width-1))[2:].zfill(width) return [int(x) for x in tuple(data_str)]
5,321,143
def bisect_last_true(arr): """Binary search for last True occurrence.""" lo, hi = -1, len(arr)-1 while lo < hi: mid = lo + hi + 1 >> 1 if arr[mid]: lo = mid else: hi = mid - 1 return lo
5,321,144
def logLikelihood(theta, times, flux, fluxErr): """ Calculates the log likelihood based on the difference between the model and the data Used by logProbability Args: theta (list) - parameters of the model times (list) - time array of the light curve flux (list) - array of flux da...
5,321,145
def check_attrs(tag, required, optional): """ Helper routine to fetch required and optional attributes and complain about any additional attributes. :param tag (xml.dom.Element): DOM element node :param required [str]: list of required attributes :param optional [str]: list of optional attribute...
5,321,146
def maybe_download(filename, expected_bytes): """Download a file if not present, and make sure it's the right size.""" if not os.path.exists(filename): filename, _ = urlretrieve(url + filename, filename) statinfo = os.stat(filename) if statinfo.st_size == expected_bytes: print('Found and...
5,321,147
def _interpolation(point_set: list)-> list: """ Written by Eric Muzzo, 101184817 Function returns a list which is stored in a variable. The function takes a list as its parameter. >>> _interpolation(point_set) """ if len(point_set[0]) == 2: degree = 1 poly = np.po...
5,321,148
def lint( obj: Union[Database, LoadedIoc], *, verbosity: int = 0, file: IO[str] = sys.stdout, fmt: FormatContext = None, ) -> Union[Database, LoadedIoc]: """ Lint a startup script or a database file. Parameters ---------- obj : The object to lint. """ fmt = fmt o...
5,321,149
def create_app(label_studio_config=None): """ Create application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/. :param label_studio_config: LabelStudioConfig object to use with input_args params """ app = flask.Flask(__package__, static_url_path='') app.secr...
5,321,150
def load_json_result(best_result_name, dataset_name): """Load json from a path (directory + filename).""" result_path = os.path.join(RESULTS_DIR, dataset_name, best_result_name) with open(result_path, 'r') as f: return json.JSONDecoder().decode( f.read() # default=json_util.d...
5,321,151
async def run_cleanup_task() -> None: """Periodic cleanup job for expired sessions and datasets.""" next_cleanup = datetime.today() while True: orcid.get_auth().cleanup_sessions() Dataset.cleanup_datasets() # wait until next time... next_cleanup = next_cleanup + timedelta(day...
5,321,152
def get_included_relationships( results: Union[EntryResource, List[EntryResource]], ENTRY_COLLECTIONS: Dict[str, EntryCollection], include_param: List[str], ) -> Dict[str, List[EntryResource]]: """Filters the included relationships and makes the appropriate compound request to include them in the re...
5,321,153
def sit(robotIP): """Make Nao stand. Warning: Needs a PoseInit before executing Keyword arguments: robotIP -- Nao's IP """ # Init proxies. try: motionProxy = ALProxy("ALMotion", robotIP, 9559) except Exception, e: print "Could not create proxy to ALMotion" print ...
5,321,154
def save_model(sess, saver, model_path="./", steps=0): """ Saves current model to checkpoint folder. :param sess: Current Tensorflow session. :param model_path: Designated model path. :param steps: Current number of steps in training process. :param saver: Tensorflow saver for session. """ ...
5,321,155
def guess_strategy_type(file_name_or_ext): """Guess strategy type to use for file by extension. Args: file_name_or_ext: Either a file name with an extension or just an extension Returns: Strategy: Type corresponding to extension or None if there's no corresponding s...
5,321,156
def plot_width(G, ax, width, tips=True, plot=False): """ Plot edge width of fault network Parameters ---------- G : nx.graph Graph ax : plt axis Axis width : np.array Width of network edges tips : bolean Plot tips plot : False Pl...
5,321,157
def get_mete_rad(S, N, beta=None, beta_dict={}): """Use beta to generate SAD predicted by the METE Keyword arguments: S -- the number of species N -- the total number of individuals beta -- allows input of beta by user if it has already been calculated """ assert S > 1, "S must be greater...
5,321,158
def determine_firmware_versions(build_target): """Returns a namedtuple with main and ec firmware versions. Args: build_target (build_target_lib.BuildTarget): The build target. Returns: MainEcFirmwareVersions namedtuple with results. """ fw_versions = get_firmware_versions(build_target) main_fw_ver...
5,321,159
def get_transcript_lengths(database, build): """ Read the transcripts from the database. Then compute the lengths. Store in a dictionary """ transcript_lengths = {} conn = sqlite3.connect(database) conn.row_factory = sqlite3.Row cursor = conn.cursor() # Get the exon lengths exon...
5,321,160
def segment_chars(plate_img, fixed_width): """ extract Value channel from the HSV format of image and apply adaptive thresholding to reveal the characters on the license plate """ V = cv2.split(cv2.cvtColor(plate_img, cv2.COLOR_BGR2HSV))[2] thresh = cv2.adaptiveThreshold(V, 255, cv2.ADAPTIVE_THRESH_GA...
5,321,161
def get_filename_addition(orig_path: str, filename_addition: str) -> str: """Gets filename with addition. So if item is '/path/name.ext' and the filename_addition is '-add', the new result would be '/path/name-add.ext'. Args: orig_path (str): The original path. filename_addition (str): The...
5,321,162
def lsshell(directory=_os.curdir): """Prints the long listing format of the given directory""" if env.is_posix(): command = 'ls -al' else: command = 'dir' print(_subprocess.check_output([command, directory], shell=True).decode('utf8', errors='ignore'))
5,321,163
def negated(input_words, include_nt=True): """ Determine if input contains negation words """ neg_words = [] neg_words.extend(NEGATE) for word in neg_words: if word in input_words: return True if include_nt: for word in input_words: if "n't" in word: ...
5,321,164
def get_box_value(box): """ Retrieves the value of the provided widget `box` and returns it. """ # Values (QAbstractSpinBox) if isinstance(box, QW.QAbstractSpinBox): return(box.value()) # Bools (QAbstractButton) elif isinstance(box, QW.QAbstractButton): return(box.isChecked...
5,321,165
def set_logger(logger): """Replace kipp internal logger Since of only Utilities' logger can output to file, so you need to replace the kipp' internal logger with Utilities' logger to save your logs to file. Usage: :: set_logger(utilities_logger) """ handler = get_wrap_handler(l...
5,321,166
def pipeline( task: str, model: Optional = None, tokenizer: Optional[Union[str, PreTrainedTokenizer]] = None, use_cuda: Optional[bool] = True, ): """ :param task: (:obj:`str`): The task defining which pipeline will be returned. Currently accepted tasks are: - :obj:`"...
5,321,167
def _handle_varlen_feature( feature, key, sparse_keys, sparse_types, sparse_ranks, types ): """handle_varlen_feature""" if tensorflow_io.experimental.columnar.VarLenFeatureWithRank not in types: raise ValueError("Unsupported VarLenFeatureWithRank {}.".format(feature)) if not feature.dtype: ...
5,321,168
def open_file_externally(path: str) -> None: """open_file_externally(path: str) -> None (internal) Open the provided file in the default external app. """ return None
5,321,169
def _get_init_fn(): """Return a function that 'warm-starts' the training. Returns: An init function. """ exclusions = [] if FLAGS.checkpoint_exclude_scopes: exclusions = [scope.strip() for scope in FLAGS.checkpoint_exclude_scopes.split(',')] variables...
5,321,170
def fit_eager(model_params, ts, vs, es=None, **kwargs): """ Train a classifier using TensorFlow with `tf.dataset`. This is the default behavior for training. :param model_params: The model (or parameters to create the model) to train :param ts: A training data set :param vs: A validation data...
5,321,171
def migration_indices(r_mgeo, p_mgeo): """ identify migration indices """ idxs = None r_mgrphs_iter = chain(*map(multibond_opening_resonances, resonance_graphs(r_mgeo))) p_mgrphs_iter = chain(*map(multibond_opening_resonances, resonance_...
5,321,172
async def on_end(channel, event): """Callback for StasisEnd events. :param channel: Channel DTMF was received from. :param event: Event. """ #print("** END **", channel, event)
5,321,173
def counter(): """Creates a counter instance""" x = [0] def c(): x[0] += 1 return x[0] return c
5,321,174
def replace_null(val): """ Replace given value with 'NULL' if it's an equivalent of NULL. val {any}: value to check returns {str}: 'NULL' or `val` """ if isinstance(val, float): if np.isnan(val): return 'NULL' if val is None: return 'NULL' if isinstance(val...
5,321,175
def _format_to_paddle(params): """Constuct dataset for paddle models""" json_file, args, save_file = params if os.path.exists(save_file): print('Ignore %s' % save_file) return summ_data = SummData(args) print('Processing %s' % json_file) jobs = json.load(open(json_file)) ...
5,321,176
def Element(node, tag, mandatory=False): """Get the element text for the provided tag from the provided node""" value = node.findtext(tag) if value is None: if mandatory: raise SyntaxError("Element '{}.{}' is mandatory, but not present!".format(node.tag, tag)) return None el...
5,321,177
def redirect_outputs(settings, is_quiet=False): """Redirect ``sys``'s outputs using Sopel's settings. :param settings: Sopel's configuration :type settings: :class:`sopel.config.Config` :param bool is_quiet: Optional, set to True to make Sopel's outputs quiet Both ``sys.stderr`` and ``sys.stdout``...
5,321,178
def validate_alignment(alignment): """ValueError on ambiguous alignment characters""" bad_seqs = [] for name, ambiguous_pos in \ alignment.getPerSequenceAmbiguousPositions().items(): if ambiguous_pos: bad_seqs.append(name) if bad_seqs: raise ValueError, 'Ambiguous characters in sequ...
5,321,179
def test_restart_policy(mock_send_message, mock_refresh): """Test submit policies to policy engine.""" loop = LoopInstance(template="template", name="test", details=LOOP_DETAILS) action = loop.act_on_loop_policy(loop.restart) mock_send_message.assert_called_once_with('PUT', ...
5,321,180
def fix_string_attr(tfjs_node): """ Older tfjs models store strings as lists of ints (representing byte values). This function finds and replaces those strings, so protobuf can correctly decode the json. """ def fix(v): if isinstance(v, list): return base64.encodebytes(bytes(v))....
5,321,181
def get_env_space(): """ Return obsvervation dimensions, action dimensions and whether or not action space is continuous. """ env = gym.make(ENV) continuous_action_space = type(env.action_space) is gym.spaces.box.Box if continuous_action_space: action_dim = env.action_space.shape[0] ...
5,321,182
def is_windows_dark_theme(): """Detect Windows theme""" # From https://successfulsoftware.net/2021/03/31/how-to-add-a-dark-theme-to-your-qt-application/ settings = QtCore.QSettings( "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", QtCore.QSettings.Nativ...
5,321,183
def write_to_file(filepath: PathStr, content: str) -> None: """Writes content to a file.""" logs.debug(f"Writing to file {filepath}") with open(filepath, "w") as file: file.write(content)
5,321,184
def maximumProduct(nums): """ :type nums: List[int] :rtype: int """ nums = sorted(nums) first_option=nums[0]*nums[1]*nums[-1] second_option=nums[-3] * nums[-2] * nums[-1] return first_option if first_option > second_option else second_option
5,321,185
def calczeta(phi1, phi2, theta1, theta2): """ Calculate the angular separation between position (phi1, theta1) and (phi2, theta2) """ zeta = 0.0 if phi1 == phi2 and theta1 == theta2: zeta = 0.0 else: argument = sin(theta1) * sin(theta2) * cos(phi1 - phi2) + cos(theta1) * c...
5,321,186
def TestInstall(vms) -> None: """Tests the MPI install. Args: vms: List of VMs in the cluster. """ hosts = ','.join([vm.internal_ip for vm in vms]) mpirun_cmd = f'mpirun -n {len(vms)} -ppn 1 -hosts {hosts} hostname' txt, _ = vms[0].RemoteCommand(f'{SourceMpiVarsCommand(vms[0])}; {mpirun_cmd}') hosts ...
5,321,187
def handler(event): """Parses event payload, extract data from BigQuery table, write to GCS""" json_data = base64.b64decode(event["data"]).decode("utf-8") data = json.loads(json_data) if "bq" not in data: raise Exception("Invalid payload: no 'bq' field in payload", data) if "table" in data...
5,321,188
def directories(path_list, use_sudo=False, owner='', group='', mode=''): """ Require a list of directories to exist. :: from fabtools import require dirs=[ '/tmp/mydir', '/tmp/mydear', '/tmp/my/dir' ] require.directories(dirs, owner='alic...
5,321,189
def transform_coverage_to_coordinates( coverage_list: List[int], ) -> List[Tuple[int, int]]: """ Takes a list of read depths where the list index is equal to the read position + 1 and returns a list of (x, y) coordinates. The coordinates will be simplified using Visvalingham-Wyatt algorithm if the l...
5,321,190
def configure(url, apikey): """ Configure CKAN connection""" try: ckan = connect(str(url), str(apikey)) config = configparser.ConfigParser() config['DEFAULT'] = {'url': str(url), 'apikey': str(apikey)} with open(configFile, 'w') as conf: c...
5,321,191
def test_sync_first_level(): """Test creating Rems for Hypothes.is top-level annotations.""" group_id = hyp.get_group_by_name(HYP_KEY, "RemNote")["id"] annotations = hyp.get_annotations(HYP_KEY, group=group_id) hyp2rem.utils.sync_first_level( hyp_key=HYP_KEY, rem_key=REM_KEY, ...
5,321,192
def complex_wrapper(func): """ Wraps complex valued functions into two-dimensional functions. This enables the root-finding routine to handle it as a vectorial function. Args: func (callable): Callable that returns a complex result. Return: two-dimensional, callable: function h...
5,321,193
def main(): """ Nucleation run """ size = 40 lattice = IsingModel(size, 1) lattice.plot_system('initial-system.png') lattice.save_movie('no-droplet.mp4') lattice.runMovie(1.5, 250*size*size, -0.30, False) lattice.plot_system('no-droplet-final-system.png') lattice.plot_magnetization('no-...
5,321,194
def test_rose_plot_data_using_cpt(data): """ Test supplying a 2D numpy array containing a list of lengths and directions. Use a cmap to color sectors. """ fig = Figure() fig.rose( data=data, region=[0, 1, 0, 360], sector=15, diameter="5.5c", cmap="bat...
5,321,195
def mod_list_comparator(bot_entry, new_list, original_list): """Function to check the differences between new and old lists. In the case of removals, the function also checks to see if their removal is due to privatization or banning. """ formatted_lines = [] changes = list(set(new_list)...
5,321,196
def get_sources_articles(id): """ Function that gets the json response to our url request """ get_news_url = source_url.format(id,api_key) with urllib.request.urlopen(get_news_url) as url: get_news_data = url.read() get_news_response = json.loads(get_news_data) news_results...
5,321,197
def check_spaces_in_filenames(files: Iterable[Path]): """Check for spaces in filenames across example directories.""" regex = re.compile(r'[\s]') files_with_space = list(filter(regex.search, (str(f) for f in files))) if files_with_space: logger.warning( 'Example file name(s) with spa...
5,321,198
def cli_domain(name: Optional[str] = None): """ Register a value domain for the CLI displayed with its own name or ``name`` """ def register(domain: TP) -> TP: if issubclass(domain, enum.Enum): _register_enum(domain, name) else: raise TypeError(f"Cannot register ...
5,321,199