content
stringlengths
22
815k
id
int64
0
4.91M
def drag_eqn(times,g,r): """define scenario and integrate""" param = np.array([ g, r]) hinit = np.array([0.0,0.0]) # initial values (position and velocity, respectively) h = odeint(deriv, hinit, times, args = (param,)) return h[:,0], h[:,1]
5,340,800
async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None: """Set up LGE device climate based on config_entry.""" entry_config = hass.data[DOMAIN] lge_devices = entry_config.get(LGE_DEVICES) if not lge_devices: return _LOGGER...
5,340,801
def virtual_potential_temperature_monc(theta, thref, q_v, q_cl): """ Virtual potential temperature. Derived variable name: th_v_monc Approximate form as in MONC Parameters ---------- theta : numpy array or xarray DataArray Potential Temperature. (K) thref : numpy array or xarr...
5,340,802
def promote_user(username): """Give admin privileges from a normal user.""" user = annotator.credentials.find_one({'username': username}) if user: if user['admin']: flash("User {0} is already an administrator".format(username), 'warning') else: annotator.credentials.u...
5,340,803
def shutdown(): """ ensures the C++ node handle is shut down cleanly. It's good to call this a the end of any program where you called rospy_and_cpp_init """ rospy.signal_shutdown('ros_init shutdown') roscpp_initializer.shutdown()
5,340,804
def slide_number_from_xml_file(filename): """ Integer slide number from filename Assumes /path/to/Slidefile/somekindofSlide36.something """ return int(filename[filename.rfind("Slide") + 5:filename.rfind(".")])
5,340,805
def massivescan(websites): """scan multiple websites / urls""" # scan each website one by one vulnerables = [] for website in websites: io.stdout("scanning {}".format(website)) if scanner.scan(website): io.stdout("SQL injection vulnerability found") vulnerables.a...
5,340,806
def is_strong_pass(password): """ Verify the strength of 'password' Returns a dict indicating the wrong criteria A password is considered strong if: 8 characters length or more 1 digit or more 1 symbol or more 1 uppercase letter or more 1 lowercase letter or more ...
5,340,807
def plot_config(config, settings=None): """ plot_config: obj -> obj --------------------------------------------------------------- Sets the defaults for a custom experiment plot configuration object from configobj. The defaults are only set if the setting does not exist (t...
5,340,808
async def notify(event): """Notify all subscribers of ``event``.""" for subscriber in async_subscribers: await subscriber(event)
5,340,809
def clear_waf_timestamp_files(conf): """ Remove timestamp files to force builds of generate_uber_files and project gen even if some command after configure failes :param conf: """ # Remove timestamp files to force builds even if some command after configure fail force_timestamp_files = CON...
5,340,810
def load_spectrogram(spectrogram_path): """Load a cante100 dataset spectrogram file. Args: spectrogram_path (str): path to audio file Returns: np.array: spectrogram """ if not os.path.exists(spectrogram_path): raise IOError("spectrogram_path {} does not exist".format(spect...
5,340,811
def evaluate_fN(model, NHI): """ Evaluate an f(N,X) model at a set of NHI values Parameters ---------- NHI : array log NHI values Returns ------- log_fN : array f(NHI,X) values """ # Evaluate without z dependence log_fNX = model.__call__(NHI) return log_fNX
5,340,812
def generate_volume_data(img_data): """ Generate volume data from img_data. :param img_data: A NIfTI.get_data object, img_data[:][x][y][z] is the tensor matrix information of voxel (x,y,z)img_data: :return: vtkImageData object which stores volume render object. """ dims = [148, 190, 160] # siz...
5,340,813
def pipe(bill_texts_df): """ soup = bs(text, 'html.parser') raw_text = extractRawText(soup) clean_text = cleanRawText(raw_text) metadata = extract_metadata(soup) """ bill_texts_df['soup'] = \ bill_texts_df['html'].apply(lambda x: bs(x, 'html.parser')) bill_texts_df[...
5,340,814
def _as_static(data, fs): """Get data into the Pyglet audio format.""" fs = int(fs) if data.ndim not in (1, 2): raise ValueError('Data must have one or two dimensions') n_ch = data.shape[0] if data.ndim == 2 else 1 audio_format = AudioFormat(channels=n_ch, sample_size=16, ...
5,340,815
def plot_success(exp_data_dict, # task_names, exp_names, title_str='Success Rate (%)', y_label_str="Success Rate (%)"): """ :param exp_data_dict: [name:list(1,2,3)] :param task_names: ['Reaching task', 'Lifting task', ] :param exp_names: ['PNO', 'PNR', 'POR'] :para...
5,340,816
def preprocess_data(cubes, time_slice: dict = None): """Regrid the data to the first cube and optional time-slicing.""" # Increase TEST_REVISION anytime you make changes to this function. if time_slice: cubes = [extract_time(cube, **time_slice) for cube in cubes] first_cube = cubes[0] # re...
5,340,817
def password_to_str(password): """ 加密 :param password: :return: """ def add_to_16(password): while len(password) % 16 != 0: password += '\0' return str.encode(password) # 返回bytes key = 'saierwangluo' # 密钥 aes = AES.new(add_to_16(key), AES.MODE_ECB) # 初始化a...
5,340,818
def email_checker_mailru(request: Request, email: str): """ This API check email from mail.ru<br> <pre> :return: JSON<br> </pre> Example:<br> <br> <code> https://server1.majhcc.xyz/api/email/checker/mailru?email=oman4omani@mail.ru """ from src.Emails.checker.mailru import che...
5,340,819
def guild_only() -> Callable: """A :func:`.check` that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command. This check raises a special exception, :exc:`.NoPrivateMessage` that is inherited from :exc:`.CheckFailure`. ...
5,340,820
def make_lvis_metrics( save_folder=None, filename_prefix="model_output", iou_types: Union[str, List[str]] = "bbox", summarize_to_stdout: bool = True, evaluator_factory: Callable[ [Any, List[str]], DetectionEvaluator ] = LvisEvaluator, gt_api_def: Sequence[ SupportedDatasetApi...
5,340,821
def _calculate_cos_loop(graph, threebody_cutoff=4.0): """ Calculate the cosine theta of triplets using loops Args: graph: List Returns: a list of cosine theta values """ pair_vector = get_pair_vector_from_graph(graph) _, _, n_sites = tf.unique_with_counts(graph[Index.BOND_ATOM_INDICE...
5,340,822
def load_plugin(): """ Returns plugin available in this module """ return HostTestPluginCopyMethod_Firefox()
5,340,823
def temp_url_page(rid): """ Temporary page where receipts are stored. The user, which visits it first, get the receipt. :param rid: (str) receipt id (user is assigned to receipt with this id) """ if not user_handler.assign_rid_user(rid, flask.session['username']): logging.warn('Trying to st...
5,340,824
def extract_dependencies(content): """ Extract the dependencies from the CMake code. The `find_package()` and `pkg_check_modules` calls must be on a single line and the first argument must be a literal string for this function to be able to extract the dependency name. :param str content: The ...
5,340,825
def _block(x, out_channels, name, conv=conv2d, kernel=(3, 3), strides=(2, 2), dilations=(1, 1), update_collection=None, act=tf.nn.leaky_relu, pooling='avg', padding='SAME', batch_norm=False): """Builds the residual blocks used in the discriminator in GAN. Args: x: The 4D input vector. ou...
5,340,826
def createLaplaceGaussianKernel(sigma, size): """构建高斯拉普拉斯卷积核 Args: sigma ([float]): 高斯函数的标准差 size ([tuple]): 高斯核的大小,奇数 Returns: [ndarray]: 高斯拉普拉斯卷积核 """ H, W = size r, c = np.mgrid[0:H:1, 0:W:1] r = r - (H - 1) / 2 c = c - (W - 1) / 2 sigma2 = pow(sigma, 2....
5,340,827
def test_datafile_success(session_obj): """ Normally a good practice is to have expected response as a string like in other tests. Here we are exceptionally making expected response a dict for easier comparison. String was causing some issues with extra white space characters. :param session_obj: se...
5,340,828
def test_DeAST_class(): """Can the DeAST class be instantiated?""" from ast import NodeVisitor from deast import DeAST deaster = DeAST() assert isinstance(deaster, DeAST) assert isinstance(deaster, NodeVisitor)
5,340,829
def is_file_type(fpath, filename, ext_list): """Returns true if file is valid, not hidden, and has extension of given type""" file_parts = filename.split('.') # invalid file if not os.path.isfile(os.path.join(fpath, filename)): return False # hidden file elif filename.startswith('.'): return Fals...
5,340,830
def xp_rirgen2(room, source_loc, mic_loc, c=340, fs=16000, t60=0.5, beta=None, nsamples=None, htw=None, hpfilt=True, method=1): """Generates room impulse responses corresponding to each source-microphone pair placed in a room. Args: room (numpy/cupy array) = room dimensions in meters...
5,340,831
def mean_bias_removal(hindcast, alignment, cross_validate=True, **metric_kwargs): """Calc and remove bias from py:class:`~climpred.classes.HindcastEnsemble`. Args: hindcast (HindcastEnsemble): hindcast. alignment (str): which inits or verification times should be aligned? - maximize...
5,340,832
def request_sudoku_valid(sudoku: str) -> bool: """valid request""" is_valid = False provider_request = requests.get(f"{base_url}/valid/{sudoku}") if provider_request.status_code == 200: request_data = provider_request.json() is_valid = request_data["result"] # TODO: else raise except...
5,340,833
def index(): """ vista principal """ return "<i>API RestFull PARCES Version 0.1</i>"
5,340,834
def show_config(ctx): """ Prints the resolved config to the console """ click.echo(ctx.obj["config"].to_yaml())
5,340,835
def tag(dicts, key, value): """Adds the key value to each dict in the sequence""" for d in dicts: d[key] = value return dicts
5,340,836
def init_emitter(): """Ensure emit is always clean, and initted (in test mode). Note that the `init` is done in the current instance that all modules already acquired. """ # init with a custom log filepath so user directories are not involved here; note that # we're not using pytest's standard ...
5,340,837
def plot_roc(fpr, tpr): """Plot the ROC curve""" plt.plot(fpr, tpr) plt.title('Receiver Operating Characteristic (ROC)') plt.legend(bbox_to_anchor=(1.05, 1), loc=2) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.savefig(Directories.ROC_CURVE_DIR.value) plt.show(...
5,340,838
def openpairshelf(filename, flag='c', protocol=None, writeback=False): """Returns a ProteinPairDB object, with similar functionality to shelve.open()""" return ProteinPairDB(filename, flag, protocol, writeback)
5,340,839
def createUser(emailid, password, contact_no, firstname, lastname, category, address, description, company_url, image_url, con=None, cur=None, db=None): """ Tries to create a new user with the given data. Returns: - dict: dict object containing all user data, if query was successfull - Fals...
5,340,840
def sensor_pull_storage(appname, accesskey, timestring, *,data_folder = None, ttn_version=3): """ Pull data from TTN via the TTN storage API. appname is the name of the TTN app accesskey is the full accesskey from ttn. For TTN V3, this is is the secret that is output when a key is created. For TTN V2, this is ...
5,340,841
async def discordView(cls:"PhaazebotWeb", WebRequest:ExtendedRequest) -> Response: """ Default url: /discord/view/{guild_id:\d+} """ PhaazeDiscord:"PhaazebotDiscord" = cls.BASE.Discord if not PhaazeDiscord: return await cls.Tree.errors.notAllowed(cls, WebRequest, msg="Discord module is not active") guild_id:st...
5,340,842
def update_max_braking_decel(vehicle, mbd): """ Updates the max braking decel of the vehicle :param vehicle: vehicle :param mbd: new max braking decel :type vehicle: VehicleProfile :return: Updated vehicle """ return vehicle.update_max_braking_decel(mbd)
5,340,843
def get_outlier_removal_mask(xcoords, ycoords, nth_neighbor=10, quantile=.9): """ Parameters ---------- xcoords : ycoords : nth_neighbor : (Default value = 10) quantile : (Default value = .9) Returns ------- """ from scipy.spatial.distan...
5,340,844
def _kp(a, b): """Special case Kronecker tensor product of a[i] and b[i] at each time interval i for i = 0 .. N-1 It is specialized for the case where both a and b are shape N x m x 1 """ if a.shape != b.shape or a.shape[-1] != 1: raise(ValueError) N = a.shape[0] # take the outer pro...
5,340,845
def omics(): """Manage -omics."""
5,340,846
def strategy(history, alivePlayers, whoami, memory): """ history contains all previous rounds (key : id of player (shooter), value : id of player (target)) alivePlayers is a list of all player ids whoami is your own id (to not kill yourself by mistake) memory is None by default ...
5,340,847
def parse_fn(serialized_example: bytes) -> FeaturesType: """Parses and converts Tensors for this module's Features. This casts the audio_raw_pcm16 feature to float32 and scales it into the range [-1.0, 1.0]. Args: serialized_example: A serialized tf.train.ExampleProto with the features dict keys dec...
5,340,848
def cli(ctx: click.Context) -> int: """ Method used to declare root CLI command through decorators. """ return 0
5,340,849
def parse_clock(line): """Parse clock information""" search = parse(REGEX_CLOCK, line) if search: return int(search.group('clock')) else: return None
5,340,850
def block_latest(self, **kwargs): """ Return the latest block available to the backends, also known as the tip of the blockchain. https://docs.blockfrost.io/#tag/Cardano-Blocks/paths/~1blocks~1latest/get :param return_type: Optional. "object", "json" or "pandas". Default: "object". :type return_ty...
5,340,851
def get_courses(): """ Route to display all courses """ params = format_dict(request.args) if params: try: result = Course.query.filter_by(**params).order_by(Course.active.desc()) except InvalidRequestError: return { 'message': 'One or more parameter(s) does ...
5,340,852
def zero_adam_param_states(state: flax.optim.OptimizerState, selector: str): """Applies a gradient for a set of parameters. Args: state: a named tuple containing the state of the optimizer selector: a path string defining which parameters to freeze. Returns: A tuple containing the new pa...
5,340,853
def main(): """ Main Function. """ inputQuery = input("Enter query string:") tic = time.time() docsAsShingleSets, allShingles, PostingDict, docIDlist = shingle(inputQuery) toc = time.time() print("Time taken = ", toc-tic) tic = time.time() matrix = matrixGenerator(allShingles,Postin...
5,340,854
def leftFitNormal(population): """ Obtain mode and standard deviation from the left side of a population. >>> pop = np.random.normal(loc=-20, scale=3, size=15000) >>> mode, sigma = leftFitNormal(pop) >>> -22 < mode < -18 True >>> round(sigma) 3 >>> pop[pop > -18] += 10 ...
5,340,855
def test_neg_init(): """ Tests that init does not run main on package import """ with mock.patch.object(__main__, "__name__", "not-main"): assert __main__.init() is None
5,340,856
def get_stock_market_list(corp_cls: str, include_corp_name=True) -> dict: """ 상장 회사 dictionary 반환 Parameters ---------- corp_cls: str Y: stock market(코스피), K: kosdaq market(코스닥), N: konex Market(코넥스) include_corp_name: bool, optional if True, returning dictionary includes corp_name(...
5,340,857
def evaluate_template(template: dict) -> dict: """ This function resolves the template by parsing the T2WML expressions and replacing them by the class trees of those expressions :param template: :return: """ response = dict() for key, value in template.items(): if key == 'qualifier': response[key] = [] ...
5,340,858
def get_CommandeProduits(path, prefix='CP_',cleaned=False): """ Read CSV (CommandeProduits) into Dataframe. All relevant columns are kept and renamed with prefix. Args: path (str): file path to CommandeProduits.csv prefix (str): All relevant columns are renamed with prefix Returns: ...
5,340,859
def hist_equal(image, hist): """ Equalize an image based on a histogram. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. hist : af.Array - Containing the histogram o...
5,340,860
def get_close_icon(x1, y1, height, width): """percentage = 0.1 height = -1 while height < 15 and percentage < 1.0: height = int((y2 - y1) * percentage) percentage += 0.1 return (x2 - height), y1, x2, (y1 + height)""" return x1, y1, x1 + 15, y1 + 15
5,340,861
def train_model(network, data, labels, batch_size, epochs, validation_data=None, verbose=True, shuffle=False): """ Train """ model = network.fit( data, labels, batch_size=batch_size, epochs=epochs, validation_data=validation_data, shuffle=s...
5,340,862
def taoyuan_agrichannel_irrigation_transfer_loss_rate(): """ Real Name: TaoYuan AgriChannel Irrigation Transfer Loss Rate Original Eqn: 0 Units: m3/m3 Limits: (None, None) Type: constant Subs: None This is "no loss rate" version. """ return 0
5,340,863
def mocked_requests() -> MockedRequests: """Return mocked requests library.""" mocked_requests = MockedRequests() with patch("libdyson.cloud.account.requests.request", mocked_requests.request): yield mocked_requests
5,340,864
def Setup(): """Sets up the logging environment.""" build_info = buildinfo.BuildInfo() log_file = r'%s\%s' % (GetLogsPath(), constants.BUILD_LOG_FILE) file_util.CreateDirectories(log_file) debug_fmt = ('%(levelname).1s%(asctime)s.%(msecs)03d %(process)d {} ' '%(filename)s:%(lineno)d] %(message...
5,340,865
def test_camera_association(focuser): """ Test association of Focuser with Camera after initialisation (getter, setter) """ sim_camera_1 = Camera() sim_camera_2 = Camera() # Cameras in the fixture haven't been associated with a Camera yet, this should work focuser.camera = sim_camera_1 assert fo...
5,340,866
def lambda_handler(event, context): """ Find and replace following words and outputs the result. Oracle -> Oracle© Google -> Google© Microsoft -> Microsoft© Amazon -> Amazon© Deloitte -> Deloitte© Example input: “We really like the new security features of Google Cloud”. Expected ...
5,340,867
def update_inv(X, X_inv, i, v): """Computes a rank 1 update of the the inverse of a symmetrical matrix. Given a symmerical matrix X and its inverse X^{-1}, this function computes the inverse of Y, which is a copy of X, with the i'th row&column replaced by given vector v. Parameters ---------- ...
5,340,868
def read_barcode_lineno_map(stream): """Build a map of barcodes to line number from a stream This builds a one based dictionary of barcode to line numbers. """ barcodes = {} reader = csv.reader(stream, delimiter="\t") for i, line in enumerate(reader): barcodes[line[0]] = i + 1 retu...
5,340,869
def match_in_candidate_innings(entry, innings, summary_innings, entities): """ :param entry: :param innings: innings to be searched in :param summary_innings: innings mentioned in the summary segment :param entities: total entities in the segment :return: """ entities_in_summary_inning =...
5,340,870
def checkpoint( name: Optional[str] = None, on_error: bool = True, cond: Union[bool, Callable[..., bool]] = False, ) -> Callable[[Callable], Any]: """ Create a checkpointing decorator. Args: ckpt_name (Optional[str]): Name of the checkpoint when saved. on_error (bool): Whether t...
5,340,871
def log_batch_stats(observes, actions, advantages, disc_sum_rew, episode, logger): """ Log various batch statistics """ logger.log({'_mean_obs': np.mean(observes), '_min_obs': np.min(observes), '_max_obs': np.max(observes), '_std_obs': np.mean(np.var(observes, axi...
5,340,872
def return_int(bit_len, unsigned=False): """ This function return the decorator that change return value to valid value. The target function of decorator should return only one value e.g. func(*args, **kargs) -> value: """ if bit_len not in VALID_BIT_LENGTH_OF_INT: err = "Value of bit_le...
5,340,873
def get_integral_curve(f, init_xy, x_end, delta): """ solve ode 'dy/dx=f(x,y)' with Euler method """ (x, y) = init_xy xs, ys = [x], [y] for i in np.arange(init_xy[0], x_end, delta): y += delta*f(x, y) x += delta xs.append(x) ys.append(y) return xs, ys
5,340,874
def compute_atime_posteriors(sg, proposals, global_srate=1.0, use_ar=False, raw_data=False, event_idx=None): """ compute the bayesian cross-correlation (logodds of signal under an AR noise model...
5,340,875
def search4vowels(pharse :str) -> set: """"Return any vowels found in a supplied word.""" vowels = set('aeiou') return vowels.intersection(set(pharse))
5,340,876
async def set_time(ctx, time: int): """Configures the timer countdown duration.""" if time <= 0: # Force duration to be 1 minute or longer em = Embed(title=':warning: Invalid `settime` Command Usage', description='Invalid timer...
5,340,877
def rsort(s): """Sort sequence s in ascending order. >>> rsort([]) [] >>> rsort([1]) [1] >>> rsort([1, 1, 1]) [1, 1, 1] >>> rsort([1, 2, 3]) [1, 2, 3] >>> rsort([3, 2, 1]) [1, 2, 3] >>> rsort([1, 2, 1]) [1, 1, 2] >>> rsort([1,2,3, 2, 1]) [1, 1, 2, 2, 3] ...
5,340,878
def xdg_data_home(): """Base directory where user specific data files should be stored.""" value = os.getenv('XDG_DATA_HOME') or '$HOME/.local/share/' return os.path.expandvars(value)
5,340,879
def read_starlight_output_syn_spec(lines): """ read syn_spec of starlight output """ Nl_obs = len(lines) wave = Column(np.zeros((Nl_obs, ), dtype=np.float), 'wave') flux_obs = Column(np.zeros((Nl_obs, ), dtype=np.float), 'flux_obs') flux_syn = Column(np.zeros((Nl_obs, ), dtype=np.float), 'flux_syn')...
5,340,880
def print_buttons(ids): """ids - [(int, str), ...] """ for ID,name in ids[::-1]: print (f'<button id="button{ID}">') print (name) print ('</button>')
5,340,881
def get_stations_trips(station_id): """ https://api.rasp.yandex.net/v1.0/schedule/ ? apikey=<ключ> & format=<формат> & station=<код станции> & lang=<язык> & [date=<дата>] & [transport_types=<тип транспорта>] & [system=<текущая система кодирования>] & [show_systems=<коды в ответе>] """ params = { 'apikey': RASP...
5,340,882
def createDir(dirPath): """ Creates a directory if it does not exist. :type dirPath: string :param dirPath: the path of the directory to be created. """ try: if os.path.dirname(dirPath) != "": os.makedirs(os.path.dirname(dirPath), exist_ok=True) # Python 3.2+ except Type...
5,340,883
def _compute_pairwise_kpt_distance(a, b): """ Args: a, b (poses): Two sets of poses to match Each "poses" is represented as a list of 3x17 or 4x17 np.ndarray """ res = np.zeros((len(a), len(b))) for i in range(len(a)): for j in range(len(b)): res[i, j] = pck_dista...
5,340,884
def _extract_dialog_node_name(dialog_nodes): """ For each dialog_node (node_id) of type *standard*, check if *title exists*. If exists, use the title for the node_name. otherwise, use the dialog_node For all other cases, use the dialog_node dialog_node: (dialog_node_title, dialog_node_type) In...
5,340,885
def _get_content(tax_id): """Get Kazusa content, either from cached file or remotely.""" target_file = os.path.join(DATA_DIR, "%s.txt" % tax_id) if not os.path.exists(target_file): url = ( "http://www.kazusa.or.jp/codon/cgi-bin/showcodon.cgi?" + "aa=1&style=N&species=%s" % t...
5,340,886
def create_supervisor_config_file( site_dir_name, wwwhisper_path, site_config_path, supervisor_config_path): """Creates site-specific supervisor config file. The file allows to start the wwwhisper application for the site. """ settings = """[program:wwwhisper-%s] command=%s/run_wwwhisper_for_site.s...
5,340,887
def search_all_entities(bsp, **search: Dict[str, str]) -> Dict[str, List[Dict[str, str]]]: """search_all_entities(key="value") -> {"LUMP": [{"key": "value", ...}]}""" out = dict() for LUMP_name in ("ENTITIES", *(f"ENTITIES_{s}" for s in ("env", "fx", "script", "snd", "spawn"))): entity_lump = getatt...
5,340,888
def pull_verbose(docker_client, repository, tag=None, log=True): """ Use low-level docker-py API to show status while pulling docker containers. Attempts to replicate docker command line output log - if True, logs the output, if False, prints the output """ for update in docker_client.api.p...
5,340,889
def expose_all(root_module: types.ModuleType, container_type: type): """ exposes all sub-modules and namespaces to be available under given container type (class) Args: root_module (types.ModuleType): module ns_type (type): namepace type (class) """ for path in root_module.__path__...
5,340,890
def is_probably_beginning_of_sentence(line): """Return True if this line begins a new sentence.""" # Check heuristically for a parameter list. for token in ['@', '-', r'\*']: if re.search(r'\s' + token + r'\s', line): return True stripped_line = line.strip() is_beginning_of_sent...
5,340,891
def default_attack_handler(deck, discard, hand, turn, supply, attack): """Handle some basic attacks in a default manner. Returns True iff the attack was handled.""" covertool.cover("domsim.py:219") if attack == COUNCIL_ROOM: # Not really an attack, but this is an easy way to handle it. ...
5,340,892
def solve_word_jumble(word_perms): """Solve a word jumble by unscrambling four jumbles, then a final jumble. Parameters: - words: list of strings, each is the scrambled letters for a single word - circles: list of strings, each marks whether the letter at that position in the solved anagram word...
5,340,893
def deprecate(remove_in, use_instead, module_name=None, name=None): """ Decorator that marks a function or class as deprecated. When the function or class is used, a warning will be issued. Args: remove_in (str): The version in which the decorated type will be removed. u...
5,340,894
def get_available_processors(): """Return the list of available processors modules.""" modules = [item.replace('.py', '') for item in os.listdir(PROCESSORS_DIR) if isfile(join(PROCESSORS_DIR, item))] return modules
5,340,895
def append_after(filename="", search_string="", new_string=""): """ Inserts a line of text to a file, after each line containing a specific string. """ out = "" with open(filename, 'r') as f: for line in f: out += line if search_string in line: out...
5,340,896
def hello_world(): """return bool if exists -> take in email""" email = request.json['email'] c = conn.cursor() c.execute("select * from Users where Users.email = {}".format(email)) result = False conn.commit() conn.close() return result
5,340,897
def get_model_relations( model: Callable, model_args: Optional[tuple] = None, model_kwargs: Optional[dict] = None, ): """ Infer relations of RVs and plates from given model and optionally data. See https://github.com/pyro-ppl/pyro/issues/949 for more details. This returns a dictionary with ...
5,340,898
def progress_enabled(): """ Checks if progress is enabled. To disable: export O4_PROGRESS=false """ return os.environ.get('O4_PROGRESS', 'true') == 'true'
5,340,899