content
stringlengths
22
815k
id
int64
0
4.91M
def is_anno_end_marker(tag): """ Checks for the beginning of a new post """ text = tag.get_text() m = anno_end_marker_regex.match(text) if m: return True else: return False
39,800
def test_enum_idx_explicit(): """ Check behaviour of an explicitly valued indexed enumeration """ @packtype.enum() class DummyEnum: """ Test description 12345 """ KEY_A : Constant(desc="Description A") = 0 KEY_B : Constant(desc="Description B") = 1 KEY_C : Constant(desc="Desc...
39,801
async def fetch_and_parse(session, url): """ Parse a fatality page from a URL. :param aiohttp.ClientSession session: aiohttp session :param str url: detail page URL :return: a dictionary representing a fatality. :rtype: dict """ # Retrieve the page. # page = await fetch_text(session...
39,802
def wmt_diag_base(): """Set of hyperparameters.""" hparams = iwslt_diag() hparams.batch_size = 4096 hparams.num_hidden_layers = 6 hparams.hidden_size = 512 hparams.filter_size = 2048 hparams.num_heads = 8 # VAE-related flags. hparams.latent_size = 512 hparams.n_posterior_layers = 4 hparams.n_decod...
39,803
def K_axialbending(EA, EI_x, EI_y, x_C=0, y_C=0, theta_p=0): """ Axial bending problem. See KK for notations. """ H_xx = EI_x*cos(theta_p)**2 + EI_y*sin(theta_p)**2 H_yy = EI_x*sin(theta_p)**2 + EI_y*cos(theta_p)**2 H_xy = (EI_y-EI_x)*sin(theta_p)*cos(theta_p) return np.array([ [EA ...
39,804
def get_closest_intersection_pt_dist(path1, path2): """Returns the manhattan distance from the start location to the closest intersection point. Args: path1: the first path (list of consecutive (x,y) tuples) path2: the secong path Returns: int of lowest manhattan distance ...
39,805
def is_voiced_offset(c_offset): """ Is the offset a voiced consonant """ return c_offset in VOICED_LIST
39,806
def create_cloudwatch_event(app_name, env, region, rules): """Create cloudwatch event for lambda from rules. Args: app_name (str): name of the lambda function env (str): Environment/Account for lambda function region (str): AWS region of the lambda function rules (dict): Trigger...
39,807
def dc_generator(noise_dim=NOISE_DIM): """Generate images from a random noise vector. Inputs: - z: TensorFlow Tensor of random noise with shape [batch_size, noise_dim] Returns: TensorFlow Tensor of generated images, with shape [batch_size, 784]. """ model = tf.keras.models.Sequenti...
39,808
def save_vocab(dict_path, token_dict, encoding="utf-8"): """保存词典为文件""" with open(dict_path, "w", encoding=encoding) as fp: for k, v in sorted(token_dict.items(), key=lambda s: s[1]): fp.write(k + "\n")
39,809
async def flipcoin(ctx): """flips a coin""" pick = ['heads','tails'] flip = random.choice(pick) await bot.say ("The coin landed on `" + flip + '`!')
39,810
def add_boundary_label(lbl, dtype=np.uint16): """ Find boundary labels for a labelled image. Parameters ---------- lbl : array(int) lbl is an integer label image (not binarized). Returns ------- res : array(int) res is an integer label image with boundary encoded as 2. ...
39,811
def kmax(array, k): """ return k largest values of a float32 array """ I = np.zeros(k, dtype='int64') D = np.zeros(k, dtype='float32') ha = float_minheap_array_t() ha.ids = swig_ptr(I) ha.val = swig_ptr(D) ha.nh = 1 ha.k = k ha.heapify() ha.addn(array.size, swig_ptr(array)) h...
39,812
def p_simple_base_type(p): # noqa """simple_base_type : BOOL | BYTE | UBYTE | SHORT | USHORT | INT | UINT | FLOAT | LONG ...
39,813
def adcp_ins2earth(u, v, w, heading, pitch, roll, vertical): """ Description: This function converts the Instrument Coordinate transformed velocity profiles to the Earth coordinate system. The calculation is defined in the Data Product Specification for Velocity Profile and Echo I...
39,814
def strength(data,l): """ Returns the strength of earthquake as tuple (P(z),S(xy)) """ # FFT # https://momonoki2017.blogspot.com/2018/03/pythonfft-1-fft.html # Fast Fourier Transform # fx = np.fft.fft(data[0]) # fy = np.fft.fft(data[1]) # fz = np.fft.fft(data[2]) # What's is the...
39,815
def commit_signal(data_id): """Nudge manager at the end of every Data object save event.""" if not getattr(settings, "FLOW_MANAGER_DISABLE_AUTO_CALLS", False): immediate = getattr(settings, "FLOW_MANAGER_SYNC_AUTO_CALLS", False) async_to_sync(manager.communicate)( data_id=data_id, sa...
39,816
def get_packages_by_commits( repository: str, commits: list, package_limit=1, ecosystem='maven') -> list: """Get package name from git repository and commit hash. A git handler is created and modified files are searched by the given commit. Package is inferred based on those...
39,817
def humanize(tag, value): """Make the metadata value human-readable :param tag: The key of the metadata value :param value: The actual raw value :return: Returns ``None`` or a human-readable version ``str`` :rtype: ``str`` or ``None`` """ for formatter in find_humanizers(tag): human...
39,818
def cartesian(sequences, dtype=None): """ Generate a cartesian product of input arrays. Parameters ---------- sequences : list of array-like 1-D arrays to form the cartesian product of. dtype : data-type, optional Desired output data-type. Returns ------- out : ndar...
39,819
def test_unavailable_range(pool): """Test proper generator returned for unused pool.""" assert list(pool._unavailable_range()) == [x for x in range(pool.maxsize)]
39,820
def nasa_date_to_iso(datestr): """Convert the day-number based NASA format to ISO. Parameters ---------- datestr : str Date string in the form Y-j Returns ------- Datestring in ISO standard yyyy-mm-ddTHH:MM:SS.MMMMMM """ date = dt.datetime.strptime(datestr, nasa_date_format...
39,821
def with_cloud_emulators(*emulator_names): """Decorator for starting cloud emulators from a unittest.TestCase.""" def decorator(cls): """Decorator.""" class Wrapped(cls): """Wrapped class.""" @classmethod def setUpClass(cls): """Class setup.""" for emulator_name in emula...
39,822
def auto_label_color(labels): """ ???+ note "Create a label->hex color mapping dict." """ use_labels = set(labels) use_labels.discard(module_config.ABSTAIN_DECODED) use_labels = sorted(use_labels, reverse=False) assert len(use_labels) <= 20, "Too many labels to support (max at 20)" pale...
39,823
def dedentString(text): """Dedent the docstring, so that docutils can correctly render it.""" dedent = min([len(match) for match in space_re.findall(text)] or [0]) return re.compile('\n {%i}' % dedent, re.M).sub('\n', text)
39,824
def preprocess(df): """Preprocess the DataFrame, replacing identifiable information""" # Usernames: <USER_TOKEN> username_pattern = r"(?<=\B|^)@\w{1,18}" df.text = df.text.str.replace(username_pattern, "<USERNAME>") # URLs: <URL_TOKEN> url_pattern = ( r"https?://(?:[a-zA-Z]|[0-9]|[$-_@.&...
39,825
def benchmark( algorithm, elements: List[str], value: str, repeat: int = 10 ) -> None: """Search for a value in elements using the given algorithm.""" times: List[int] = [] for i in range(repeat): print(f"[{i + 1}/{repeat}] Searching...", end="", flush=True) start_time = time.perf_count...
39,826
def mobilenetv3_large_w7d20(**kwargs): """ MobileNetV3 Small 224/0.35 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chainer/model...
39,827
def random_forest_classifier(model, inputs, method="predict_proba"): """ Creates a SKAST expression corresponding to a given random forest classifier """ trees = [decision_tree(estimator.tree_, inputs, method="predict_proba", value_transform=lambda v: v/len(model.estimators_)) for estimator...
39,828
def show_compass_calibration(clb_upi, version="3"): """Show compass calibration data for given `clb_upi`.""" db = km3db.core.DBManager() compass_upi = clbupi2compassupi(clb_upi) compass_model = compass_upi.split("/")[1] print("Compass UPI: {}".format(compass_upi)) print("Compass model: {}".forma...
39,829
def apply_proxies(proxies): """Read in skaffold.yaml, apply proxies as Docker --build-args, save as skaffold.dev.yaml.""" doc = yaml.load(open(base_yaml, 'r')) for artifact in doc['build']['artifacts']: if 'docker' not in artifact: artifact['docker'] = {} if 'buildArgs' not in ar...
39,830
def mock_get_settings(test): """ Decorator to mock :func:`cowbird.utils.get_settings` to allow retrieval of settings from :class:`DummyRequest`. .. warning:: Only apply on test methods (not on class TestCase) to ensure that :mod:`pytest` can collect them correctly. """ from cowbird.utils im...
39,831
def mean_absolute_deviation(numbers: List[float]) -> float: """ For a given list of input numbers, calculate Mean Absolute Deviation around the mean of this dataset. Mean Absolute Deviation is the average absolute difference between each element and a centerpoint (mean in this case): MAD = average |...
39,832
def save_markovianity(args, w_dict, neg_log_p, empirical_freq, expected_freq, class_names): """ Save the results of the comparison to an HMM on the bout types Parameters: args: Argparse object containing general parameters: w_dict: the motif output in numerical form neg_log_p: negative log P va...
39,833
def _convert_to_interbatch_order(order: pd.Series, batch: pd.Series) -> pd.Series: """ Convert the order values from a per-batch order to a interbatch order. Parameters ---------- order: pandas.Series order and batch must share the same index, size and be of...
39,834
def jsonfy(grammar_file: str, input_string: str): """display a json data by converting an input_string using pegtree grammar_file Args: grammar_file (str): pegtree grammar filename input_string (str): input string for converting """ start, path = start_option(grammar_file.strip()) ...
39,835
def CV_INIT_3X3_DELTAS(*args): """CV_INIT_3X3_DELTAS(double deltas, int step, int nch)""" return _cv.CV_INIT_3X3_DELTAS(*args)
39,836
def is_instance_cold_migrated_alarm(alarms, instance, guest_hb=False): """ Check if an instance cold-migrated alarm has been raised """ expected_alarm = {'alarm_id': fm_constants.FM_ALARM_ID_VM_COLD_MIGRATED, 'severity': fm_constants.FM_ALARM_SEVERITY_CRITICAL} return _instanc...
39,837
def precision_macro(y_target, y_predicted): """ y_target: m x n 2D array. {0, 1} real labels y_predicted: m x n 2D array {0, 1} prediction labels m (y-axis): # of instances n (x-axis): # of classes """ average = 'macro' score = precision_score(y_target, y_predicted, ave...
39,838
def checkParameter(): """ function: check parameter """ if g_opts.clusterUser == "": GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50001"] % 'U' + ".") if g_opts.action == "": GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50001"] % 't' + ".") if g_opts.action != "reset": ...
39,839
def layout(mat,widths=None,heights=None): """layout""" ncol=len(mat[0]) nrow=len(mat) arr=[] list(map(lambda m: arr.extend(m),mat)) rscript='layout(matrix(c(%s), %d, %d, byrow = TRUE),' %(str(arr)[1:-1],nrow,ncol) if widths: rscript+='widths=c(%s),' %(str(widths)[1:-1]) if h...
39,840
def get_file_language(filename, text=None): """Get file language from filename""" ext = osp.splitext(filename)[1] if ext.startswith('.'): ext = ext[1:] # file extension with leading dot language = ext if not ext: if text is None: text, _enc = encoding.read(filename) ...
39,841
def _get_output_name(fpattern,file_ind,ind): """ Returns an output name for volumetric image This function returns a file output name for the image volume based on the names of the file names of the individual z-slices. All variables are kept the same as in the original filename, but the z values ar...
39,842
def MatchNameComponent(key, name_list, case_sensitive=True): """Try to match a name against a list. This function will try to match a name like test1 against a list like C{['test1.example.com', 'test2.example.com', ...]}. Against this list, I{'test1'} as well as I{'test1.example'} will match, but not I{'test...
39,843
def dump_json(data_obj,file_path: Union[str, Path]): """dump a data object in a file """ with open(file_path,'w') as f: json.dump(data_obj,f,indent=4,sort_keys=True)
39,844
def news_api(): """Uses news API and returns a dictionary containing news """ news_base_url = "https://newsapi.org/v2/top-headlines?" news_api_key = keys["news"] country = location["country"] news_url = news_base_url + "country=" + country + "&apiKey=" + news_api_key n_api = requests.get(news_ur...
39,845
def plot_chains(mcmc, figsize=(20, 20)): """Summary Args: mcmc (MCMC): Description out_dir (str): Description """ params = [*mcmc.prior_ranges.keys()] for param in params: plt.figure(figsize=figsize) plt.subplot(2,1,1) for i, chain in enumerate(mcmc.cha...
39,846
def compress(mesh, engine_name="draco"): """ Compress mesh data. Args: mesh (:class:`Mesh`): Input mesh. engine_name (``string``): Valid engines are: * ``draco``: `Google's Draco engine <https://google.github.io/draco/>`_ [#]_ Returns: A binary...
39,847
def _is_syntax_is_missing(language): """ download the grammar for a specific language if the files is missing @param language language: python, sqlite, ... @return grammar file """ locations = { "R": "https://github.com/antlr/grammars-v4/tree/master/r...
39,848
def get_hotkey_next(config: configparser.RawConfigParser): """ 获取热键:下一个桌面背景 """ return __get_hotkey(config, 'Hotkey', 'hk_next')
39,849
def ensure_enum_member(value: Optional[Any], enum_class: Type[Enum]) -> None: """Raise an EnumMemberError if passed value is not in given enum class.""" # Python 3.8 compatibility, see https://docs.python.org/3/whatsnew/3.7.html#id5 with warnings.catch_warnings(): warnings.filterwarnings("ignore", ...
39,850
def abs_to_rel_f(vector, cell, pbc): """ Converts a position vector in absolute coordinates to relative coordinates for a film system. """ # TODO this currently only works if the z-coordinate is the one with no pbc # Therefore if a structure with x non pbc is given this should also work. # m...
39,851
def get_soup(url): """ Returns beautiful soup object of given url. get_soup(str) -> object(?) """ req = urllib2.Request(url) response = urllib2.urlopen(req) html = response.read() soup = bs4(html) return soup
39,852
def internal_server_error(error): """ Handles unexpected server error with 500_SERVER_ERROR """ message = error.message or str(error) app.logger.info(message) return make_response(jsonify(status=500, error='Internal Server Error', message=message), 500)
39,853
def diffsnorms(A, S, V, n_iter=20): """ 2-norm accuracy of a Schur decomp. of a matrix. Computes an estimate snorm of the spectral norm (the operator norm induced by the Euclidean vector norm) of A-VSV', using n_iter iterations of the power method started with a random vector; n_iter must be a ...
39,854
def get_subclasses_recursively(_class: type, _seen: set = None) -> typing.Generator: """ itersubclasses(cls) Generator over all subclasses of a given class, in depth first order. >>> list(get_subclasses_recursively(int)) == [bool] True >>> class A(object): pass >>> class B(A): pass >>>...
39,855
def unmount_ramdisk(dev_path, path): """Unmount RAM disk with `dev_path` and `path`.""" run('umount', path) run('diskutil', 'eject', dev_path) run('rm', '-r', path)
39,856
def data_selection(workload: spec.Workload, input_queue: Iterator[Tuple[spec.Tensor, spec.Tensor]], optimizer_state: spec.OptimizerState, current_param_container: spec.ParameterContainer, hyperparameters: spec.Hyperparamters, ...
39,857
def graph_cases_factory(selenium): """ :type selenium: selenium.webdriver.remote.webdriver.WebDriver :rtype: callable :return: Constructor method to create a graph cases factory with a custom host. """ return lambda host: GraphCaseFactory(selenium=selenium, host=host)
39,858
def clean_scene_from_file(file_name): """ Args: file_name: The name of the input sequence file Returns: Name of the scene used in the sequence file """ scene = scenename_from_file(file_name) print('Scene: ', scene) mesh_file = SCENE_PATH + scene + '/10M_clean.ply' return ...
39,859
def _non_overlapping_chunks(seq, size): """ This function takes an input sequence and produces chunks of chosen size that strictly do not overlap. This is a much faster implemetnation than _overlapping_chunks and should be preferred if running on very large seq. Parameters ---------- seq : ...
39,860
def load_data(path="/home/bumsoo/Data/Planetoid", dataset="cora"): """ ind.[:dataset].x => the feature vectors of the training instances (scipy.sparse.csr.csr_matrix) ind.[:dataset].y => the one-hot labels of the labeled training instances (numpy.ndarray) ind.[:dataset].allx => the feature vect...
39,861
def test_disarmed(): """Test disarmed slugify.""" nikola.utils.USE_SLUGIFY = False o = nikola.utils.slugify(u'Zażółć gęślą jaźń!-123.456', lang='pl') assert o == u'Zażółć gęślą jaźń!-123.456' assert isinstance(o, nikola.utils.unicode_str) nikola.utils.USE_SLUGIFY = True
39,862
def Compute_Error(X_data, pinn, K, mu, Lf, deltamean, epsilon, ndim) : """ Function to determine error for input data X_data :param array X_data: input data for PINN :param PINN pinn: PINN under investigation :param float K: key parameter for using trapezoidal rule and estimating the number of requ...
39,863
def sort_fiducials(qr_a, qr_b): """Sort 2d fiducial markers in a consistent ordering based on their relative positions. In general, when we find fiducials in an image, we don't expect them to be returned in a consistent order. Additionally, the image coordinate may be rotated from image to image. He...
39,864
def form_render(path: str, **kwargs) -> str: """ Just jinja2 """ file_text = Path(path).read_text() template = jinja2.Template(file_text) return template.render(**kwargs)
39,865
def revision_call_handlers(self, record): # 对logging标准模块打猴子补丁。主要是使父命名空间的handler不重复记录当前命名空间日志已有种类的handler。 """ 重要。这可以使同名logger或父logger随意添加同种类型的handler,确保不会重复打印。 :param self: :param record: :return: """ """ Pass a record to all relevant handlers. Loop through all handlers for this ...
39,866
def _post_startup(started_all, wait_for_server): """Post startup actions.""" if started_all: # let's give the whole system a while to breathe time.sleep(float(context.config.userdata.get('breath_time', 5))) else: raise Exception('Server failed to start in under {s} seconds'. ...
39,867
def _names(fg, bg): """3/4 bit encoding part c.f. https://en.wikipedia.org/wiki/ANSI_escape_code#3.2F4_bit Parameters: """ if not (fg is None or fg in _FOREGROUNDS): raise ValueError('Invalid color name fg = "{}"'.format(fg)) if not (bg is None or bg in _BACKGROUNDS): raise Va...
39,868
def preprocess(code): """Preprocess a code by removing comments, version and merging includes.""" if code: #code = remove_comments(code) code = merge_includes(code) return code
39,869
def _from_schemas_get_model( stay_within_model: bool, schemas: _oa_types.Schemas, schema: _oa_types.Schema ) -> types.ModelArtifacts: """ Get artifacts for a model. Assume the schema is valid. Args: schema: The schema of the model to get artifacts for. schemas: All defined schemas ...
39,870
def cli(): """Discord profiles picture & banner generator cli""" # If there are no args if len(sys.argv) < 2: print("Please specify an image") sys.exit(1) # Load the image arg = sys.argv[1] # If it's a link if re.match(r'(http|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^...
39,871
def solution2(inp): """Solves the second part of the challenge""" return "done"
39,872
def juld_to_grdt(juld: JulianDay) -> GregorianDateTime: """ユリウス通日をグレゴリオ曆の日時に變換する.""" A = math.floor(juld.julian_day + 68569.5) B = juld.julian_day + 0.5 a = math.floor(A / 36524.25) b = A - math.floor(36524.25 * a + 0.75) c = math.floor((b + 1) / 365.25025) d = b - math.floor(365.25 * c) + 3...
39,873
def users_all(request): """ Returns name + surname and email of all users Note: This type of function can only be justified when considering the current circumstances: An *INTERNAL* file sharing app (used by staff) Hence, all names and emails may be fetched be other authenticated users ...
39,874
def _resolve_categorical_entities(request, responder): """ This function retrieves all categorical entities as listed below and filters the knowledge base using these entities as filters. The final search object containing the shortlisted employee data is returned back to the calling function. """ ...
39,875
def filter_c13(df): """ Filter predicted formulas with 13C. Returns filtered df and n excluded """ shape_i = df.shape[0] df = df[df['C13'] == 0] df = df.reset_index(drop=True) shape_f = df.shape[0] n_excluded = shape_i - shape_f return df, n_excluded
39,876
def getContent(url): """ 此函数用于抓取返回403禁止访问的网页 """ random_header = random.choice(HEARDERS) """ 对于Request中的第二个参数headers,它是字典型参数,所以在传入时 也可以直接将个字典传入,字典中就是下面元组的键值对应 """ req = Request(url) req.add_header("User-Agent", random_header) req.add_header("Host", "datachart....
39,877
def neighbour(x,y,image): """Return 8-neighbours of image point P1(x,y), in a clockwise order""" img = image.copy() x_1, y_1, x1, y1 = x-1, y-1, x+1, y+1; return [img[x_1][y], img[x_1][y1], img[x][y1], img[x1][y1], img[x1][y], img[x1][y_1], img[x][y_1], img[x_1][y_1]]
39,878
def CTlog(importedFile): """Processes CT Log file and outputs data in text window. """ parametersDict = {} # New dictionary holding data from log file. studyInfo = [] # List for creation of file name. # Opens and parses the data from log file with open(importedFile, 'r') as textInput: fo...
39,879
def _load_saved_files( dir_path: str, load_adata: bool, map_location: Optional[Literal["cpu", "cuda"]] = None, ): """Helper to load saved files.""" setup_dict_path = os.path.join(dir_path, "attr.pkl") adata_path = os.path.join(dir_path, "adata.h5ad") varnames_path = os.path.join(dir_path, "v...
39,880
def deconv2d(x, kernel, output_shape, strides=(1, 1), border_mode='valid', dim_ordering='default', image_shape=None, filter_shape=None): """2D deconvolution (i.e. transposed convolution). # Arguments x: input tensor. kernel: kernel tensor. output_s...
39,881
def template(m1, m2): """ :param m1: :param m2: :return: """ c_mass = chirp_mass(m1, m2) B = 16.6 # In seconds to - 5/8 t = np.linspace(0, 0.45, 10000) tc = 0.48 gw_frequency = B * c_mass ** (-5 / 8) * (tc - t) ** (-3 / 8) t_h = np.linspace(-450, 0, 10000) t_merge_...
39,882
def _como_hasheable(matriz): """Retorna una copia hasheable (y por tanto inmutable) de `matriz`.""" return tuple(tuple(fila) for fila in matriz)
39,883
def diff(*args, **kwargs): """ Return a diff between two hex list :param args: :param kwargs: :return: """ skip_if_same = True if kwargs.get("skip_if_same", False): skip_if_same = kwargs["skip_if_same"] if len(args) != 2: raise NotImplementedError("Only comparison of ...
39,884
def gravity_effect(position, other_position): """Return effect other_position has on position.""" if position == other_position: return 0 elif position > other_position: return -1 return 1
39,885
def Import(): """ Loads and merges a Katana file into the current one. @type fileName: C{str} @type floatNodes: C{bool} @rtype: C{list} of L{Node} @param fileName: The name of the file or the ID of the asset to import. @param floatNodes: Flag that controls whether to make nodes interact...
39,886
def add_task(request): """add new task""" if request.method == "POST": #check whether name is empty or not if request.POST.get('name') != '': name = request.POST.get('name') priority = request.POST.get('priority') task = Task(name=name,priority=priority) ...
39,887
def rots(n_phi_pairs): """ From the provided list of (axis,angle) pairs, construct the product of rotations roti(axis0,angle0) *** roti(axis1,angle1) ... Because rotation of q by A is achieved through A***q***conj(A), rotate( A *** B, q ) is the same as rotate( A, rotate(B, q...
39,888
def n_cr_shell( thickness, radius, length ): """ Critical compressive load for cylindrical shell. Calculates the critical load for a cylindrical shell under pure compression and assumes uniform stress distribution. Calculation according to EN1993-1-6 [1], Annex D. ...
39,889
def handle_todoweek(bot, ievent): """ no arguments - show time related todo items for this week """ name = ievent.user.data.name or ievent.channel todo = TodoList(name) todoos = todo.withintime(today(), today()+7*24*60*60) saytodo(bot, ievent, todoos, name)
39,890
def unique_slug(s, model, num_chars=50): """ Return slug of num_chars length unique to model `s` is the string to turn into a slug `model` is the model we need to use to check for uniqueness """ slug = slugify(s) slug = slug[:num_chars].strip('-') while True: dup = model.objects...
39,891
def _to_vertexes(data): """create points at every vertex, incl holes""" # create new file outfile = GeoTable() outfile.fields = list(data.fields) # loop points if "LineString" in data.type: for feat in data: if "Multi" in feat.geometry["type"]: for l...
39,892
def _load(fname) : """ Load a cached file and return the resulting object @param fname: file name """ try : f = open(fname) return pickle.load(f) finally : f.close()
39,893
def client_job(id_to_send,msg_to_send,gr): """does a client.start and send the messages to the needed ppl""" client = TelegramClient(tlt_conf.sess, tlt_conf.api_id, tlt_conf.api_hash) client.start() deelay=0 with client: client.get_participants(gr[0]) for i in range(0,len(iD_to_send)): try: cli...
39,894
def reale(x, com="error", tol=None, msg=None, xp=None): """Return real part of complex data (with error checking). Parameters ---------- x : array-like The data to check. com : {'warn', 'error', 'display', 'report'} Control rather to raise a warning, an error, or to just display to ...
39,895
def find_less_than_or_equal(series_key, value): """Find the largest value less-than or equal-to the given value. Args: series_key: An E-Series key such as E24. value: The query value. Returns: The largest value from the specified series which is less-than or equal-to the qu...
39,896
def GetCommentsByMigration(migration): """Get the comments for a migration""" q = db.Query(models.Comment).filter('migration =', migration) return list(q.fetch(1000))
39,897
def get_proxy_list(html_response): """ Returns list of proxies scraped from html_response. :param html_response: Raw HTML text :type html_response: unicode :rtype: list[unicode] """ try: tmp = IPS_REGEXP.findall(html_response.replace("\n", ","))[0] proxies = tmp.split("</tex...
39,898
def test_should_have_env_defined(): """for auth user (the system account assigned to authenticate)""" assert 'OS_USERNAME' in os.environ assert 'OS_USER_DOMAIN_NAME' in os.environ assert 'OS_PASSWORD' in os.environ assert 'OS_AUTH_URL' in os.environ assert 'OS_PROJECT_NAME' in os.environ ass...
39,899