content
stringlengths
22
815k
id
int64
0
4.91M
def get_table_from_alter_table(line, alter_expr): """ Parse the content and return full qualified schema.table from the line if schema provided, else return the table name. Fact: if schema name or table name contains any special chars, each should be double quoted already in dump file. """ ...
30,500
def read_and_setup_bs(request): """ This routine reads the parameter files, sets up the lattice and calculates or reads in the bandstructure Parameters ---------- test_number : int The test number, e.g. the folder under the tests folder. Returns ------- bs : object ...
30,501
def bind_port(socket, ip, port): """ Binds the specified ZMQ socket. If the port is zero, a random port is chosen. Returns the port that was bound. """ connection = 'tcp://%s' % ip if port <= 0: port = socket.bind_to_random_port(connection) else: connection += ':%i' % port ...
30,502
def eval_once(saver, summary_writer, ler, summary_op): """Run Eval once. Args: saver: Saver. summary_writer: Summary writer. ler: Top K op. summary_op: Summary op. """ with tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir) if ckpt...
30,503
def update_target_graph(actor_tvars, target_tvars, tau): """ Updates the variables of the target graph using the variable values from the actor, following the DDQN update equation. """ op_holder = list() # .assign() is performed on target graph variables with discounted actor graph variable values f...
30,504
def safe(function: Callable[..., T]) -> Callable[..., Result[T, Exception]]: """Wraps a function that may raise an exception. e.g.: @safe def bad() -> int: raise Exception("oops") """ def wrapped(*args, **kwargs) -> Result[T, Exception]: try: return Ok(...
30,505
def test_load_labels_data_include_missing_labels_as_false(): """ Test the load_labels_data function by checking whether the query produces the correct labels """ # set up labeling config variables dates = [ datetime.datetime(2016, 1, 1, 0, 0), datetime.datetime(2016, 2, 1, 0, 0), ...
30,506
def strtime(millsec, form="%i:%02i:%06.3f"): """ Time formating function Args: millsec(int): Number of milliseconds to format Returns: (string)Formated string """ fc = form.count("%") days, milliseconds = divmod(millsec, 86400000) hours, milliseconds = divmod(millsec, 3...
30,507
def parallel_categories(): """Parallel Categories Plot.""" mean_neighborhood_sfo = sfo_data.groupby(["neighborhood"]).mean() mean_sale_price_sfo = mean_neighborhood_sfo.sort_values("sale_price_sqr_foot", ascending=False) sfo = mean_sale_price_sfo.head(10) a = sfo.reset_index() parallel_categorie...
30,508
def hessian_filter(img: Image, scales: list, dimension: int = 0, scaled_to_eval=False, normalized=False, parallel=False) -> Image: """Applies a (multi-scale) hessian-like filtering operation on a 3D stack. Transforms an image to an input image where each pixel represents an object-ness measu...
30,509
def close_project(id_, **kwargs): """Close a project :param id_: The ID of the project object to be updated :type id_: str :rtype: ProjectSerializer """ proj = get_project_object(id_) check_project_permission(proj, kwargs["token_info"]) if proj.owner != kwargs["user"]: raise con...
30,510
def inspect_download_url(input_path, args, facts): """Process a direct download URL Gather information required to create a recipe. Args: input_path: The path or URL that Recipe Robot was asked to use to create recipes. args: The command line arguments. facts: A continu...
30,511
def min_cycle_ratio(G: nx.Graph, dist): """[summary] todo: parameterize cost and time Arguments: G ([type]): [description] Returns: [type]: [description] """ mu = 'cost' sigma = 'time' set_default(G, mu, 1) set_default(G, sigma, 1) T = type(dist[next(it...
30,512
def int2base(x, base): """ Method to convert an int to a base Source: http://stackoverflow.com/questions/2267362 """ import string digs = string.digits + string.ascii_uppercase if x < 0: sign = -1 elif x == 0: return digs[0] else: sign = 1 x *= sign digits = ...
30,513
def geometric(X): """ If x1,x2,...xn ~iid~ GEO(p) then the MLE is 1 / X-bar Parameters ---------- X : array_like Returns: ---------- geo_mle : MLE calculation for p-hat for GEO(p) References ---------- [1] Casella, G., Berger, R. L., "Statistical Infe...
30,514
def parse_args(): """Parse input arguments.""" parser = argparse.ArgumentParser(description='Run train or eval scripts for Gated2Depth') parser.add_argument("--base_dir", help="Path to dataset", required=True) parser.add_argument("--train_files_path", help="Path to file with train file names", require...
30,515
def test_bad_colours_set(): """ Validating that the BadColoursSetError exception is raised when required """ mastermind = MastermindCore() with pytest.raises(BadColoursSetError): mastermind.configure( code_length = 4, allow_duplicates = False, colours_set = ['...
30,516
def calc_dH( e_per_atom, stoich=None, num_H_atoms=0, ): """ The original method is located in: F:\Dropbox\01_norskov\00_git_repos\PROJ_IrOx_Active_Learning_OER\data\proj_data_irox.py Based on a E_DFT/atom of -7.047516 for rutile-IrO2 See the following dir for derivation: PR...
30,517
def store_policy_instance(policy_type_id, policy_instance_id, instance): """ Store a policy instance """ type_is_valid(policy_type_id) key = _generate_instance_key(policy_type_id, policy_instance_id) if SDL.get(key) is not None: # Reset the statuses because this is a new policy instance,...
30,518
def _make_asset_build_reqs(asset): """ Prepare requirements and inputs lists and display it :params str asset: name of the asset """ def _format_reqs(req_list): """ :param list[dict] req_list: :return list[str]: """ templ = "\t{} ({})" return [templ....
30,519
def gsl_eigen_herm_alloc(*args, **kwargs): """gsl_eigen_herm_alloc(size_t const n) -> gsl_eigen_herm_workspace""" return _gslwrap.gsl_eigen_herm_alloc(*args, **kwargs)
30,520
def cosine_similarity(array1, array2): """ Calcula la similitud coseno entre dos arrays """ # -sum(l2_norm(y_true) * l2_norm(y_pred)) return -dot(array1, array2)/(norm(array1)*norm(array2))
30,521
def DEW_T(Y, P, all_params): """ Y = list of mollar fractions of vapor like [0.2 ,0.8] or [0.1 0.2 0.7] Sumation of X list must be 1.0 P = Pressure in kPa all_params = list of parameters for Antonie equations example for all params: all_params = [[A1, B1, C1], ...
30,522
def plugin_last(): """This function should sort after other plug-in functions""" return "last"
30,523
def init_seg_table(metadata, tablename, segid_colname=cn.seg_id, chunked=True): """ Specifies a table for tracking info about a segment. """ columns = [Column("id", BigInteger, primary_key=True), Column(cn.seg_id, Integer, index=True), Column(cn.size, Integer), # Cen...
30,524
def extract_shebang_command(handle): """ Extract the shebang_ command line from an executable script. :param handle: A file-like object (assumed to contain an executable). :returns: The command in the shebang_ line (a string). The seek position is expected to be at the start of the file and will b...
30,525
def set_resource_limit(limit, soft=None, hard=None, warn_on_failure=False): """Uses the ``resource`` package to change a resource limit for the current process. If the ``resource`` package cannot be imported, this command does nothing. Args: limit: the name of the resource to limit. Must be th...
30,526
def split_abstracts(ftm_df): """ Split the mail abstract (item content) into different mails. This is required to find the 'novel' email, and the rest of the threat. We create a new row for each email in the threat, but it keeps the ID of the 'novel email'. We add two boolean flags for is_novel, an...
30,527
def merge(xref): """ Do some logic here to clean things up!""" pgconn = get_dbconn('mesosite', user='mesonet') ipgconn = get_dbconn('iem', user='mesonet') for nwsli, name in xref.iteritems(): cursor = pgconn.cursor() rwcursor = pgconn.cursor() icursor = ipgconn.cursor() n...
30,528
def get_weight_from_alias(blend_shape, alias): """ Given a blend shape node and an aliased weight attribute, return the index in .weight to the alias. """ # aliasAttr lets us get the alias from an attribute, but it doesn't let us get the attribute # from the alias. existing_indexes = blend_s...
30,529
def __check_dependences_and_predecessors(pet: PETGraphX, out_dep_edges: List[Tuple[Any, Any, Any]], parent_task: CUNode, cur_cu: CUNode): """Checks if only dependences to self, parent omittable node or path to target task exists. Checks if node is a direct successor of a...
30,530
def clone_master_track(obj, stdata, stindex, stduration): """ ghetto-clone ('deep copy') an object using JSON populate subtrack info from CUE sheet """ newsong = json.loads(json.dumps(obj)) newsong['subsong'] = {'index': stindex, 'start_time': stdata['index'][1][0], 'duration': stduration} n...
30,531
def create_graph(num_islands, bridge_config): """ Helper function to create graph using adjacency list implementation """ adjacency_list = [list() for _ in range(num_islands + 1)] for config in bridge_config: source = config[0] destination = config[1] cost = config[2] ...
30,532
def distinct_extractors(count=True, active=True): """ Tool to count unique number of predictors for each Dataset/Task """ active_datasets = ms.Dataset.query.filter_by(active=active) superset = set([v for (v, ) in ms.Predictor.query.filter_by(active=True).filter( ms.Predictor.dataset_id.in_( ...
30,533
def get_timepoint( data, tp=0 ): """Returns the timepoint (3D data volume, lowest is 0) from 4D input. You can save memory by using [1]: nifti.dataobj[..., tp] instead: see get_nifti_timepoint() Works with loop_and_save(). Call directly, or with niftify(). Ref: [1]: http:/...
30,534
def method_from_name(klass, method_name: str): """ Given an imported class, return the given method pointer. :param klass: An imported class containing the method. :param method_name: The method name to find. :return: The method pointer """ try: return getattr(klass, method_name) ...
30,535
def create_config_file(config_path=CONFIG_FILE_PATH): """ generate a generic config file from a given path :param config_path: :return: """ if os.path.exists(config_path): logging.warning("the file config.txt already exits, it will not be overwritten") else: of = open(config_...
30,536
def get_querypage(site: Site, page: str, limit: int = 500): """ :type site Site :type page str :type limit int :rtype: list[str] """ # http://poznan.wikia.com/api.php?action=query&list=querypage&qppage=Nonportableinfoboxes # http://poznan.wikia.com/api.php?action=query&list=querypage&qpp...
30,537
def parse_value(string: str) -> str: """Check if value is a normal string or an arrow function Args: string (str): Value Returns: str: Value if it's normal string else Function Content """ content, success = re.subn(r'^\(\s*\)\s*=>\s*{(.*)}$', r'\1', string) if not success: ...
30,538
def test_arrowleft_shortchut(vim_bot): """Test j command (Cursor moves right).""" main, editor_stack, editor, vim, qtbot = vim_bot editor.stdkey_backspace() qtbot.keyPress(editor, Qt.Key_Right) cmd_line = vim.get_focus_widget() _, col = editor.get_cursor_line_column() qtbot.keyPress(editor, ...
30,539
def uniqify(seq, idfun=None): """Return only unique values in a sequence""" # order preserving if idfun is None: def idfun(x): return x seen = {} result = [] for item in seq: marker = idfun(item) if marker in seen: continue ...
30,540
def inside(Sv, r, r0, r1): """ Mask data inside a given range. Args: Sv (float): 2D array with data to be masked. r (float): 1D array with range data. r0 (int): Upper range limit. r1 (int): Lower range limit. Returns: bool...
30,541
def file_exists(fpath: str): """Checks if file exists by the given path :param str fpath: A path to validate for being a file :returns: True, if fpath is a file False, if fpath doesn't exists or isn't a file """ return os.path.isfile(fpath)
30,542
def get_solution_name( fs: float, tf_name: str, tf_var: str, postfix: Optional[str] = None ) -> str: """Get the name of a solution file""" from resistics.common import fs_to_string solution_name = f"{fs_to_string(fs)}_{tf_name.lower()}" if tf_var != "": tf_var = tf_var.replace(" ", "_") ...
30,543
def test_client_arm(server, client): """Should call the API and arm the system.""" html = """[ { "Poller": {"Poller": 1, "Panel": 1}, "CommandId": 5, "Successful": True, } ]""" server.add( responses.POST, "https://example.com/api/panel/...
30,544
def test_get_filename_from_request(patch_url_handler): """Test getting the filename of an url from a request object.""" # url with no filename in name, but in request content headers request = urlopen("http://valid.com") filename = packagerbuddy._get_filename_from_request(request) assert filename ==...
30,545
def escape(message: str) -> str: """Escape tags which might be interpreted by the theme tokenizer. Should be used when passing text from external sources to `theme.echo`. """ return re.sub( rf"<(/?{TAG_RE})>", r"\<\1>", message, )
30,546
def display_notebook(host, port, display): """Display Aim instance in an ipython context output frame. """ import IPython.display shell = """ <iframe id="aim" width="100%" height="800" frameborder="0" src={}:{}{}> </iframe> """.format(host, port, '/notebook/') # @TODO wr...
30,547
async def normalize_message(app: FastAPI, message: Message) -> Message: """ Given a TRAPI message, updates the message to include a normalized qgraph, kgraph, and results """ try: merged_qgraph = await normalize_qgraph(app, message.query_graph) merged_kgraph, node_id_map, edge_id_map...
30,548
def ec_elgamal_encrypt(msg, pk, symmalg): """ Computes a random b, derives a key from b*g and ab*g, then encrypts it using symmalg. Input: msg Plaintext message string. pk Public key: a tuple (EC, ECPt, ECPt), that is (ec, generator g, a*g) symmalg A callable th...
30,549
def plot_confusion_matrix(cm, classes, normalize=False, cmap=plt.cm.YlGnBu): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ np.set_printoptions(precision=2) fig, ax = plt.s...
30,550
def meshgrid(params): """Returns meshgrid X that can be used for 1D plotting. params is what is returned by finess.params.util.read_params.""" assert(params['finess', 'ndims'] == 1) mx = params['grid', 'mx'] xlow = params['grid', 'xlow'] xhigh = params['grid', 'xhigh'] dx = (xhigh-x...
30,551
def _pbe_p12(params, passphrase, hash_alg, cipher, key_size): """PKCS#12 cipher selection function for password-based encryption This function implements the PKCS#12 algorithm for password-based encryption. It returns a cipher object which can be used to encrypt or decrypt data based on the sp...
30,552
def add_settings_routes(app): """ Create routes related to settings """ @app.route('/v1/rule_settings/', methods=['GET']) @requires_login @use_kwargs({ 'agency_code': webargs_fields.String(required=True), 'file': webargs_fields.String(validate=webargs_validate. ...
30,553
def delete_by_date_paste(date): """ Deletes the paste entries older than a certain date. Note that it will delete any document/index type entered into it for elasticsearch, the paste restriction is due to postgreql :return: True once """ # Create a connection to the database (seemd to want it i...
30,554
def add_user_to_ldap_and_login(self, server, user=None, ch_user=None, login=None, exitcode=None, message=None, rbac=False): """Add user to LDAP and ClickHouse and then try to login. """ self.context.ldap_node = self.context.cluster.node(server) if ch_user is None: ch_user = {} if login is N...
30,555
def is_venv(): """Check whether if this workspace is a virtualenv. """ dir_path = os.path.dirname(SRC) is_venv_flag = True if SYS_NAME == "Windows": executable_list = ["activate", "pip.exe", "python.exe"] elif SYS_NAME in ["Darwin", "Linux"]: executable_list = ["activate", "pip"...
30,556
def convert(origDict, initialSpecies): """ Convert the original dictionary with species labels as keys into a new dictionary with species objects as keys, using the given dictionary of species. """ new_dict = {} for label, value in origDict.items(): new_dict[initialSpecies[label]] =...
30,557
def Vector(point, direction, simple=None): """ Easy to use Vector type constructor. If three arguments are passed, the first two are the x components of the point and the third is the direction component of the Vector. """ if simple is not None: point = Point(point, direction) di...
30,558
def check_runner(event, context): """ Pure lambda function to pull run and check information from SQS and run the checks. Self propogates. event is a dict of information passed into the lambda at invocation time. """ if not event: return app_utils_obj.run_check_runner(event)
30,559
def createGrid(nx, ny): """ Create a grid position array. """ direction = 0 positions = [] if (nx > 1) or (ny > 1): half_x = int(nx/2) half_y = int(ny/2) for i in range(-half_y, half_y+1): for j in range(-half_x, half_x+1): if not ((i==0) and (...
30,560
def print_gradient(texto,grad): """ Impressão do Gradiente. Utilizado para Gradiente de Suporte ou de Confiança conforme a faixa em que ele se encontra. :param: grad: vetor de Gradiente que será alterado :param: val: valor atual que será contabilizado no vetor de Gradiente """ print('{:...
30,561
def _update_distances_for_one_sample( sample_index, new_distances, all_distances, sample_name_to_index ): """Updates all distance data in dictionary all_distances. new_distances=list of tuples, made by _load_one_sample_distances_file""" for other_sample, distance in new_distances: other_index = ...
30,562
def pay(name): """Pay participants""" # Skip if performing local development if reseval.is_local(name): return # Get config config = reseval.load.config_by_name(name) # Get credentials credentials = reseval.load.credentials_by_name(name, 'crowdsource') # Pay participants m...
30,563
def get_private_network(filters: Optional[Sequence[pulumi.InputType['GetPrivateNetworkFilterArgs']]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetPrivateNetworkResult: """ Get information about a Vultr private network. ## Example Usage Get the information...
30,564
def test_cell_order_2d(): """Test for 6 cells in 2d""" cell_order_reference = [[1, 3, 4], [2, 3, 4, 5], [4, 5], [4], [5], []] cell_order = create_cell_order_2d(1, [3, 2]) npt.assert_array_equal(cell_order_reference, cell_order)
30,565
def bootstrap(tank, context): """ Interface for older versions of tk-multi-launchapp. This is deprecated and now replaced with the ``startup.py`` file and ``SoftwareLauncher`` interface. Prepares the environment for a tk-houdini bootstrap. This method is called directly from the tk-multi-launc...
30,566
def make1(): """ делаем простой документ, но уже с разметкой. это helloworld.docx """ doc = docx.Document() # добавляем первый параграф doc.add_paragraph('Здравствуй, мир!') # добавляем еще два параграфа par1 = doc.add_paragraph('Это второй абзац.') par2 = doc.add_paragraph('Это ...
30,567
def sdc_pandas_series_operator_le(self, other): """ Pandas Series operator :attr:`pandas.Series.le` implementation .. only:: developer **Test**: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_op7* python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_ser...
30,568
def getArrFromFile(path = fromPath): """ 读取原始csv文件,返回numpy数组 :param path: 原始csv文件路径 string类型 default:fromPath :return: X: 由原始文件生成的数组 二维numpy数组类型 """ X = numpy.genfromtxt(path,dtype=float,delimiter=',')[1:,:-2] return X
30,569
def erode(binary_image, erosion=1): """ Sets 1s at boundaries of binary_image to 0 """ batch_array = binary_image.data.cpu().numpy() return torch.tensor( np.stack([ binary_erosion( array, iterations=erosion, border_value=1, # so th...
30,570
def plot_chirpam_fit(cell_mean, param_d, QI=None, fit_f=sinexp_sigm, start=420, stop=960, ax=None): """ Helper function to visualize the fit of a cell response to a chirp_am stimulus. params: - cell_mean: Cell's mean response to the stimulus - param_d: Parameter diction...
30,571
def convert2SQUAD_format(hoppy_data, write_file_name): """ Converts QAngaroo data (hoppy_data) into SQuAD format. The SQuAD-formatted data is written to disk at write_file_name. Note: All given support documents per example are concatenated into one super-document. All text is lowercased. ""...
30,572
def command_ltc(bot, user, channel, args): """Display current LRC exchange rates from BTC-E""" r = bot.get_url("https://btc-e.com/api/2/ltc_usd/ticker") j = r.json()['ticker'] return bot.say(channel, "BTC-E: avg:$%s last:$%s low:$%s high:$%s vol:%s" % (j['avg'], j['last'], j['low'], j['high'], j['vol']...
30,573
def new_match(request, cmd_args): """ Return a slack message with a link to a new match """ # Could potentially add arguments to allow game configuration here serializer = LiveMatchSerializer(data={"config": cmd_args}) if serializer.is_valid(): live_match = serializer.save() re...
30,574
def abort(container_dir, why=None, payload=None): """Abort a running application. Called when some initialization failed in a running container. """ flag_aborted(container_dir, why, payload) container_dir = os.path.realpath(os.path.join(container_dir, '../')) supervisor.control_service(containe...
30,575
def head(feats, anchors, num_classes): """Convert final layer features to bounding box parameters. Parameters ---------- feats : tensor Final convolutional layer features. anchors : array-like Anchor box widths and heights. num_classes : int Number of target classes. ...
30,576
def socfaker_azurevmtopology_get(): """ None """ if validate_request(request): return jsonify(str(socfaker.products.azure.vm.topology))
30,577
def read_json_file(filename): """Load json object from a file.""" with open(filename, 'r') as f: content = json.load(f) return content
30,578
def createVectorisedTargValObjFunction(functTypeStr:str, averageMethod="mean",catchOverflow=True, errorRetVal=1e30, normToErrorRetVal=False, greaterThanIsOk=False, lessThanIsOk=False, useAbsVals=False, divideErrorsByNormFactor=None): """ Creates a comparison function that operators on (iterA,iterB) and returns a singl...
30,579
def get_nonoverlap_ra_dataset_conf(dataset_conf): """extract segments by shifting segment length""" if dataset_conf["if_rand"]: info("disabled dataset_conf if_rand") dataset_conf["if_rand"] = False if dataset_conf["seg_rand"]: info("disabled dataset_conf seg_rand") dataset_co...
30,580
def _f_model_snaive_wday(a_x, a_date, params, is_mult=False, df_actuals=None): """Naive model - takes last valid weekly sample""" if df_actuals is None: raise ValueError('model_snaive_wday requires a df_actuals argument') # df_actuals_model - table with actuals samples, # adding y_out column w...
30,581
def read_fts(self,s, orders=None, filename=None, pfits=True, verb=True): """ SYNTAX: read_fts(filename) OUTPUT: namedtuple('spectrum', 'w f berv bjd blaze drift timeid sn55 ') w - wavelength f - flux berv - Barycentric Earth Radial Velocity bjd - Barycentric J...
30,582
def main(): """The main function.""" model_args, training_args, inference_args = uisrnn.parse_arguments() diarization_experiment(model_args, training_args, inference_args)
30,583
def save_model(sess, model_saver, model_out_dir): """ Saves the FCN model. :param sess: TF Session :param model_saver: TF model saver :param model_out_dir: Directory to save the model in """ # Create a folder for the models: if os.path.exists(model_out_dir): shutil.rmtree(model_...
30,584
def union_exprs(La, Lb): """ Union two lists of Exprs. """ b_strs = set([node.unique_str() for node in Lb]) a_extra_nodes = [node for node in La if node.unique_str() not in b_strs] return a_extra_nodes + Lb
30,585
def programs_reload(): """Reload programs from config file Parameters (default): - do_create (True) - do_update (True) - do_pause (False) """ try: result = dar.reload_programs(**request.args) except TypeError as e: log.info("Caught TypeError: %s" % (str(e))) ...
30,586
def generate_urls(): """Gathers clinical trials from clinicaltrials.gov for search term defined in build_url() function and downloads to specified file format. """ api_call = build_url(expr='Cancer', max_rnk=1, fmt='json') r = requests.get(api_call) data = r.json() n_studies = data['...
30,587
def xyz2luv(xyz, illuminant="D65", observer="2"): """XYZ to CIE-Luv color space conversion. Parameters ---------- xyz : (M, N, [P,] 3) array_like The 3 or 4 dimensional image in XYZ format. Final dimension denotes channels. illuminant : {"A", "D50", "D55", "D65", "D75", "E"}, option...
30,588
def safe_open_w(path): """ Open "path" for writing, creating any parent directories as needed. """ mkdir_p(os.path.dirname(path)) return open(path, 'wb')
30,589
def mysql_drop_tables(): """ Drop the application tables""" require('environment', provided_by=[production, staging]) total_tables = mysql_count_tables() question = ("Do you want to drop the {} tables in '%(db_name)s'?" .format(total_tables) % env) if not confirm(question): ...
30,590
def direct_publish_workflow(previous_model, new_deposit): """Workflow publishing the deposits on submission.""" from b2share.modules.deposit.api import PublicationStates new_state = new_deposit['publication_state'] previous_state = previous_model.json['publication_state'] if previous_state != new_s...
30,591
def today(): """ Today Page: Displays all the notifications like the word of the day, news highlights or friends who added you or shared a note with you """ return render_template('main/today.html', username=session['username'])
30,592
def load_data_states(csv_filename): """Load data for file .csv.""" with open(csv_filename, mode='r') as csvfile: reader = csv.DictReader(csvfile) for row in reader: state = State(**row) #state.save() print(state)
30,593
def compile_read_regex(read_tags, file_extension): """Generate regular expressions to disern direction in paired-end reads.""" read_regex = [re.compile(r'{}\.{}$'.format(x, y))\ for x, y in itertools.product(read_tags, [file_extension])] return read_regex
30,594
def hello_world(): """Print 'Hello World!' to the console.""" print("Hello world!")
30,595
def filter(start=None, stop=None, **kwargs): """ Get commands with ``start`` <= date < ``stop``. Additional ``key=val`` pairs can be supplied to further filter the results. Both ``key`` and ``val`` are case insensitive. In addition to the any of the command parameters such as TLMSID, MSID, SCS, S...
30,596
def _get_energy_at_time(masses, pos, vel, time_idx): """ Internal function used to calculate kinetic energy and potential energy at a give time index using a vectorized direct sum approach. This function is necessary to facilitate the parallelization of the energy calculation across multiple CPU cor...
30,597
def test_base_forest_quantile(): """ Test that the base estimators belong to the correct class. """ rng = np.random.RandomState(0) X = rng.randn(10, 1) y = np.linspace(0.0, 100.0, 10.0) rfqr = RandomForestQuantileRegressor(random_state=0, max_depth=1) rfqr.fit(X, y) for est in rfqr....
30,598
def get_root_url_for_date(date): """ Returns the root URL of the TMCDB web I/F for the given date. The argument date should be an ISO-8601 date string (YYYY-MM-DD). The returned URL already contains the date. """ year = date[:4] mm = date[5:7] hostname = get_host_name() return "%s/i...
30,599