code stringlengths 1 18.2k |
|---|
def raw(self) -> str: """ Return a raw document of the Identity :return: """ return """Version: {version} Type: Identity Currency: {currency} Issuer: {pubkey} UniqueID: {uid} Timestamp: {timestamp} """.format(version=self.version, currency=self.currency, pubkey=self.pubkey, uid=self.uid, timestamp=self.timestamp) |
def inline(self) -> str: """ Return an inline string of the Identity :return: """ return "{pubkey}:{signature}:{timestamp}:{uid}".format( pubkey=self.pubkey, signature=self.signatures[0], timestamp=self.timestamp, uid=self.uid) |
def _validate_extension(self): """Validates that source file extension is supported. :raises: UnsupportedExtensionError """ extension = self.fpath.split('.')[-1] if extension not in self.supported_extensions: raise UnsupportedExtensionError |
def convert_content(self) -> dict: """Convert content of source file into dict result.""" source_content = self.load_content() converted = {} tagged, content = self._get_tags_and_content(source_content) if tagged: converted.update(self._parse_tags(tagged)) if content: converted['content'] = content.strip() return conve... |
def _get_tags_and_content(self, content: str) -> typing.Tuple[str, str]: """Splits content into two string - tags part and another content.""" content_lines = content.split('\n') tag_lines = [] if content_lines[0] != '---': return '', content content_lines.pop(0) for line in content_lines: # type: str if line in ('---'... |
def parse(text): """ Parses the dependency schema from a given string (typically a container stdout log) """ found = re.findall(r'(?<=BEGIN_DEPENDENCIES_SCHEMA_OUTPUT>).*(?=<END_DEPENDENCIES_SCHEMA_OUTPUT)', text) dependency_results = [] for match in found: data = json.loads(match) validate(data) # will throw Validatio... |
def command(execute=None): # noqa: E501 """Execute a Command Execute a command # noqa: E501 :param execute: The data needed to execute this command :type execute: dict | bytes :rtype: Response """ if connexion.request.is_json: execute = Execute.from_dict(connexion.request.get_json()) # noqa: E501 if(not hasAccess()): r... |
def get_script(name=None): # noqa: E501 """Retrieve the contents of a script Retrieve the contents of a script # noqa: E501 :param name: The script name. :type name: str :rtype: Response """ if(not hasAccess()): return redirectUnauthorized() driver = LoadedDrivers.getDefaultBaseDriver() return Response(status=200, body... |
def comp_listing(request, directory_slug=None): """ Output the list of HTML templates and subdirectories in the COMPS_DIR """ context = {} working_dir = settings.COMPS_DIR if directory_slug: working_dir = os.path.join(working_dir, directory_slug) dirnames = [] templates = [] items = os.listdir(working_dir) templates = ... |
def comp(request, slug, directory_slug=None): """ View the requested comp """ context = {} path = settings.COMPS_DIR comp_dir = os.path.split(path)[1] template = "{0}/{1}".format(comp_dir, slug) if directory_slug: template = "{0}/{1}/{2}".format(comp_dir, directory_slug, slug) working_dir = os.path.join(path, slug) if ... |
def export_comps(request): """ Returns a zipfile of the rendered HTML templates in the COMPS_DIR """ in_memory = BytesIO() zip = ZipFile(in_memory, "a") comps = settings.COMPS_DIR static = settings.STATIC_ROOT or "" context = RequestContext(request, {}) context['debug'] = False # dump static resources # TODO: inspect e... |
= os.path.relpath(full_path, comps) template_path = os.path.join(comps.split('/')[-1], rel_path) html = render_to_string(template_path, context) # convert static refs to relative links depth = len(rel_path.split(os.sep)) - 1 if depth == 0: dotted_rel = '.' else: dotted_rel = '' i = 0 while i < depth: dotted_rel += '../... |
def from_signed_raw(cls: Type[PeerType], raw: str) -> PeerType: """ Return a Peer instance from a signed raw format string :param raw: Signed raw format string :return: """ lines = raw.splitlines(True) n = 0 version = int(Peer.parse_field("Version", lines[n])) n += 1 Peer.parse_field("Type", lines[n]) n += 1 currency =... |
def raw(self) -> str: """ Return a raw format string of the Peer document :return: """ doc = """Version: {0} Type: Peer Currency: {1} PublicKey: {2} Block: {3} Endpoints: """.format(self.version, self.currency, self.pubkey, self.blockUID) for _endpoint in self.endpoints: doc += "{0}\n".format(_endpoint.inline()) return... |
def generate_image_from_url(url=None, timeout=30): """ Downloads and saves a image from url into a file. """ file_name = posixpath.basename(url) img_tmp = NamedTemporaryFile(delete=True) try: response = requests.get(url, timeout=timeout) response.raise_for_status() except Exception as e: # NOQA return None, None img_tm... |
def is_rhyme(d, w1, w2): """check if words rhyme""" for p1 in d[w1]: # extract only "rhyming portion" p1 = p1.split("'")[-1] m = VOWELS_RE.search(p1) if not m: print(p1) p1 = p1[m.start():] for p2 in d[w2]: p2 = p2.split("'")[-1] m = VOWELS_RE.search(p2) if not m: print(w2, p2) p2 = p2[m.start():] if p1 == p2: return T... |
def init_perfect_ttable(words): """initialize (normalized) theta according to whether words rhyme""" d = read_celex() not_in_dict = 0 n = len(words) t_table = numpy.zeros((n, n + 1)) # initialize P(c|r) accordingly for r, w in enumerate(words): if w not in d: not_in_dict += 1 for c, v in enumerate(words): if c < r: t_t... |
def get_nested_dicts_with_key_value(parent_dict: dict, key, value): """Return all nested dictionaries that contain a key with a specific value. A sub-case of NestedLookup.""" references = [] NestedLookup(parent_dict, references, NestedLookup.key_value_equality_factory(key, value)) return (document for document, _ in re... |
def get_nested_dicts_with_key_containing_value(parent_dict: dict, key, value): """Return all nested dictionaries that contain a key with a specific value. A sub-case of NestedLookup.""" references = [] NestedLookup(parent_dict, references, NestedLookup.key_value_containing_value_factory(key, value)) return (document fo... |
def _nested_lookup(document, references, operation): """Lookup a key in a nested document, yield a value""" if isinstance(document, list): for d in document: for result in NestedLookup._nested_lookup(d, references, operation): yield result if isinstance(document, dict): for k, v in document.items(): if operation(k, v):... |
def step_random_processes(oscillators): """ Args: oscillators (list): A list of oscillator.Oscillator objects to operate on Returns: None """ if not rand.prob_bool(0.01): return amp_bias_weights = [(0.001, 1), (0.1, 100), (0.15, 40), (1, 0)] # Find out how many oscillators should move num_moves = iching.get_hexagram('N... |
def build_chunk(oscillators): """ Build an audio chunk and progress the oscillator states. Args: oscillators (list): A list of oscillator.Oscillator objects to build chunks from Returns: str: a string of audio sample bytes ready to be written to a wave file """ step_random_processes(oscillators) subchunks = [] for osc ... |
if (osc.amplitude.value > avg_amp and rand.prob_bool(0.1) or rand.prob_bool(0.01)): osc.amplitude.drift_target = rand.weighted_rand( [(-5, 1), (0, 10)]) osc.amplitude.change_rate = rand.weighted_rand( osc.amplitude.change_rate_weights) return new_chunk.astype(config.SAMPLE_DATA_TYPE).tostring() |
def shell(database='default'): """Runs the command-line client for the specified database. """ target = engine[database] dialect = engine[database].dialect.name if dialect == 'mysql': args = ['mysql'] if target.url.username: args += ['--user=%s' % target.url.username] if target.url.password: args += ['--password=%s' % ... |
def parseprint(code, filename="<string>", mode="exec", **kwargs): """Parse some code from a string and pretty-print it.""" node = parse(code, mode=mode) # An ode to the code print(dump(node, **kwargs)) |
def picknthweekday(year, month, dayofweek, hour, minute, whichweek): """dayofweek == 0 means Sunday, whichweek 5 means last instance""" first = datetime.datetime(year, month, 1, hour, minute) weekdayone = first.replace(day=((dayofweek-first.isoweekday())%7+1)) for n in range(whichweek): dt = weekdayone+(whichweek-n)*ON... |
def list(): """Return a list of all time zones known to the system.""" handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) tzkey = winreg.OpenKey(handle, TZKEYNAME) result = [winreg.EnumKey(tzkey, i) for i in range(winreg.QueryInfoKey(tzkey)[0])] tzkey.Close() handle.Close() return result |
def colorstart(fgcolor, bgcolor, weight): ''' Begin a text style. ''' if weight: weight = bold else: weight = norm if bgcolor: out('\x1b[%s;%s;%sm' % (weight, fgcolor, bgcolor)) else: out('\x1b[%s;%sm' % (weight, fgcolor)) |
def cprint(text, fg=grey, bg=blackbg, w=norm, cr=False, encoding='utf8'): ''' Print a string in a specified color style and then return to normal. def cprint(text, fg=white, bg=blackbg, w=norm, cr=True): ''' colorstart(fg, bg, w) out(text) colorend(cr) |
def bargraph(data, maxwidth, incolor=True, cbrackets=('\u2595', '\u258F')): ''' Creates a monochrome or two-color bar graph. ''' threshold = 100.0 // (maxwidth * 2) # if smaller than 1/2 of one char wide position = 0 begpcnt = data[0][1] * 100 endpcnt = data[-1][1] * 100 if len(data) < 1: return # Nada to do maxwidth =... |
0)) position = position + width # and graph if incolor and not (fgcolor is None): cprint(char * width, fgcolor, bgcolor, bold, False) else: out((char * width)) if i == (datalen - 1): # correct last one if position < maxwidth: if incolor: # char cprint(char * (maxwidth-position), fgcolor, bgcolor, bold, False) else: out... |
def rainbar(data, maxwidth, incolor=True, hicolor=True, cbrackets=('\u2595', '\u258F')): ''' Creates a "rainbar" style bar graph. ''' if not data: return # Nada to do datalen = len(data) endpcnt = data[-1][1] maxwidth = maxwidth - 2 # because of brackets # setup csi, csib, _, pal, rst, plen = get_palette(hicolor) empty... |
= fgcolor or min(int((j+offset)/bucket), (plen-1)) #~ colorind=fgcolor or get_color_index(j, offset,maxwidth,plen) if colorind == lastind: out(char) else: color = fgcolor or pal[colorind] out((csib % color) + char) lastind = colorind else: out((char * width)) if i == (datalen - 1): # check if last one correct if positi... |
def _set_linters(self): """Use user linters or all available when not specified.""" if 'linters' in self._config: self.user_linters = list(self._parse_cfg_linters()) self.linters = {linter: self._all_linters[linter] for linter in self.user_linters} else: self.linters = self._all_linters |
def print_config(self): """Print all yala configurations, including default and user's.""" linters = self.user_linters or list(self.linters) print('linters:', ', '.join(linters)) for key, value in self._config.items(): if key != 'linters': print('{}: {}'.format(key, value)) |
def _parse_cfg_linters(self): """Return valid linter names found in config files.""" user_value = self._config.get('linters', '') # For each line of "linters" value, use comma as separator for line in user_value.splitlines(): yield from self._parse_linters_line(line) |
def get_linter_config(self, name): """Return linter options without linter name prefix.""" prefix = name + ' ' return {k[len(prefix):]: v for k, v in self._config.items() if k.startswith(prefix)} |
def _merge(cls, default, user): """Append user options to default options. Return yala section.""" section = cls._CFG_SECTION merged = default[section] if section not in user: return merged user = user[section] for key, value in user.items(): if key in merged: merged[key] += ' ' + value else: merged[key] = value return... |
def as_text(str_or_bytes, encoding='utf-8', errors='strict'): """Return input string as a text string. Should work for input string that's unicode or bytes, given proper encoding. >>> print(as_text(b'foo')) foo >>> b'foo'.decode('utf-8') == u'foo' True """ if isinstance(str_or_bytes, text): return str_or_bytes return s... |
def get_safe_path(in_str): """Return `in_str` converted to a string that can be be safely used as a path (either filename, or directory name). >>> print(get_safe_path("hello world, what's up?.txt")) hello_world__what_s_up_.txt Surrounding spaces are removed, and other "bad characters" are replaced with an underscore. T... |
norm_str = _SAFE_PATH_RE.sub( '_', unicodedata.normalize('NFKD', as_text(in_str)).strip()) if len(norm_str.strip('.')) == 0: # making sure the normalized result is non-empty, and not just dots raise ValueError(in_str) return norm_str[:_MAX_PATH_NAME_LEN] |
def attempt_dev_link_via_import(self, egg): """Create egg-link to FS location if an egg is found through importing. Sometimes an egg *is* installed, but without a proper egg-info file. So we attempt to import the egg in order to return a link anyway. TODO: currently it only works with simple package names like "psycopg... |
def _install_exception_handler(self): """ Installs a replacement for sys.excepthook, which handles pretty-printing uncaught exceptions. """ def handler(t, value, traceback): if self.args.verbose: sys.__excepthook__(t, value, traceback) else: sys.stderr.write('%s\n' % unicode(value).encode('utf-8')) sys.excepthook = han... |
def strip_encoding_cookie(filelike): """Generator to pull lines from a text-mode file, skipping the encoding cookie if it is found in the first two lines. """ it = iter(filelike) try: first = next(it) if not cookie_comment_re.match(first): yield first second = next(it) if not cookie_comment_re.match(second): yield seco... |
def source_to_unicode(txt, errors='replace', skip_encoding_cookie=True): """Converts a bytes string with python source code to unicode. Unicode strings are passed through unchanged. Byte strings are checked for the python source file encoding cookie to determine encoding. txt can be either a bytes buffer or a string co... |
def decode_source(source_bytes): """Decode bytes representing source code and return the string. Universal newline support is used in the decoding. """ # source_bytes_readline = io.BytesIO(source_bytes).readline # encoding, _ = detect_encoding(source_bytes_readline) newline_decoder = io.IncrementalNewlineDecoder(None, ... |
def requires_subrepo(func: Callable) -> Callable: """ Decorator that requires the `git subrepo` command to be accessible before calling the given function. :param func: the function to wrap :return: the wrapped function """ def decorated(*args, **kwargs): try: run([GIT_COMMAND, _GIT_SUBREPO_COMMAND, "--version"]) excep... |
def clone(location: str, directory: str, *, branch: str=None, tag: str=None, commit: str=None, author_name: str=None, author_email: str=None) -> Commit: """ Clones the repository at the given location as a subrepo in the given directory. :param location: the location of the repository to clone :param directory: the dir... |
commit reference of the checkout """ if os.path.exists(directory): raise ValueError(f"The directory \"{directory}\" already exists") if not os.path.isabs(directory): raise ValueError(f"Directory must be absolute: {directory}") if branch and tag: raise ValueError(f"Cannot specify both branch \"{branch}\" and tag \"{tag}... |
execution_environment=execution_environment) except RunException as e: if re.search("Can't clone subrepo. (Unstaged|Index has) changes", e.stderr) is not None: raise UnstagedChangeException(git_root) from e elif "Command failed:" in e.stderr: try: repo_info = run([GIT_COMMAND, _GIT_LS_REMOTE_COMMAND, location]) if not ... |
def status(directory: str) -> Tuple[RepositoryLocation, Branch, Commit]: """ Gets the status of the subrepo that has been cloned into the given directory. :param directory: the directory containing the subrepo :return: a tuple consisting of the URL the subrepo is tracking, the branch that has been checked out and the c... |
def pull(directory: str) -> Commit: """ Pulls the subrepo that has been cloned into the given directory. :param directory: the directory containing the subrepo :return: the commit the subrepo is on """ if not os.path.exists(directory): raise ValueError(f"No subrepo found in \"{directory}\"") try: result = run([GIT_COMM... |
def cached(fn, size=32): ''' this decorator creates a type safe lru_cache around the decorated function. Unlike functools.lru_cache, this will not crash when unhashable arguments are passed to the function''' assert callable(fn) assert isinstance(size, int) return overload(fn)(lru_cache(size, typed=True)(fn)) |
def translate(client, event, channel, nick, rest): """ Translate a phrase using Google Translate. First argument should be the language[s]. It is a 2 letter abbreviation. It will auto detect the orig lang if you only give one; or two languages joined by a |, for example 'en|de' to trans from English to German. Follow t... |
"An error occurred. " "Are you sure {langpair} is a valid language?") return tmpl.format(**vars()) |
def get_model(app_dot_model): """ Returns Django model class corresponding to passed-in `app_dot_model` string. This is helpful for preventing circular-import errors in a Django project. Positional Arguments: ===================== - `app_dot_model`: Django's `<app_name>.<model_name>` syntax. For example, the default Dj... |
def match_modules(allowed_modules): """Creates a matcher that matches a list/set/tuple of allowed modules.""" cleaned_allowed_modules = [ utils.mod_to_mod_name(tmp_mod) for tmp_mod in allowed_modules ] cleaned_split_allowed_modules = [ tmp_mod.split(".") for tmp_mod in cleaned_allowed_modules ] cleaned_allowed_modules ... |
def match_classes(allowed_classes): """Creates a matcher that matches a list/tuple of allowed classes.""" cleaned_allowed_classes = [ utils.cls_to_cls_name(tmp_cls) for tmp_cls in allowed_classes ] def matcher(cause): cause_cls = None cause_type_name = cause.exception_type_names[0] try: cause_cls_idx = cleaned_allowed_... |
def combine_or(matcher, *more_matchers): """Combines more than one matcher together (first that matches wins).""" def matcher(cause): for sub_matcher in itertools.chain([matcher], more_matchers): cause_cls = sub_matcher(cause) if cause_cls is not None: return cause_cls return None return matcher |
def getTWFiles(self): """Get data files with Twitter messages (tweets). Each item is a list of pickle files on the ../data/tw/ directory (probably with some hashtag or common theme). Use social.tw.search and social.tw.stream to get tweets. Tweets are excluded from package to ease sharing.""" ddir="../data/tw/" # get fi... |
def run_cmd(cmd, log='log.log', cwd='.', stdout=sys.stdout, bufsize=1, encode='utf-8'): """ Runs a command in the backround by creating a new process and writes the output to a specified log file. :param log(str) - log filename to be used :param cwd(str) - basedir to write/create the log file :param stdout(pipe) - stdo... |
proc.communicate() with open(logfile, 'w') as f: if out: f.write(out) else: f.write(err) |
def touch_log(log, cwd='.'): """ Touches the log file. Creates if not exists OR updates the modification date if exists. :param log: :return: nothing """ logfile = '%s/%s' % (cwd, log) with open(logfile, 'a'): os.utime(logfile, None) |
def create(output_dir): """Create a new collector or actor""" template_path = os.path.join(os.path.dirname(__file__), 'project_template') click.secho('Let\'s create a new component!', fg='green') name = click.prompt('What is the name of this component (ex. python-pip)?') click.secho('') click.secho('We assume this will... |
{project_dir}` and try running `dependencies test`!'.format(name=name, project_dir=project_dir), fg='green') click.secho( 'We started you out with a fully functioning component based in python.\n' + 'Once you\'ve got a handle on how it works then you can change it to whatever language you want.' ) |
def validate(text, file, schema_type): """Validate JSON input using dependencies-schema""" content = None if text: print('Validating text input...') content = text if file: print('Validating file input...') content = file.read() if content is None: click.secho('Please give either text input or a file path. See help for... |
def run(self): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ connectable = engine_from_config( self._config.get_section(self._config.config_ini_section), prefix='sqlalchemy.', poolclass=pool.NullPool) with connectable.connect() as conne... |
def _clean(): """ Cleans up build dir """ LOGGER.info('Cleaning project directory...') folders_to_cleanup = [ '.eggs', 'build', f'{config.PACKAGE_NAME()}.egg-info', ] for folder in folders_to_cleanup: if os.path.exists(folder): LOGGER.info('\tremoving: %s', folder) shutil.rmtree(folder) |
def str_to_application_class(self, an_app_key): """a configman compatible str_to_* converter""" try: app_class = str_to_python_object(self.apps[an_app_key]) except KeyError: app_class = str_to_python_object(an_app_key) try: self.application_defaults = DotDict( app_class.get_application_defaults() ) except AttributeErro... |
def tokenise(template): '''A generator which yields Token instances''' upto = 0 lineno = 0 for m in tag_re.finditer(template): start, end = m.span() lineno = template.count('\n', 0, start) + 1 # Humans count from 1 # If there's a gap between our start and the end of the last match, # there's a Text node between. if upt... |
def delete(table, session, conds): """Performs a hard delete on a row, which means the row is deleted from the Savage table as well as the archive table. :param table: the model class which inherits from :class:`~savage.models.user_table.SavageModelMixin` and specifies the model of the user table from which we are quer... |
= _get_conditions_list(table, conds, archive=False) session.execute( sa.delete(table, whereclause=_get_conditions(conds_list)) ) |
def get( table, session, version_id=None, t1=None, t2=None, fields=None, conds=None, include_deleted=True, page=1, page_size=100, ): """ :param table: the model class which inherits from :class:`~savage.models.user_table.SavageModelMixin` and specifies the model of the user table from which we are querying :param sessi... |
if both t1 and t2 are none or unspecified, this will return the latest data (i.e. time slice of data now). This must either be a valid sql time string or a datetime.datetime object. :param fields: a list of strings which corresponds to columns in the table; If None or unspecified, returns all fields in the table. :para... |
include changes where ``deleted = 0`` i.e. the data was in the user table. :param page: the offset of the result set (1-indexed); i.e. if page_size is 100 and page is 2, the result set will contain results 100 - 199 :param page_size: upper bound on number of results to display. Note the actual returned result set may b... |
if t2 is None: # return a historical time slice rows = _get_historical_time_slice( table, session, t1, conds, include_deleted, limit, offset ) return _format_response(rows, fields, version_col_names) if t1 is None: t1 = datetime.utcfromtimestamp(0) rows = _get_historical_changes( table, session, conds, t1, t2, include_... |
def _format_response(rows, fields, unique_col_names): """This function will look at the data column of rows and extract the specified fields. It will also dedup changes where the specified fields have not changed. The list of rows should be ordered by the compound primary key which versioning pivots around and be in as... |
dictionaries representing rows from the ArchiveTable. :param fields: a list of strings of fields to be extracted from the archived row. """ output = [] old_id = None for row in rows: id_ = {k: row[k] for k in unique_col_names} formatted = {k: row[k] for k in row if k != 'data'} if id_ != old_id: # new unique versioned ... |
def _get_conditions(pk_conds, and_conds=None): """If and_conds = [a1, a2, ..., an] and pk_conds = [[b11, b12, ..., b1m], ... [bk1, ..., bkm]], this function will return the mysql condition clause: a1 & a2 & ... an & ((b11 and ... b1m) or ... (b11 and ... b1m)) :param pk_conds: a list of list of primary key constraints ... |
def _get_conditions_list(table, conds, archive=True): """This function returns a list of list of == conditions on sqlalchemy columns given conds. This should be treated as an or of ands. :param table: the user table model class which inherits from savage.models.SavageModelMixin :param conds: a list of dictionaries of k... |
table.version_columns: raise ValueError('{} is not one of the unique columns <{}>'.format( col_name, ','.join(table.version_columns) )) conditions.append(getattr(t, col_name) == value) all_conditions.append(conditions) return all_conditions |
def _get_limit_and_offset(page, page_size): """Returns a 0-indexed offset and limit based on page and page_size for a MySQL query. """ if page < 1: raise ValueError('page must be >= 1') limit = page_size offset = (page - 1) * page_size return limit, offset |
def _get_order_clause(archive_table): """Returns an ascending order clause on the versioned unique constraint as well as the version column. """ order_clause = [ sa.asc(getattr(archive_table, col_name)) for col_name in archive_table._version_col_names ] order_clause.append(sa.asc(archive_table.version_id)) return order... |
def add_resource_permissions(*args, **kwargs): """ This syncdb hooks takes care of adding a view permission too all our content types. """ # for each of our content types for resource in find_api_classes('v1_api', ModelResource): auth = resource._meta.authorization content_type = ContentType.objects.get_for_model(resou... |
def areObservableElements(self, elementNames): """ Mention if all elements are observable element. :param str ElementName: the element name to evaluate :return: true if is an observable element, otherwise false. :rtype: bool """ if not(hasattr(elementNames, "__len__")): raise TypeError( "Element name should be a array ... |
def isObservableElement(self, elementName): """ Mention if an element is an observable element. :param str ElementName: the element name to evaluate :return: true if is an observable element, otherwise false. :rtype: bool """ if not(isinstance(elementName, str)): raise TypeError( "Element name should be a string ." + "... |
def add(self, observableElement): """ add an observable element :param str observableElement: the name of the observable element :raises RuntimeError: if element name already exist in the store """ if observableElement not in self._observables: self._observables.append(observableElement) else: raise RuntimeError( "{0} ... |
def remove(self, observableElement): """ remove an obsrvable element :param str observableElement: the name of the observable element """ if observableElement in self._observables: self._observables.remove(observableElement) |
def install_config_kafka(self): """ install and config kafka :return: """ if self.prompt_check("Download and install kafka"): self.kafka_install() if self.prompt_check("Configure and autostart kafka"): self.kafka_config() |
def install_config_elastic(self): """ install and config elasticsearch :return: """ if self.prompt_check("Download and install elasticsearch"): self.elastic_install() if self.prompt_check("Configure and autostart elasticsearch"): self.elastic_config() |
def install_config_logstash(self): """ install and config logstash :return: """ if self.prompt_check("Download and install logstash"): self.logstash_install() if self.prompt_check("Configure and autostart logstash"): self.logstash_config() |
def install_config_kibana(self): """ install and config kibana :return: """ if self.prompt_check("Download and install kibana"): self.kibana_install() if self.prompt_check("Configure and autostart kibana"): self.kibana_config() |
def install_config_spark(self): """ install and config spark :return: """ if self.prompt_check("Download and install hadoop"): self.hadoop_install() if self.prompt_check("Download and install spark"): self.spark_install() if self.prompt_check("Configure spark"): self.spark_config() |
def add_slave_server(self): """ 添加slave服务器 :return: """ master = self.args.config[1] slave = self.args.add_slave # install java at slave server self.reset_server_env(slave, self.configure) if self.prompt_check("Update package at slave server"): self.update_source_list() self.common_update_sys() if self.prompt_check("In... |
self.configure[slave]['user'], self.configure[slave]['host'] )) # config slave and master if self.prompt_check("Configure master and slave server"): master = self.args.config[1] slave = self.args.add_slave if self.args.bigdata_app == 'spark': self.add_spark_slave(master, slave, self.configure) |
def get_file_content(url, comes_from=None): """Gets the content of a file; it may be a filename, file: URL, or http: URL. Returns (location, content)""" match = _scheme_re.search(url) if match: scheme = match.group(1).lower() if (scheme == 'file' and comes_from and comes_from.startswith('http')): raise InstallationErro... |
def url_to_path(url): """ Convert a file: URL to a path. """ assert url.startswith('file:'), ( "You can only turn file: urls into filenames (not %r)" % url) path = url[len('file:'):].lstrip('/') path = urllib.unquote(path) if _url_drive_re.match(path): path = path[0] + ':' + path[2:] else: path = '/' + path return path |
def path_to_url(path): """ Convert a path to a file: URL. The path will be made absolute. """ path = os.path.normcase(os.path.abspath(path)) if _drive_re.match(path): path = path[0] + '|' + path[2:] url = urllib.quote(path) url = url.replace(os.path.sep, '/') url = url.lstrip('/') return 'file:///' + url |
def path_to_url2(path): """ Convert a path to a file: URL. The path will be made absolute and have quoted path parts. """ path = os.path.normpath(os.path.abspath(path)) drive, path = os.path.splitdrive(path) filepath = path.split(os.path.sep) url = '/'.join([urllib.quote(part) for part in filepath]) if not drive: url =... |
def geturl(urllib2_resp): """ Use instead of urllib.addinfourl.geturl(), which appears to have some issues with dropping the double slash for certain schemes (e.g. file://). This implementation is probably over-eager, as it always restores '://' if it is missing, and it appears some url schemata aren't always followed ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.