code
stringlengths
1
18.2k
def get_nendo (): """今は何年度?""" y, m = map(int, time.strftime("%Y %m").split()) return y if m >= 4 else y - 1
def find_files(self): '''Find files in `paths` which match valid extensions''' for path in self.paths: for subpath, dirs, files in os.walk(path): for filename in files: (name, ext) = os.path.splitext(filename) if ext in self.extensions: yield os.path.join(subpath, filename)
def is_boolean(node): """Checks if node is True or False""" return any([ isinstance(node, ast.Name) and node.id in ('True', 'False'), hasattr(ast, 'NameConstant') # Support for Python 3 NameConstant and isinstance(node, getattr(ast, 'NameConstant')) # screw you pylint! and str(node.value) in ('True', 'False') ])
def call_name_is(siter, name): """Checks the function call name""" return ( isinstance(siter, ast.Call) and hasattr(siter.func, 'attr') and siter.func.attr == name )
def target_names(targets): """Retrieves the target names""" names = [] for entry in targets: if isinstance(entry, ast.Name): names.append(entry.id) elif isinstance(entry, ast.Tuple): for element in entry.elts: if isinstance(element, ast.Name): names.append(element.id) return names
def labeled(**kwargs): """decorator to give practices labels""" def for_practice(practice): """assigns label to practice""" practice.code = kwargs.pop('code') practice.msg = kwargs.pop('msg') practice.solution = kwargs.pop('solution') return practice return for_practice
def daemonize(pidfile=None): """ Turn the running process into a proper daemon according to PEP3143. Args: pidfile --The pidfile to create. """ # Prevent core dumps resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) # Change working directory os.chdir("/") # Change file creation mask os.umask(0) # Detach process context:...
not open pass # Create pidfile if pidfile is None or pidfile.strip() == '': logger.debug('Empty pidfile set') else: pid = os.getpid() try: with open(pidfile, 'w') as f: f.write('{}\n'.format(pid)) f.close() except EnvironmentError: logger.error('Failed to create pidfile at {}'.format(pidfile)) def remove_pid_file(): os...
def config_str2dict(option_value): """ Parse the value of a config option and convert it to a dictionary. The configuration allows lines formatted like: foo = Bar:1,Baz,Flub:0.75 This gets converted to a dictionary: foo = { 'Bar': 1, 'Baz': 0, 'Flub': 0.75 } Args: option_value -- The config string to parse. """ dict = ...
def log_to_syslog(): """ Configure logging to syslog. """ # Get root logger rl = logging.getLogger() rl.setLevel('INFO') # Stderr gets critical messages (mostly config/setup issues) # only when not daemonized stderr = logging.StreamHandler(stream=sys.stderr) stderr.setLevel(logging.CRITICAL) stderr.setFormatter(logging...
def main(sid, token, to, from_, url): """Create, connect, and block on the listener worker.""" try: worker = APNSWorker(sid=sid, token=token, to=to, from_=from_, url=url) worker.connect() worker.run_forever() except KeyboardInterrupt: worker.close()
def getSaveFileName(self, *args, **kwargs): """ analogue to QtWidgets.QFileDialog.getSaveFileNameAndFilter but returns the filename + chosen file ending even if not typed in gui """ if 'directory' not in kwargs: if self.opts['save']: if self.opts['save']: kwargs['directory'] = self.opts['save'] fname = QtWidgets.QFileD...
def check_dependencies(req, indent=1, history=None): """ Given a setuptools package requirement (e.g. 'gryphon==2.42' or just 'gryphon'), print a tree of dependencies as they resolve in this environment. """ # keep a history to avoid infinite loops if history is None: history = set() if req in history: return history.a...
def load_dependencies(req, history=None): """ Load the dependency tree as a Python object tree, suitable for JSON serialization. >>> deps = load_dependencies('jaraco.packaging') >>> import json >>> doc = json.dumps(deps) """ if history is None: history = set() dist = pkg_resources.get_distribution(req) spec = dict( req...
def check_dependencies_remote(args): """ Invoke this command on a remote Python. """ cmd = [args.python, '-m', 'depends', args.requirement] env = dict(PYTHONPATH=os.path.dirname(__file__)) return subprocess.check_call(cmd, env=env)
def _send(self, line): """ Write a line of data to the server. Args: line -- A single line of data to write to the socket. """ if not line.endswith('\r\n'): if line.endswith('\n'): logger.debug('Fixing bare LF before sending data to socket') line = line[0:-1] + '\r\n' else: logger.debug( 'Fixing missing CRLF before sen...
def _read(self): """ Read a single response line from the server. """ line = '' finished = False while not finished: char = self._socket.recv(1) if char == '': return '' elif char == '\r': continue elif char == '\n': finished = True continue else: line = line + char logger.debug('Server sent: ' + line.rstrip()) return ...
def _peek(self, chars=1): """ Peek at the data in the server response. Peeking should only be done when the response can be predicted. Make sure that the socket will not block by requesting too much data from it while peeking. Args: chars -- the number of characters to peek. """ line = self._socket.recv(chars, socket.M...
def connect(self): """ Connect to TCP or domain socket, and process the server LMTP greeting. """ # extract proto from socket setting try: (proto, spec) = self.socket.split(':') except ValueError: raise DspamClientError( 'Failed to parse DSPAM socket specification, ' 'no proto found: ' + self.socket) if proto == 'unix'...
socket.socket( socket.AF_INET, socket.SOCK_STREAM) self._socket.connect((host, port)) except socket.error as err: self._socket = None raise DspamClientError( 'Failed to connect to DSPAM server at host {} ' 'port {}: {}'.format(host, port, err)) logger.debug( 'Connected to DSPAM server at host {}, port {}'.format( host,...
def lhlo(self): """ Send LMTP LHLO greeting, and process the server response. A regular LMTP greeting is sent, and if accepted by the server, the capabilities it returns are parsed. DLMTP authentication starts here by announcing the dlmtp_ident in the LHLO as our hostname. When the ident is accepted and DLMTP mode is e...
response') if resp[3] == ' ': # difference between "250-8BITMIME" and "250 SIZE" finished = True
def mailfrom(self, sender=None, client_args=None): """ Send LMTP MAIL FROM command, and process the server response. In DLMTP mode, the server expects the client to identify itself. Because the envelope sender is of no importance to DSPAM, the client is expected to send an identity and a password (dspam.conf: ServerPas...
by the client. These are in the form as they are passed to the command-line 'dspam' program. See man dspam(1) for details, and the process() or classify() methods in this class for simple examples. Args: sender -- The envelope sender to use in LMTP mode. client_args -- DSPAM parameters to pass to the server in DLMTP mo...
if not resp.startswith('250'): raise DspamClientError( 'Unexpected server response at MAIL FROM: ' + resp)
def rcptto(self, recipients): """ Send LMTP RCPT TO command, and process the server response. The DSPAM server expects to find one or more valid DSPAM users as envelope recipients. The set recipient will be the user DSPAM processes mail for. When you need want DSPAM to deliver the message itself, and need to pass the s...
def data(self, message): """ Send LMTP DATA command and process the server response. The server response is stored as a list of dicts in <DspamClient>.results, keyed on the recipient name(s). Depending on the server return data, different formats are available: * LMTP mode -- Dict containing 'accepted', a bool indicati...
result format yourself and decide whether that was acceptable for your use case. This is due to the fact that it's possible to configure the server to return non LMTP responses, even when in LMTP mode (see dspam.conf: ServerParameters). Note: while processing response data in stdout mode, it's not possible to relate th...
# Send message payload for line in message.split('\n'): if line == '.': # Dot stuffing line = '..' self._send(line) # Send end-of-data self._send('.\r\n') # Depending on server configuration, several responses are possible: # * Standard LMTP response code, once for each recipient: # 250 2.6.0 <bar> Message accepted for...
recipients will still be something indicating 'accepted'. peek = self._peek(24) if peek.startswith('250'): # Response is LTMP formatted regex = re.compile('250 \d\.\d\.\d <([^>]+)>') finished = False while not finished: resp = self._read() match = regex.match(resp) if not match: raise DspamClientError( 'Unexpected serv...
= ('user', 'result', 'class', 'probability', 'confidence', 'signature') self.results[rcpt] = dict(zip(fields, match.groups())) if self.results[rcpt]['signature'] == 'N/A': del(self.results[rcpt]['signature']) logger.debug( 'Message handled for recipient {} in DLMTP summary mode, ' 'result is {}'.format(rcpt, match.grou...
message body ' 'is {} chars'.format(rcpt, result, len(message))) message = '' # Remember next result result = resp[25:] elif resp == '.': # A single dot can signal end-of-data, or might be just # regular mail data. self._socket.setblocking(False) try: # If _peek() succeeds, we did not reach end-of-data yet # so it was ...
= resp else: message = message + '\r\n' + resp else: raise DspamClientError( 'Unexpected server response at END-OF-DATA: ' + resp)
def rset(self): """ Send LMTP RSET command and process the server response. """ self._send('RSET\r\n') resp = self._read() if not resp.startswith('250'): logger.warn('Unexpected server response at RSET: ' + resp) self._recipients = [] self.results = {}
def quit(self): """ Send LMTP QUIT command, read the server response and disconnect. """ self._send('QUIT\r\n') resp = self._read() if not resp.startswith('221'): logger.warning('Unexpected server response at QUIT: ' + resp) self._socket.close() self._socket = None self._recipients = [] self.results = {}
def process(self, message, user): """ Process a message. """ if not self._socket: self.connect() self.lhlo() else: self.rset() if not self.dlmtp: raise DspamClientError('DLMTP mode not available') self.mailfrom(client_args='--process --deliver=summary') self.rcptto((user,)) self.data(message) # check for valid result f...
def get_resource_method(name, template): """ Creates a function that is suitable as a method for ResourceCollection. """ def rsr_meth(self, **kwargs): http_method = template['http_method'] extra_path = template.get('extra_path') if extra_path: fills = {'res_id': kwargs.pop('res_id', '')} path = self.path + (extra_path ...
path, response, self.client) for r in obj], response=response ) else: ret = Resource(obj, path, response, self.client) return ret rsr_meth.__name__ = name return rsr_meth
def Getter(accessor, normalizer=lambda x: x): """ Returns a function that will access an attribute off of an object. If that attribute is callable, it will call it. Accepts a normalizer to call on the value at the end. """ if not callable(accessor): short_description = get_pretty_name(accessor) accessor = attrgetter(ac...
def DisplayGetter(accessor, *args, **kwargs): """ Returns a Getter that gets the display name for a model field with choices. """ short_description = get_pretty_name(accessor) accessor = 'get_%s_display' % accessor getter = Getter(accessor, *args, **kwargs) getter.short_description = short_description return getter
def initial_step(self, phase, x, y): """ Transform input to the CORDIC working quadrants """ self.x[0] = x self.y[0] = y self.phase[0] = phase if self.MODE == CordicMode.ROTATION: if phase > 0.5: # > np.pi/2 self.x[0] = -x self.phase[0] = phase - 1.0 elif phase < -0.5: # < -np.pi/2 self.x[0] = -x self.phase[0] = phase ...
def main(self, x, y, phase): """ Runs one step of pipelined CORDIC Returned phase is in 1 to -1 range """ self.initial_step(phase, x, y) # pipelined CORDIC for i in range(self.ITERATIONS - 1): if self.MODE == CordicMode.ROTATION: direction = self.phase[i] > 0 elif self.MODE == CordicMode.VECTORING: direction = self.y[i...
def blockSignals(self, boolean): """add block/unblock of keyboard shortcut""" pgParameter.blockSignals(self, boolean) try: item = self.items[0] if item.key: item.key.blockSignals(boolean) except: pass
def replaceWith(self, param): """replace this parameter with another""" i = self.parent().children().index(self) # TODO: transfer the children: p = self.parent() self.parent().removeChild(self) p.insertChild(i, param) self = param
def deploy(self): """ Open a ZIP archive, validate requirements then deploy the webfont into project static files """ self._info("* Opening archive: {}", self.archive_path) if not os.path.exists(self.archive_path): self._error("Given path does not exists: {}", self.archive_path) with zipfile.ZipFile(self.archive_path, ...
not contain any supported format: {}", ', '.join(allowed_extensions)) else: self._debug("* Finded font files in archive: {}", ', '.join(font_files)) # Extract files from archive tmp_container, css_content = self.extract(zip_archive, font_files) # Install files self.install(tmp_container, font_dir, css_content)
def extract(self, zip_archive, font_files): """ Extract files to install """ # Get a temp directory tmp_container = tempfile.mkdtemp(prefix='icomoon-tmp') self._debug("* Temporary dir for extracted archive: {}", tmp_container) # Extract manifest to temp directory zip_archive.extract(settings.ICOMOON_MANIFEST_FILENAME, ...
def install(self, tmp_container, font_tmpdir, css_content): """ Install extracted files and builded css """ # Write builded css file to its destination with open(self.webfont_settings['csspart_path'], 'w') as css_file: css_file.write(css_content) # Clean previous font dir if os.path.exists(self.webfont_settings['fontdi...
def create_parser(): """Creates and returns the command line parser, an :class:`argparser.ArgumentParser` instance.""" parser = ArgumentParser( formatter_class=RawDescriptionHelpFormatter, description=DESCRIPTION, epilog=EPILOG, add_help=False) directory = parser.add_argument_group("Directory") directory.add_argument( ...
to directory.") info = parser.add_argument_group("Information") info.add_argument( '-h', '--help', action='store_true', default=False, help="Prints this help and exits") info.add_argument( '--usage', action='store_true', default=False, help="Prints additional help on globs and exits") info.add_argument( '--version', ac...
def main(*kw): """Command line entry point; arguments must match those defined in in :meth:`create_parser()`; returns 0 for success, else 1. Example:: command.main("-i", "**/*.py", "--no-default-excludes") Runs formic printing out all .py files in the current working directory and its children to ``sys.stdout``. If *kw...
system. *.py Selects every matching file anywhere in the whole tree Matches /foo.py and /bar/foo.py but not /foo.pyc or /bar/foo.pyc/ /*.py Selects every matching file in the root of the directory (but no deeper). Matches /foo.py but not /bar/foo.py /myapp/** Matches all files under /myapp and below. /myapp/**/__init__...
such as hidden VCS files and directories. The full list is at: * https://formic.readthedocs.io/en/latest/api.html#formic.formic.get_initial_default_excludes Default excludes can be simply switched off on both the command line and the API, for example:: $ formic -i "*.py" -e "__init__.py" "**/*test*/" "test_*" --no-defa...
def get_current_version(project_name=None, project_dir=os.curdir, repo_dir=None): """ Retrieves the version of the package, checking in this order of priority: * From an environment variable named ${project_name}_VERSION (all in caps) if project_name was specified. * From the PKG-INFO file if inside a packaged distro. ...
line.split(' ', 1)[-1] if version is None: try: version = api.get_current_version(repo_path=repo_dir) except: pass if version is None: if project_name: try: distribution = pkg_resources.get_distribution(project_name) if distribution.has_version(): version = distribution.version except: pass if version is None: raise Ru...
def get_authors(project_dir=os.curdir): """ Retrieves the authors list, from the AUTHORS file (if in a package) or generates it from the git history. Returns: list(str): List of authors Raises: RuntimeError: If the authors could not be retrieved """ authors = set() pkg_info_file = os.path.join(project_dir, 'PKG-INFO') ...
def get_changelog(project_dir=os.curdir, bugtracker_url='', rpm_format=False): """ Retrieves the changelog, from the CHANGELOG file (if in a package) or generates it from the git history. Optionally in rpm-compatible format. :param project_dir: Path to the git repo of the project. :type project_dir: str :param bugtrack...
def get_releasenotes(project_dir=os.curdir, bugtracker_url=''): """ Retrieves the release notes, from the RELEASE_NOTES file (if in a package) or generates it from the git history. Args: project_dir(str): Path to the git repo of the project. bugtracker_url(str): Url to the bug tracker for the issues. Returns: str: rele...
def create_authors(project_dir=os.curdir): """ Creates the authors file, if not in a package. Returns: None Raises: RuntimeError: If the authors could not be retrieved """ pkg_info_file = os.path.join(project_dir, 'PKG-INFO') authors_file = os.path.join(project_dir, 'AUTHORS') if os.path.exists(pkg_info_file): return a...
def create_changelog(project_dir=os.curdir, bugtracker_url='', rpm_format=False): """ Creates the changelog file, if not in a package. :param project_dir: Path to the git repo of the project. :type project_dir: str :param bugtracker_url: Url to the bug tracker for the issues. :type bugtracker_url: str :param rpm_format...
def create_releasenotes(project_dir=os.curdir, bugtracker_url=''): """ Creates the release notes file, if not in a package. Args: project_dir(str): Path to the git repo of the project. bugtracker_url(str): Url to the bug tracker for the issues. Returns: None Raises: RuntimeError: If the release notes could not be retri...
def p_rddl_block(self, p): '''rddl_block : rddl_block domain_block | rddl_block instance_block | rddl_block nonfluent_block | empty''' if p[1] is None: p[0] = dict() else: name, block = p[2] p[1][name] = block p[0] = p[1]
def p_domain_block(self, p): '''domain_block : DOMAIN IDENT LCURLY req_section domain_list RCURLY''' d = Domain(p[2], p[4], p[5]) p[0] = ('domain', d)
def p_req_section(self, p): '''req_section : REQUIREMENTS ASSIGN_EQUAL LCURLY string_list RCURLY SEMI | REQUIREMENTS LCURLY string_list RCURLY SEMI | empty''' if len(p) == 7: p[0] = p[4] elif len(p) == 6: p[0] = p[3] self._print_verbose('requirements')
def p_domain_list(self, p): '''domain_list : domain_list type_section | domain_list pvar_section | domain_list cpf_section | domain_list reward_section | domain_list action_precond_section | domain_list state_action_constraint_section | domain_list state_invariant_section | empty''' if p[1] is None: p[0] = dict() else:...
def p_type_list(self, p): '''type_list : type_list type_def | empty''' if p[1] is None: p[0] = [] else: p[1].append(p[2]) p[0] = p[1]
def p_type_def(self, p): '''type_def : IDENT COLON OBJECT SEMI | IDENT COLON LCURLY enum_list RCURLY SEMI''' if len(p) == 5: p[0] = (p[1], p[3]) elif len(p) == 7: p[0] = (p[1], p[4])
def p_enum_list(self, p): '''enum_list : enum_list COMMA ENUM_VAL | ENUM_VAL | empty''' if p[1] is None: p[0] = [] elif len(p) == 4: p[1].append(p[3]) p[0] = p[1] elif len(p) == 2: p[0] = [p[1]]
def p_pvar_list(self, p): '''pvar_list : pvar_list pvar_def | empty''' if p[1] is None: p[0] = [] else: p[1].append(p[2]) p[0] = p[1]
def p_nonfluent_def(self, p): '''nonfluent_def : IDENT LPAREN param_list RPAREN COLON LCURLY NON_FLUENT COMMA type_spec COMMA DEFAULT ASSIGN_EQUAL range_const RCURLY SEMI | IDENT COLON LCURLY NON_FLUENT COMMA type_spec COMMA DEFAULT ASSIGN_EQUAL range_const RCURLY SEMI''' if len(p) == 16: p[0] = PVariable(name=p[1], fl...
def p_intermfluent_def(self, p): '''intermfluent_def : IDENT LPAREN param_list RPAREN COLON LCURLY INTERMEDIATE COMMA type_spec COMMA LEVEL ASSIGN_EQUAL range_const RCURLY SEMI | IDENT COLON LCURLY INTERMEDIATE COMMA type_spec COMMA LEVEL ASSIGN_EQUAL range_const RCURLY SEMI''' if len(p) == 16: p[0] = PVariable(name=p[...
def p_cpf_list(self, p): '''cpf_list : cpf_list cpf_def | empty''' if p[1] is None: p[0] = [] else: p[1].append(p[2]) p[0] = p[1]
def p_action_precond_section(self, p): '''action_precond_section : ACTION_PRECONDITIONS LCURLY action_precond_list RCURLY SEMI | ACTION_PRECONDITIONS LCURLY RCURLY SEMI''' if len(p) == 6: p[0] = ('preconds', p[3]) elif len(p) == 5: p[0] = ('preconds', []) self._print_verbose('action-preconditions')
def p_action_precond_list(self, p): '''action_precond_list : action_precond_list action_precond_def | action_precond_def''' if len(p) == 3: p[1].append(p[2]) p[0] = p[1] elif len(p) == 2: p[0] = [p[1]]
def p_state_action_constraint_section(self, p): '''state_action_constraint_section : STATE_ACTION_CONSTRAINTS LCURLY state_cons_list RCURLY SEMI | STATE_ACTION_CONSTRAINTS LCURLY RCURLY SEMI''' if len(p) == 6: p[0] = ('constraints', p[3]) elif len(p) == 5: p[0] = ('constraints', []) self._print_verbose('state-action-co...
def p_state_cons_list(self, p): '''state_cons_list : state_cons_list state_cons_def | state_cons_def''' if len(p) == 3: p[1].append(p[2]) p[0] = p[1] elif len(p) == 2: p[0] = [p[1]]
def p_state_invariant_section(self, p): '''state_invariant_section : STATE_INVARIANTS LCURLY state_invariant_list RCURLY SEMI | STATE_INVARIANTS LCURLY RCURLY SEMI''' if len(p) == 6: p[0] = ('invariants', p[3]) elif len(p) == 5: p[0] = ('invariants', []) self._print_verbose('invariants')
def p_state_invariant_list(self, p): '''state_invariant_list : state_invariant_list state_invariant_def | state_invariant_def''' if len(p) == 3: p[1].append(p[2]) p[0] = p[1] elif len(p) == 2: p[0] = [p[1]]
def p_term_list(self, p): '''term_list : term_list COMMA term | term | empty''' if p[1] is None: p[0] = [] elif len(p) == 4: p[1].append(p[3]) p[0] = p[1] elif len(p) == 2: p[0] = [p[1]]
def p_pvar_expr(self, p): '''pvar_expr : IDENT LPAREN term_list RPAREN | IDENT''' if len(p) == 2: p[0] = ('pvar_expr', (p[1], None)) elif len(p) == 5: p[0] = ('pvar_expr', (p[1], p[3]))
def p_boolean_expr(self, p): '''boolean_expr : expr AND expr | expr AMPERSAND expr | expr OR expr | expr IMPLY expr | expr EQUIV expr | NOT expr %prec UMINUS | bool_type''' if len(p) == 4: p[0] = (p[2], (p[1], p[3])) elif len(p) == 3: p[0] = (p[1], (p[2],)) elif len(p) == 2: p[0] = ('boolean', p[1])
def p_numerical_expr(self, p): '''numerical_expr : expr PLUS expr | expr MINUS expr | expr TIMES expr | expr DIV expr | MINUS expr %prec UMINUS | PLUS expr %prec UMINUS | INTEGER | DOUBLE''' if len(p) == 4: p[0] = (p[2], (p[1], p[3])) elif len(p) == 3: p[0] = (p[1], (p[2],)) elif len(p) == 2: p[0] = ('number', p[1])
def p_control_expr(self, p): '''control_expr : IF LPAREN expr RPAREN THEN expr ELSE expr %prec IF | SWITCH LPAREN term RPAREN LCURLY case_list RCURLY''' if len(p) == 9: p[0] = (p[1], (p[3], p[6], p[8])) elif len(p) == 8: p[0] = (p[1], (p[3], *p[6]))
def p_randomvar_expr(self, p): '''randomvar_expr : BERNOULLI LPAREN expr RPAREN | DIRAC_DELTA LPAREN expr RPAREN | KRON_DELTA LPAREN expr RPAREN | UNIFORM LPAREN expr COMMA expr RPAREN | NORMAL LPAREN expr COMMA expr RPAREN | EXPONENTIAL LPAREN expr RPAREN | DISCRETE LPAREN IDENT COMMA lconst_case_list RPAREN | DIRICHL...
def p_typed_var_list(self, p): '''typed_var_list : typed_var_list COMMA typed_var | typed_var''' if len(p) == 4: p[1].append(p[3]) p[0] = p[1] elif len(p) == 2: p[0] = [p[1]]
def p_expr_list(self, p): '''expr_list : expr_list COMMA expr | expr''' if len(p) == 4: p[1].append(p[3]) p[0] = p[1] elif len(p) == 2: p[0] = [p[1]]
def p_case_list(self, p): '''case_list : case_list COMMA case_def | case_def''' if len(p) == 4: p[1].append(p[3]) p[0] = p[1] elif len(p) == 2: p[0] = [p[1]]
def p_case_def(self, p): '''case_def : CASE term COLON expr | DEFAULT COLON expr''' if len(p) == 5: p[0] = ('case', (p[2], p[4])) elif len(p) == 4: p[0] = ('default', p[3])
def p_lconst_case_list(self, p): '''lconst_case_list : lconst COLON expr | lconst COLON OTHERWISE | lconst_case_list COMMA lconst COLON expr''' if len(p) == 4: p[0] = [('lconst', (p[1], p[3]))] elif len(p) == 6: p[1].append(('lconst', (p[3], p[5]))) p[0] = p[1]
def p_instance_list(self, p): '''instance_list : instance_list domain_section | instance_list nonfluents_section | instance_list objects_section | instance_list init_state_section | instance_list max_nondef_actions_section | instance_list horizon_spec_section | instance_list discount_section | empty''' if p[1] is None:...
def p_horizon_spec_section(self, p): '''horizon_spec_section : HORIZON ASSIGN_EQUAL pos_int_type_or_pos_inf SEMI | HORIZON ASSIGN_EQUAL TERMINATE_WHEN LPAREN expr RPAREN''' if len(p) == 5: p[0] = ('horizon', p[3]) elif len(p) == 7: p[0] = ('horizon', p[5]) self._print_verbose('horizon')
def p_nonfluent_list(self, p): '''nonfluent_list : nonfluent_list domain_section | nonfluent_list objects_section | nonfluent_list init_non_fluent_section | empty''' if p[1] is None: p[0] = dict() else: name, section = p[2] p[1][name] = section p[0] = p[1]
def p_objects_list(self, p): '''objects_list : objects_list objects_def | objects_def | empty''' if len(p) == 3: p[1].append(p[2]) p[0] = p[1] elif len(p) == 2: p[0] = [p[1]]
def p_object_const_list(self, p): '''object_const_list : object_const_list COMMA IDENT | IDENT''' if len(p) == 4: p[1].append(p[3]) p[0] = p[1] elif len(p) == 2: p[0] = [p[1]]
def p_pvar_inst_list(self, p): '''pvar_inst_list : pvar_inst_list pvar_inst_def | pvar_inst_def''' if len(p) == 3: p[1].append(p[2]) p[0] = p[1] elif len(p) == 2: p[0] = [p[1]]
def p_pvar_inst_def(self, p): '''pvar_inst_def : IDENT LPAREN lconst_list RPAREN SEMI | IDENT SEMI | NOT IDENT LPAREN lconst_list RPAREN SEMI | NOT IDENT SEMI | IDENT LPAREN lconst_list RPAREN ASSIGN_EQUAL range_const SEMI | IDENT ASSIGN_EQUAL range_const SEMI''' if len(p) == 6: p[0] = ((p[1], p[3]), True) elif len(p) ...
def p_lconst_list(self, p): '''lconst_list : lconst_list COMMA lconst | lconst''' if len(p) == 4: p[1].append(p[3]) p[0] = p[1] elif len(p) == 2: p[0] = [p[1]]
def p_string_list(self, p): '''string_list : string_list COMMA IDENT | IDENT | empty''' if p[1] is None: p[0] = [] elif len(p) == 4: p[1].append(p[3]) p[0] = p[1] elif len(p) == 2: p[0] = [p[1]]
def selectable_delete(self) -> Expectation: ''' Remove two projects by selecting them via `<space>` and pressing `d` ''' self.cmd_sync('ProAdd! tpe2/dep') self._count(2) self.cmd_sync('Projects') self.cmd_sync('call feedkeys("\\<space>\\<space>d")') return self._count(0)
def delete(self, **kwds): """ Endpoint: /tag/<id>/delete.json Deletes this tag. Returns True if successful. Raises a TroveboxError if not. """ result = self._client.tag.delete(self, **kwds) self._delete_fields() return result