code
stringlengths
1
18.2k
def info(): """ List information about this productive environment :return: """ print() print('root directory :', tasks.conf.APE_ROOT) print() print('active container :', os.environ.get('CONTAINER_NAME', '')) print() print('active product :', os.environ.get('PRODUCT_NAME', '')) print() print('ape feature selection :', ...
def cd(doi): """ cd to directory of interest(doi) a doi can be: herbert - the container named "herbert" sdox:dev - product "website" located in container "herbert" :param doi: :return: """ parts = doi.split(':') if len(parts) == 2: container_name, product_name = parts[0], parts[1] elif len(parts) == 1 and os.environ.ge...
def switch(poi): """ Zaps into a specific product specified by switch context to the product of interest(poi) A poi is: sdox:dev - for product "dev" located in container "sdox" If poi does not contain a ":" it is interpreted as product name implying that a product within this container is already active. So if this tas...
already zapped into a product in order # to enable simply switching products by doing ape zap prod. container_name = os.environ.get('CONTAINER_NAME') product_name = parts[0] else: print('unable to find poi: ', poi) sys.exit(1) if container_name not in tasks.get_containers(): raise ContainerNotFound('No such container %...
def install_container(container_name): """ Installs the container specified by container_name :param container_name: string, name of the container """ container_dir = os.path.join(os.environ['APE_ROOT_DIR'], container_name) if os.path.exists(container_dir): os.environ['CONTAINER_DIR'] = container_dir else: raise Contai...
def get_poi_tuple(poi=None): """ Takes the poi or None and returns the container_dir and the product name either of the passed poi (<container_name>: <product_name>) or from os.environ- :param poi: optional; <container_name>: <product_name> :return: tuple of the container directory and the product name """ if poi: part...
def validate_product_equation(poi=None): """ Validates the product equation. * Validates the feature order * Validates the product spec (mandatory functional features) :param poi: optional product of interest """ from . import utils from . import validators container_dir, product_name = tasks.get_poi_tuple(poi=poi) fea...
product equation\n' '\t\t=> Create spec file featuremodel/productline/<container>/product_spec.json' ) return spec_validator = validators.ProductSpecValidator(spec_path, product_name, feature_list) if not spec_validator.is_valid(): if spec_validator.get_errors_mandatory(): print('\t\tERROR: The following feature are mi...
def get_ordered_feature_list(info_object, feature_list): """ Orders the passed feature list by the given, json-formatted feature dependency file using feaquencer's topsort algorithm. :param feature_list: :param info_object: :return: """ feature_dependencies = json.load(open(info_object.feature_order_json)) feature_sele...
def config_to_equation(poi=None): """ Generates a product.equation file for the given product name. It generates it from the <product_name>.config file in the products folder. For that you need to have your project imported to featureIDE and set the correct settings. """ from . import utils container_dir, product_name ...
= '' feature_list.append(line) except IOError: print('{} does not exist. Make sure your config file exists.'.format(info_object.config_file_path)) feature_list = tasks.get_ordered_feature_list(info_object, feature_list) try: with open(info_object.equation_file_path, 'w') as eq_file: eq_file.writelines(feature_list) pri...
def token(cls: Type[SIGType], pubkey: str) -> SIGType: """ Return SIG instance from pubkey :param pubkey: Public key of the signature issuer :return: """ sig = cls() sig.pubkey = pubkey return sig
def token(cls: Type[CSVType], time: int) -> CSVType: """ Return CSV instance from time :param time: Timestamp :return: """ csv = cls() csv.time = str(time) return csv
def compose(self, parser: Any, grammar: Any = None, attr_of: str = None): """ Return the CSV(time) expression as string format :param parser: Parser instance :param grammar: Grammar :param attr_of: Attribute of... """ return "CSV({0})".format(self.time)
def token(cls: Type[CLTVType], timestamp: int) -> CLTVType: """ Return CLTV instance from timestamp :param timestamp: Timestamp :return: """ cltv = cls() cltv.timestamp = str(timestamp) return cltv
def token(cls: Type[XHXType], sha_hash: str) -> XHXType: """ Return XHX instance from sha_hash :param sha_hash: SHA256 hash :return: """ xhx = cls() xhx.sha_hash = sha_hash return xhx
def token(cls: Type[OperatorType], keyword: str) -> OperatorType: """ Return Operator instance from keyword :param keyword: Operator keyword in expression :return: """ op = cls(keyword) return op
def token(cls: Type[ConditionType], left: Any, op: Optional[Any] = None, right: Optional[Any] = None) -> ConditionType: """ Return Condition instance from arguments and Operator :param left: Left argument :param op: Operator :param right: Right argument :return: """ condition = cls() condition.left = left if op: condit...
def compose(self, parser: Any, grammar: Any = None, attr_of: str = None) -> str: """ Return the Condition as string format :param parser: Parser instance :param grammar: Grammar :param attr_of: Attribute of... """ if type(self.left) is Condition: left = "({0})".format(parser.compose(self.left, grammar=grammar, attr_of=...
def load_library(self, path): ''' Load a template library into the state. ''' module = import_module(path) self.tags.update(module.register.tags) self.helpers.update(module.register.helpers)
def get_default_logger(): """Returns default driver logger. :return: logger instance :rtype: logging.Logger """ handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) handler.setFormatter(logging.Formatter( "[%(levelname)1.1s %(asctime)s %(name)s] %(message)s", "%y%m%d %H:%M:%S")) logger_name = "pydbal" if C...
def ensure_connected(self): """Ensures database connection is still open.""" if not self.is_connected(): if not self._auto_connect: raise DBALConnectionError.connection_closed() self.connect()
def query(self, sql, *args, **kwargs): """Executes an SQL SELECT query, returning a result set as a Statement object. :param sql: query to execute :param args: parameters iterable :param kwargs: parameters iterable :return: result set as a Statement object :rtype: pydbal.statement.Statement """ self.ensure_connected() ...
def execute(self, sql, *args, **kwargs): """Executes an SQL INSERT/UPDATE/DELETE query with the given parameters and returns the number of affected rows. :param sql: statement to execute :param args: parameters iterable :param kwargs: parameters iterable :return: number of affected rows :rtype: int """ self.ensure_conn...
def begin_transaction(self): """Starts a transaction by suspending auto-commit mode.""" self.ensure_connected() self._transaction_nesting_level += 1 if self._transaction_nesting_level == 1: self._driver.begin_transaction() elif self._nest_transactions_with_savepoints: self.create_savepoint(self._get_nested_transaction_...
def commit(self): """Commits the current transaction.""" if self._transaction_nesting_level == 0: raise DBALConnectionError.no_active_transaction() if self._is_rollback_only: raise DBALConnectionError.commit_failed_rollback_only() self.ensure_connected() if self._transaction_nesting_level == 1: self._driver.commit() el...
def commit_all(self): """Commits all current nesting transactions.""" while self._transaction_nesting_level != 0: if not self._auto_commit and self._transaction_nesting_level == 1: return self.commit() self.commit()
def rollback(self): """Cancels any database changes done during the current transaction.""" if self._transaction_nesting_level == 0: raise DBALConnectionError.no_active_transaction() self.ensure_connected() if self._transaction_nesting_level == 1: self._transaction_nesting_level = 0 self._driver.rollback() self._is_rol...
def transaction(self, callback): """Executes a function in a transaction. The function gets passed this Connection instance as an (optional) parameter. If an exception occurs during execution of the function or transaction commit, the transaction is rolled back and the exception re-thrown. :param callback: the function...
def set_auto_commit(self, auto_commit): """Sets auto-commit mode for this connection. If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by a call to either the met...
def set_transaction_isolation(self, level): """Sets the transaction isolation level. :param level: the level to set """ self.ensure_connected() self._transaction_isolation_level = level self._platform.set_transaction_isolation(level)
def get_transaction_isolation(self): """Returns the currently active transaction isolation level. :return: the current transaction isolation level :rtype: int """ if self._transaction_isolation_level is None: self._transaction_isolation_level = self._platform.get_default_transaction_isolation_level() return self._trans...
def set_nest_transactions_with_savepoints(self, nest_transactions_with_savepoints): """Sets if nested transactions should use savepoints. :param nest_transactions_with_savepoints: `True` or `False` """ if self._transaction_nesting_level > 0: raise DBALConnectionError.may_not_alter_nested_transaction_with_savepoints_in_...
def create_savepoint(self, savepoint): """Creates a new savepoint. :param savepoint: the name of the savepoint to create :raise: pydbal.exception.DBALConnectionError """ if not self._platform.is_savepoints_supported(): raise DBALConnectionError.savepoints_not_supported() self.ensure_connected() self._platform.create_sa...
def release_savepoint(self, savepoint): """Releases the given savepoint. :param savepoint: the name of the savepoint to release :raise: pydbal.exception.DBALConnectionError """ if not self._platform.is_savepoints_supported(): raise DBALConnectionError.savepoints_not_supported() if self._platform.is_release_savepoints_s...
def rollback_savepoint(self, savepoint): """Rolls back to the given savepoint. :param savepoint: the name of the savepoint to rollback to :raise: pydbal.exception.DBALConnectionError """ if not self._platform.is_savepoints_supported(): raise DBALConnectionError.savepoints_not_supported() self.ensure_connected() self._p...
def insert(self, table, values): """Inserts a table row with specified data. :param table: the expression of the table to insert data into, quoted or unquoted :param values: a dictionary containing column-value pairs :return: last inserted ID """ assert isinstance(values, dict) sb = self.sql_builder().insert(table) for...
def update(self, table, values, identifier): """Updates a table row with specified data by given identifier. :param table: the expression of the table to update quoted or unquoted :param values: a dictionary containing column-value pairs :param identifier: the update criteria; a dictionary containing column-value pairs...
def delete(self, table, identifier): """Deletes a table row by given identifier. :param table: the expression of the table to update quoted or unquoted :param identifier: the delete criteria; a dictionary containing column-value pairs :return: the number of affected rows :rtype: int """ assert isinstance(identifier, di...
def _execute(self, sql, params): """Execute statement with reconnecting by connection closed error codes. 2006 (CR_SERVER_GONE_ERROR): MySQL server has gone away 2013 (CR_SERVER_LOST): Lost connection to MySQL server during query 2055 (CR_SERVER_LOST_EXTENDED): Lost connection to MySQL server at '%s', system error: %d ...
def requirements(self): """ Verifica che tutti i pacchetti apt necessari al "funzionamento" della classe siano installati. Se cosi' non fosse li installa. """ cache = apt.cache.Cache() for pkg in self.pkgs_required: try: pkg = cache[pkg] if not pkg.is_installed: try: pkg.mark_install() cache.commit() except LockFailedE...
def set_shares(self): """ Setta la variabile membro 'self.samba_shares' il quale e' una lista di dizionari con i dati da passare ai comandi di "umount" e "mount". I vari dizionari sono popolati o da un file ~/.pygmount.rc e da un file passato dall'utente. """ if self.filename is None: self.filenamename = os.path.expand...
def run(self): """ Esegue il montaggio delle varie condivisioni chiedendo all'utente username e password di dominio. """ logging.info('start run with "{}" at {}'.format( self.username, datetime.datetime.now())) progress = Progress(text="Controllo requisiti software...", pulsate=True, auto_close=True) progress(1) try: s...
entry_text='password', password=True) if self.domain_password is None or len(self.domain_password) == 0: error_msg = u"Inserimento di una password di dominio vuota" ErrorMessage(self.msg_error % error_msg) sys.exit(3) progress_msg = u"Collegamento unità di rete in corso..." progress = Progress(text=progress_msg, pulsat...
# smonto la condivisione prima di rimontarla umont_cmd = self.cmd_umount % share if self.verbose: logging.warning("Umount command: %s" % umont_cmd) if not self.dry_run: umount_p = subprocess.Popen(umont_cmd, shell=True) returncode = umount_p.wait() time.sleep(2) mount_cmd = self.cmd_mount % share if self.verbose: place...
def _dump(db): """ Dump :class:`mongomock.database.Database` to dict data. """ db_data = {"name": db.name, "_collections": dict()} for col_name, collection in iteritems(db._collections): if col_name != "system.indexes": col_data = { "_documents": collection._documents, "_uniques": collection._uniques, } db_data["_colle...
def _load(db_data, db): """ Load :class:`mongomock.database.Database` from dict data. """ if db.name != db_data["name"]: raise ValueError("dbname doesn't matches! Maybe wrong database data.") db.__init__(client=db._client, name=db.name) for col_name, col_data in iteritems(db_data["_collections"]): collection = db.get_c...
def dump_db(db, file, pretty=False, overwrite=False, verbose=True): """ Dump :class:`mongomock.database.Database` to a local file. Only support ``*.json`` or ``*.gz`` (compressed json file) :param db: instance of :class:`mongomock.database.Database`. :param file: file path. :param pretty: bool, toggle on jsonize into p...
def load_db(file, db, verbose=True): """ Load :class:`mongomock.database.Database` from a local file. :param file: file path. :param db: instance of :class:`mongomock.database.Database`. :param verbose: bool, toggle on log. :return: loaded db. """ db_data = json.load(file, verbose=verbose) return _load(db_data, db)
def makeOrmValuesSubqueryCondition(ormSession, column, values: List[Union[int, str]]): """ Make Orm Values Subquery :param ormSession: The orm session instance :param column: The column from the Declarative table, eg TableItem.colName :param values: A list of string or int values """ if isPostGreSQLDialect(ormSession.b...
def makeCoreValuesSubqueryCondition(engine, column, values: List[Union[int, str]]): """ Make Core Values Subquery :param engine: The database engine, used to determine the dialect :param column: The column, eg TableItem.__table__.c.colName :param values: A list of string or int values """ if isPostGreSQLDialect(engine)...
def resource_path(package_name: str, relative_path: typing.Union[str, Path]) -> Path: """ Get absolute path to resource, works for dev and for PyInstaller """ relative_path = Path(relative_path) methods = [ _get_from_dev, _get_from_package, _get_from_sys, ] for method in methods: path = method(package_name, relative_pa...
def _verbose_message(message, *args, **kwargs): """Print the message to stderr if -v/PYTHONVERBOSE is turned on.""" verbosity = kwargs.pop('verbosity', 1) if sys.flags.verbose >= verbosity: if not message.startswith(('#', 'import ')): message = '# ' + message print(message.format(*args), file=sys.stderr)
def _open_connection(self): """ Open a new connection socket to the CPS.""" if self._scheme == 'unix': self._connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0) self._connection.connect(self._path) elif self._scheme == 'tcp': self._connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.SOL_...
def _send_request(self, xml_request): """ Send the prepared XML request block to the CPS using the corect protocol. Args: xml_request -- A fully formed xml request string for the CPS. Returns: The raw xml response string. Raises: ConnectionError -- Can't establish a connection with the server. """ if self._scheme == 'h...
def _send_http_request(self, xml_request): """ Send a request via HTTP protocol. Args: xml_request -- A fully formed xml request string for the CPS. Returns: The raw xml response string. """ headers = {"Host": self._host, "Content-Type": "text/xml", "Recipient": self._storage} try: # Retry once if failed in case the so...
def _send_socket_request(self, xml_request): """ Send a request via protobuf. Args: xml_request -- A fully formed xml request string for the CPS. Returns: The raw xml response string. """ def to_variant(number): buff = [] while number: byte = number % 128 number = number // 128 if number > 0: byte |= 0x80 buff.append(c...
from_variant(stream[offset:]) offset += used wire_type = field_header & 0x07 field_id = field_header >> 3 if wire_type==2: message_lenght, used = from_variant(stream[offset:]) offset += used fields[field_id] = stream[offset:offset+message_lenght] offset += message_lenght elif wire_type==0: fields[field_id], used = from...
<< 24) else: raise ConnectionError() def socket_send(data): sent_bytes = 0 failures = 0 total_bytes = len(data) while sent_bytes < total_bytes: sent = self._connection.send(data[sent_bytes:]) if sent == 0: failures += 1 if failures > 5: raise ConnectionError() continue sent_bytes += sent def socket_recieve(lenght): tot...
id=3 error message # TODO: check for and raise errors return response[1]
def similar_text(self, *args, **kwargs): """ Search for documents that are similar to directly supplied text or to the textual content of an existing document. Args: text -- Text to found something similar to. len -- Number of keywords to extract from the source. quota -- Minimum number of keywords matching in the dest...
def main(arguments=None): """ *The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command* """ # setup the command-line util settings su = tools( arguments=arguments, docString=__doc__, logLevel="WARNING", options_first=False, projectName="rockfinder", defaultSe...
RUN THE cl_utils.py AT %s' % (startTime,)) # CALL FUNCTIONS/OBJECTS if init: from os.path import expanduser home = expanduser("~") filepath = home + "/.config/rockfinder/rockfinder.yaml" cmd = """open %(filepath)s""" % locals() p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True) try: cmd = """open %(filepath)s""" % lo...
= dataSet.markdown(filepath=None) elif rst: output = dataSet.reST(filepath=None) print output if "dbConn" in locals() and dbConn: dbConn.commit() dbConn.close() ## FINISH LOGGING ## endTime = times.get_now_sql_datetime() runningTime = times.calculate_time_difference(startTime, endTime) log.info('-- FINISHED ATTEMPT TO ...
def safe_division(dividend, divisor): """ :return: nan: invalid arguments :rtype: float """ try: divisor = float(divisor) dividend = float(dividend) except (TypeError, ValueError, AssertionError): return float("nan") try: return dividend / divisor except (ZeroDivisionError): return float("nan")
def compare_version(lhs_version, rhs_version): """ <Major>.<Minor>.<Revision> 形式のバージョン文字列を比較する。 :return: 0<: LHSがRHSより小さい 0: LHS == RHS 0>: LHSがRHSより大きい :rtype: int """ lhs_major, lhs_minor, lhs_revision = [ int(v) for v in lhs_version.split(".")] rhs_major, rhs_minor, rhs_revision = [ int(v) for v in rhs_version.split...
def dump_dict(dict_input, indent=4): """ 辞書型変数を文字列に変換して返す """ dict_work = dict(dict_input) """ for key, value in six.iteritems(dict_input): if any([f(value) for f in (is_float, isDict, is_list_or_tuple)]): dict_work[key] = value continue try: dict_work[key] = str(value) except: dict_work[key] = str(type(value)) dict_wo...
def makedirs_safe(fulldir): """Creates a directory if it does not exists. Takes into consideration concurrent access support. Works like the shell's 'mkdir -p'. """ try: if not os.path.exists(fulldir): os.makedirs(fulldir) except OSError as exc: # Python >2.5 import errno if exc.errno == errno.EEXIST: pass else: raise
def str_(name): """Return the string representation of the given 'name'. If it is a bytes object, it will be converted into str. If it is a str object, it will simply be resurned.""" if isinstance(name, bytes) and not isinstance(name, str): return name.decode('utf8') else: return name
def qsub(command, queue=None, cwd=True, name=None, deps=[], stdout='', stderr='', env=[], array=None, context='grid', hostname=None, memfree=None, hvmem=None, gpumem=None, pe_opt=None, io_big=False): """Submits a shell job to a given grid queue Keyword parameters: command The command to be submitted to the grid queue A...
variables that will be set on the environment running the command of your choice. array If set should be either: 1. a string in the form m[-n[:s]] which indicates the starting range 'm', the closing range 'n' and the step 's'. 2. an integer value indicating the total number of jobs to be submitted. This is equivalent o...
individual control of each job. The environment variable SGE_TASK_ID will be set on the executing process automatically by SGE and indicates the unique identifier in the range for which the current job instance is for. context The setshell context in which we should try a 'qsub'. Normally you don't need to change the d...
only if mem is not set (cf. qsub -l h_vmem=<...>) gpumem Applicable only for GPU-based queues. If set, it asks for the GPU queue with a minimum amount of memory. The amount should not be more than 24. (cf. qsub -l gpumem=<...>) hostname If set, it asks the queue to use only a subset of the available nodes Symbols: | fo...
isinstance(queue, six.string_types) and queue not in ('all.q', 'default'): scmd += ['-l', queue] if memfree: scmd += ['-l', 'mem_free=%s' % memfree] if hvmem: scmd += ['-l', 'h_vmem=%s' % hvmem] if gpumem: scmd += ['-l', 'gpumem=%s' % gpumem] if io_big: scmd += ['-l', 'io_big'] if hostname: scmd += ['-l', 'hostname=%s'...
+= ['-e', stdout] scmd += ['-terse'] # simplified job identifiers returned by the command line for k in env: scmd += ['-v', k] if array is not None: scmd.append('-t') if isinstance(array, six.string_types): try: i = int(array) scmd.append('1-%d:1' % i) except ValueError: #must be complete... scmd.append('%s' % array) i...
def qstat(jobid, context='grid'): """Queries status of a given job. Keyword parameters: jobid The job identifier as returned by qsub() context The setshell context in which we should try a 'qsub'. Normally you don't need to change the default. This variable can also be set to a context dictionary in which case we just ...
kv = QSTAT_FIELD_SEPARATOR.split(s, 1) if len(kv) == 2: retval[kv[0]] = kv[1] return retval
def qdel(jobid, context='grid'): """Halts a given job. Keyword parameters: jobid The job identifier as returned by qsub() context The setshell context in which we should try a 'qsub'. Normally you don't need to change the default. This variable can also be set to a context dictionary in which case we just setup using t...
def update_state(world): """ Increment the world state, determining which cells live, die, or appear. Args: world (list[list]): A square matrix of cells Returns: None """ world_size = len(world) def wrap(index): """Wrap an index around the other end of the array""" return index % world_size for x in range(world_size): ...
cell with two or three live neighbours lives if not (live_neighbor_count == 2 or live_neighbor_count == 3): world[x][y].value = False else: # Any dead cell with exactly three live neighbours comes alive if live_neighbor_count == 3: world[x][y].value = True
def click_event(event): """On click, bring the cell under the cursor to Life""" grid_x_coord = int(divmod(event.x, cell_size)[0]) grid_y_coord = int(divmod(event.y, cell_size)[0]) world[grid_x_coord][grid_y_coord].value = True color = world[x][y].color_alive.get_as_hex() canvas.itemconfig(canvas_grid[grid_x_coord][grid...
def draw_canvas(): """Render the tkinter canvas based on the state of ``world``""" for x in range(len(world)): for y in range(len(world[x])): if world[x][y].value: color = world[x][y].color_alive.get_as_hex() else: color = world[x][y].color_dead.get_as_hex() canvas.itemconfig(canvas_grid[x][y], fill=color)
def div(p, q): """ ``p / q`` returning the correct infinity instead of raising ZeroDivisionError. """ from math import copysign if q != 0.0: # Normal case, no infinities. return p / q elif p == 0.0: return p / q # Doesn't return, raises an Exception. elif copysign(1, q) > 0: # q is +0.0, return inf with same sign as p....
def _make_context(context=None): """Create the namespace of items already pre-imported when using shell. Accepts a dict with the desired namespace as the key, and the object as the value. """ namespace = {'db': db, 'session': db.session} namespace.update(_iter_context()) if context is not None: namespace.update(context...
def init(**kwargs): """Initialize the specified names in the specified databases. The general process is as follows: - Ensure the database in question exists - Ensure all tables exist in the database. """ # TODO: Iterate through all engines in name set. database = kwargs.pop('database', False) if database and not datab...
def clear(**kwargs): """Clear the specified names from the specified databases. This can be highly destructive as it destroys tables and when all names are removed from a database, the database itself. """ database = kwargs.pop('database', False) expression = lambda target, table: table.drop(target) test = lambda x, ta...
def flush(**kwargs): """Flush the specified names from the specified databases. This can be highly destructive as it destroys all data. """ expression = lambda target, table: target.execute(table.delete()) test = lambda target, table: not table.exists(target) op(expression, reversed(metadata.sorted_tables), test=test, ...
def is_table_included(table, names): """Determines if the table is included by reference in the names. A table can be named by its component or its model (using the short-name or a full python path). eg. 'package.models.SomeModel' or 'package:SomeModel' or 'package' would all include 'SomeModel'. """ # No names indicat...
def autocomplete(): """Command and option completion for the main option parser (and options) and its subcommands (and options). Enable by sourcing one of the completion shell scripts (bash or zsh). """ # Don't complete if user hasn't sourced bash_completion file. if 'PIP_AUTO_COMPLETE' not in os.environ: return cwords...
not current.startswith('-'): installed = [] lc = current.lower() for dist in get_installed_distributions(local_only=True): if dist.key.startswith(lc) and dist.key not in cwords[1:]: installed.append(dist.key) # if there are no dists installed, fall back to option completion if installed: for dist in installed: print(di...
main parser only when necessary if current.startswith('-') or current.startswith('--'): subcommands += [opt.get_opt_string() for opt in parser.option_list if opt.help != optparse.SUPPRESS_HELP] print(' '.join([x for x in subcommands if x.startswith(current)])) sys.exit(1)
def secret_loader(self, callback): """ Decorate a method that receives a key id and returns a secret key """ if not callback or not callable(callback): raise Exception("Please pass in a callable that loads secret keys") self.secret_loader_callback = callback return callback
def context_loader(self, callback): """ Decorate a method that receives a key id and returns an object or dict that will be available in the request context as g.cavage_context """ if not callback or not callable(callback): raise Exception("Please pass in a callable that loads your context.") self.context_loader_callba...
def replay_checker(self, callback): """ Decorate a method that receives the request headers and returns a bool indicating whether we should proceed with the request. This can be used to protect against replay attacks. For example, this method could check the request date header value is within a delta value of the serv...
def parse(self, response): """ 从 self.data 中将文章信息格式化为 :class:`.MoearPackageMobiItem` """ # 工作&输出路径 self.template_dir = self.settings.get('TEMPLATE_DIR') shutil.rmtree( self.settings.get('BUILD_SOURCE_DIR'), ignore_errors=True) self.build_source_dir = utils.mkdirp( self.settings.get('BUILD_SOURCE_DIR')) # 获取Post模板对象 tem...
def filter_images_urls(image_urls, image_filter, common_image_filter=None): ''' 图片链接过滤器,根据传入的过滤器规则,对图片链接列表进行过滤并返回结果列表 :param list(str) image_urls: 图片链接字串列表 :param list(str) image_filter: 过滤器字串列表 :param list(str) common_image_filter: 可选,通用的基础过滤器, 会在定制过滤器前对传入图片应用 :return: 过滤后的结果链接列表,以及被过滤掉的链接列表 :rtype: list(str), list(st...
def generate_mobi_file(self): ''' 使用 :mod:`subprocess` 模块调用 ``KindleGen`` 工具, 将已准备好的书籍源文件编译生成 ``mobi`` 文件 ''' opf_file = os.path.join(self.build_source_dir, 'moear.opf') command_list = [self.kg, opf_file] output = subprocess.Popen( command_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False).communicate()...
def closed(self, reason): ''' 异步爬取本地化处理完成后,使用结果数据,进行输出文件的渲染,渲染完毕, 调用 :meth:`.MobiSpider.generate_mobi_file` 方法,生成目标 ``mobi`` 文件 ''' # 拷贝封面&报头图片文件 utils.mkdirp(os.path.join(self.build_source_dir, 'images')) self._logger.info(self.options) shutil.copy( self.options.get('img_cover'), os.path.join(self.build_source_dir, 'i...
Template(fh.read()) # 渲染toc.ncx目标文件 toc_path = os.path.join(self.build_source_dir, 'misc', 'toc.ncx') utils.mkdirp(os.path.dirname(toc_path)) with codecs.open(toc_path, 'wb', 'utf-8') as fh: fh.write(template_toc.render( data=self.data, spider=self.spider, options=self.options)) # 获取toc.html模板对象 template_toc_path = os....
def makeicons(source): """ Create all the neccessary icons from source image """ im = Image.open(source) for name, (_, w, h, func) in icon_sizes.iteritems(): print('Making icon %s...' % name) tn = func(im, (w, h)) bg = Image.new('RGBA', (w, h), (255, 255, 255)) x = (w / 2) - (tn.size[0] / 2) y = (h / 2) - (tn.size[1] /...