code stringlengths 1 18.2k |
|---|
headers['status'] != 'ok': raise SystemExit('Failed to pull file') else: make_dirs_if_dont_exist(data_store.get_full_file_path(cpjoin(*fle['path'].split('/')[:-1]) + '/')) data_store.fs_put(fle['path'], req_result) # Files which have been deleted on server and need deleting on client if changes['to_delete_on_client'] !... |
print out.append({'1_path' : fle['file_info']['path'], '2_client_status' : fle['client_status'], '3_server_status' : fle['server_status'], '4_resolution' : ['client', 'server']}) if fle['server_status'] == 'Changed': server_versions.append(fle['file_info']) #=============== if server_versions != []: choice = None if no... |
or 'server' to choose which version to retain.") # Update the latest revision in the manifest only if there are no conflicts else: data_store.begin() manifest = data_store.read_local_manifest() manifest['have_revision'] = result['head'] data_store.write_local_manifest(manifest) data_store.commit() #delete the conflicts... |
def register_action(action): """ Adds an action to the parser cli. :param action(BaseAction): a subclass of the BaseAction class """ sub = _subparsers.add_parser(action.meta('cmd'), help=action.meta('help')) sub.set_defaults(cmd=action.meta('cmd')) for (name, arg) in action.props().items(): sub.add_argument(arg.name, a... |
def run(*args, **kwargs): """ Runs the parser and it executes the action handler with the provided arguments from the CLI. Also catches the BaseError interrupting the execution and showing the error message to the user. Default arguments comes from the cli args (sys.argv array) but we can force those arguments when wri... |
def cli(ctx): """ This is a command line app to get useful stats from a trello board and report on them in useful ways. Requires the following environment varilables: TRELLOSTATS_APP_KEY=<your key here> TRELLOSTATS_APP_TOKEN=<your token here> """ ctx.obj = dict() ctx.obj['app_key'] = os.environ.get('TRELLOSTATS_APP_KEY... |
def snapshot(ctx, board, done): """ Recording mode - Daily snapshots of a board for ongoing reporting: -> trellis report --board=87hiudhw --spend --revenue --done=Done """ ctx.obj['board_id'] = board ts = TrelloStats(ctx.obj) Snapshot.create_table(fail_silently=True) done_id = ts.get_list_id_from_name(done) ct = cycle_... |
def report(ctx, board, done, output): ctx.obj['board_id'] = board ts = TrelloStats(ctx.obj) """ Reporting mode - Daily snapshots of a board for ongoing reporting: -> trellis report --board=87hiudhw --spend --revenue --done=Done """ ct = cycle_time(ts, board, done) env = get_env() # Get all render functions from the mod... |
def translation(language): """ Return a translation object in the default 'django' domain. """ global _translations if language not in _translations: _translations[language] = Translations(language) return _translations[language] |
def gettext(message): """ Translate the 'message' string. It uses the current thread to find the translation object to use. If no current translation is activated, the message will be run through the default translation object. """ global _default _default = _default or translation(DEFAULT_LANGUAGE) translation_object ... |
def _new_gnu_trans(self, localedir, use_null_fallback=True): """ Return a mergeable gettext.GNUTranslations instance. A convenience wrapper. By default gettext uses 'fallback=False'. Using param `use_null_fallback` to avoid confusion with any other references to 'fallback'. """ use_null_fallback = False return gettext_... |
def add_localedir_translations(self, localedir): """Merge translations from localedir.""" global _localedirs if localedir in self.localedirs: return self.localedirs.append(localedir) full_localedir = os.path.join(localedir, 'locale') if os.path.exists(full_localedir): translation = self._new_gnu_trans(full_localedir) s... |
def merge(self, other): """Merge another translation into this catalog.""" if not getattr(other, '_catalog', None): return # NullTranslations() has no _catalog if self._catalog is None: # Take plural and _info from first catalog found self.plural = other.plural self._info = other._info.copy() self._catalog = other._cat... |
def decode_input(text_in): """ Decodes `text_in` If text_in is is a string, then decode it as utf-8 string. If text_in is is a list of strings, then decode each string of it, then combine them into one outpust string. """ if type(text_in) == list: text_out = u' '.join([t.decode('utf-8') for t in text_in]) else: text_ou... |
def _set_local_file_path(self): """ Take from environment variable, create dirs and create file if doesn' exist. """ self.FILE_LOCAL = self._transfer.get_env('FILE_LOCAL') if not self.FILE_LOCAL: filename = '{}_{}.{}'.format(str(self._transfer.prefix), str(self._transfer.namespace), str(self.file_extension)) self.FILE_... |
def gen_post_status(): """ Show only published posts outside debug. """ if not app.config["DEBUG"]: post_status = and_(Post.status == PostStatus.PUBLISH) else: post_status = or_(Post.status == PostStatus.PUBLISH, Post.status == PostStatus.DRAFT) return post_status |
def _simple_dispatch(self, name, params): """ Dispatch method """ try: # Internal method func = self.funcs[name] except KeyError: # Other method pass else: # Internal method found if isinstance(params, (list, tuple)): return func(*params) else: return func(**params) # Call the other method outside the except block, to ... |
def subscribe(self, observer): """Subscribe an observer to this subject and return a subscription id """ sid = self._sn self.observers[sid] = observer self._sn += 1 return SubscribeID(self, sid) |
def unsubscribe(self, sid): """Disconnect an observer from this subject """ if sid not in self.observers: raise KeyError( 'Cannot disconnect a observer does not connected to subject' ) del self.observers[sid] |
def make_module_class(name): """Takes the module referenced by name and make it a full class. """ source = sys.modules[name] members = vars(source) is_descriptor = lambda x: not isinstance(x, type) and hasattr(x, '__get__') descriptors = {k: v for (k, v) in members.items() if is_descriptor(v)} members = {k: v for (k, v... |
def build_ann(N_input=None, N_hidden=2, N_output=1, hidden_layer_type='Linear', verbosity=1): """Build a neural net with the indicated input, hidden, and outout dimensions Arguments: params (dict or PyBrainParams namedtuple): default: {'N_hidden': 6} (this is the only parameter that affects the NN build) Returns: FeedF... |
nn['output'])) nn.addConnection(pb.structure.FullConnection(nn['input'], nn['hidden'] if N_hidden else nn['output'])) for i, (Nhid, hidlaytype) in enumerate(zip(N_hidden[:-1], hidden_layer_type[:-1])): Nhid = int(Nhid) nn.addConnection(pb.structure.FullConnection(nn[('hidden-{}'.format(i) if i else 'hidden')], nn['hidd... |
def prepend_dataset_with_weather(samples, location='Fresno, CA', weather_columns=None, use_cache=True, verbosity=0): """ Prepend weather the values specified (e.g. Max TempF) to the samples[0..N]['input'] vectors samples[0..N]['target'] should have an index with the date timestamp If you use_cache for the curent year, ... |
in enumerate(samples): timestamp = timestamps[sampnum] try: weather_day = weather_df.loc[timestamp.date()] except: from traceback import print_exc print_exc() weather_day = {} if verbosity >= 0: warnings.warn('Unable to find weather for the date {}'.format(timestamp.date())) NaN = float('NaN') sample['input'] = [weathe... |
def dataset_from_dataframe(df, delays=(1, 2, 3), inputs=(1, 2, -1), outputs=(-1,), normalize=False, verbosity=1): """Compose a pybrain.dataset from a pandas DataFrame Arguments: delays (list of int): sample delays to use for the input tapped delay line Positive and negative values are treated the same as sample counts ... |
Detect categorical variables with low dimensionality and split into separate bits Vowpel Wabbit hashes strings into an int? Detect ordinal variables and convert to continuous int sequence SEE: http://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm """ if isinstance(delays, int): if delays: delays = range(1, de... |
df[inp_outs].std() if normalize and verbosity > 0: print("Input mean values (used to normalize input biases): {}".format(means[:N_inp])) print("Output mean values (used to normalize output biases): {}".format(means[N_inp:])) ds = pb.datasets.SupervisedDataSet(N_inp * len(delays), N_out) if verbosity > 0: print("Dataset... |
enumerate(df[outputs].values): if verbosity > 0 and i % 100 == 0: print("{}%".format(i / .01 / len(df))) elif verbosity > 1: print('sample[{i}].target={out_vec}'.format(i=i, out_vec=out_vec)) if i < max(delays): continue inp_vec = [] for delay in delays: inp_vec += list((df[inputs].values[i - delay] - means[:N_inp]) / ... |
def input_dataset_from_dataframe(df, delays=(1, 2, 3), inputs=(1, 2, -1), outputs=None, normalize=True, verbosity=1): """ Build a dataset with an empty output/target vector Identical to `dataset_from_dataframe`, except that default values for 2 arguments: outputs: None """ return dataset_from_dataframe(df=df, delays=de... |
def inputs_from_dataframe(df, delays=(1, 2, 3), inputs=(1, 2, -1), outputs=None, normalize=True, verbosity=1): """ Build a sequence of vectors suitable for "activation" by a neural net Identical to `dataset_from_dataframe`, except that only the input vectors are returned (not a full DataSet instance) and default values... |
def build_trainer(nn, ds, verbosity=1): """Configure neural net trainer from a pybrain dataset""" return pb.supervised.trainers.rprop.RPropMinusTrainer(nn, dataset=ds, batchlearning=True, verbose=bool(verbosity)) |
def weight_matrices(nn): """ Extract list of weight matrices from a Network, Layer (module), Trainer, Connection or other pybrain object""" if isinstance(nn, ndarray): return nn try: return weight_matrices(nn.connections) except: pass try: return weight_matrices(nn.module) except: pass # Network objects are ParameterCo... |
def dataset_nan_locs(ds): """ from http://stackoverflow.com/a/14033137/623735 # gets the indices of the rows with nan values in a dataframe pd.isnull(df).any(1).nonzero()[0] """ ans = [] for sampnum, sample in enumerate(ds): if pd.isnull(sample).any(): ans += [{ 'sample': sampnum, 'input': pd.isnull(sample[0]).nonzero(... |
def table_nan_locs(table): """ from http://stackoverflow.com/a/14033137/623735 # gets the indices of the rows with nan values in a dataframe pd.isnull(df).any(1).nonzero()[0] """ ans = [] for rownum, row in enumerate(table): try: if pd.isnull(row).any(): colnums = pd.isnull(row).nonzero()[0] ans += [(rownum, colnum) fo... |
def plot_network_results(network, ds=None, mean=0, std=1, title='', show=True, save=True): """Identical to plot_trainer except `network` and `ds` must be provided separately""" df = sim_network(network=network, ds=ds, mean=mean, std=std) df.plot() plt.xlabel('Date') plt.ylabel('Threshold (kW)') plt.title(title) if show... |
def trainer_results(trainer, mean=0, std=1, title='', show=True, save=True): """Plot the performance of the Network and SupervisedDataSet in a pybrain Trainer DataSet target and output values are denormalized before plotting with: output * std + mean Which inverses the normalization (output - mean) / std Args: trainer ... |
plot_network_results(network=trainer.module, ds=trainer.ds, mean=mean, std=std, title=title, show=show, save=save) |
def sim_trainer(trainer, mean=0, std=1): """Simulate a trainer by activating its DataSet and returning DataFrame(columns=['Output','Target']) """ return sim_network(network=trainer.module, ds=trainer.ds, mean=mean, std=std) |
def sim_network(network, ds=None, index=None, mean=0, std=1): """Simulate/activate a Network on a SupervisedDataSet and return DataFrame(columns=['Output','Target']) The DataSet's target and output values are denormalized before populating the dataframe columns: denormalized_output = normalized_output * std + mean Whic... |
# just in case network is a trainer or has a Module-derived instance as one of it's attribute # isinstance(network.module, (networks.Network, modules.Module)) if hasattr(network, 'module') and hasattr(network.module, 'activate'): # may want to also check: isinstance(network.module, (networks.Network, modules.Module)) n... |
def lex(args): """ Lex input and return a list of actions to perform. """ if len(args) == 0 or args[0] == SHOW: return [(SHOW, None)] elif args[0] == LOG: return [(LOG, None)] elif args[0] == ECHO: return [(ECHO, None)] elif args[0] == SET and args[1] == RATE: return tokenizeSetRate(args[2:]) elif args[0] == SET and ar... |
def run_svc_action(self, name, replace=None, svc=None): """ backwards compatible to reflex service object. This looks for hooks on current object as well as in the actions sub-object. """ actions = svc.get('actions') if actions and actions.get(name): return self.run(name, actions=actions, replace=replace) if svc.get(na... |
def run(self, name, replace=None, actions=None): """ Do an action. If `replace` is provided as a dictionary, do a search/replace using %{} templates on content of action (unique to action type) """ self.actions = actions # incase we use group action = actions.get(name) if not action: self.die("Action not found: {}", na... |
def _run__group(self, action, replace): """ Run a group of actions in sequence. >>> Action().run("several", actions={ ... "several": { ... "type": "group", ... "actions": ["hello","call","then"] ... }, "hello": { ... "type": "exec", ... "cmd": "echo version=%{version}" ... }, "call": { ... "type": "hook", ... "url": "h... |
def _run__hook(self, action, replace): """Simple webhook""" url = action.get("url") expected = action.get("expect", {}).get("response-codes", (200, 201, 202, 204)) if replace and action.get("template", True): url = self.rfxcfg.macro_expand(url, replace) self.logf("Action {} hook\n", action['name']) self.logf("{}\n", ur... |
def _run__exec(self, action, replace): """ Run a system command >>> Action().run("hello", actions={ ... "hello": { ... "type": "exec", ... "cmd": "echo version=%{version}" ... }}, replace={ ... "version": "1712.10" ... }) version=1712.10 """ cmd = action.get('cmd') shell = False if isinstance(cmd, str): shell = True if... |
def _run__http(self, action, replace): """More complex HTTP query.""" query = action['query'] # self._debug = True url = '{type}://{host}{path}'.format(path=query['path'], **action) content = None method = query.get('method', "get").lower() self.debug("{} {} url={}\n", action['type'], method, url) if method == "post": ... |
status={} content={}\n", action['type'], result.status_code, result.text) if result.status_code not in expected_codes: self.die("Unable to make {} call, unexpected result ({})", action['type'], result.status_code) if 'content' in expect: self.debug("{} expect content={}\n", action['type'], expect['content']) if expect[... |
async def main(): """ Main code """ # Create Client from endpoint string in Duniter format client = Client(BMAS_ENDPOINT) try: # Create Web Socket connection on block path ws_connection = client(bma.ws.block) # From the documentation ws_connection should be a ClientWebSocketResponse object... # # https://docs.aiohttp.o... |
text... if msg.type == aiohttp.WSMsgType.TEXT: print("Received a block") # Validate jsonschema and return a the json dict block_data = parse_text(msg.data, bma.ws.WS_BLOCK_SCHEMA) print(block_data) elif msg.type == aiohttp.WSMsgType.CLOSED: # Connection is closed print("Web socket connection closed !") elif msg.type ==... |
def _get_default_args(func): """ returns a dictionary of arg_name:default_values for the input function """ args, varargs, keywords, defaults = inspect.getargspec(func) print(args) return dict(zip(reversed(args), reversed(defaults))) |
def _get_arg_names(func): ''' this returns the arg names since dictionaries dont guarantee order ''' args, varargs, keywords, defaults = inspect.getargspec(func) return(tuple(args)) |
def strict_defaults(fn): ''' use this decorator to enforce type checking on functions based on the function's defaults ''' @wraps(fn) def wrapper(*args, **kwargs): defaults = _get_default_args(fn) # dictionary that holds each default type needed_types={ key:type(defaults[key]) for key in defaults } # ordered tuple of t... |
def update_mailing_lists_in_m2m( sender=None, userprofile=None, pk_set=None, subscribe=None, unsubscribe=None, verbose=None, email_enabled=None, ): """ m2m_model = m2m model class for 'email_notifications' or 'sms_notifications'. """ response = None email_enabled = email_enabled or settings.EMAIL_ENABLED if email_enabl... |
def superdict(arg=()): """Recursive defaultdict which can init with other dict """ def update(obj, arg): return obj.update(arg) or obj return update(defaultdict(superdict), arg) |
def rget(d, key): """Recursively get keys from dict, for example: 'a.b.c' --> d['a']['b']['c'], return None if not exist. """ if not isinstance(d, dict): return None assert isinstance(key, str) or isinstance(key, list) keys = key.split('.') if isinstance(key, str) else key cdrs = cdr(keys) cars = car(keys) return rget(... |
def deepcopy(data): """Use pickle to do deep_copy""" try: return pickle.loads(pickle.dumps(data)) except TypeError: return copy.deepcopy(data) |
def deepcp(data): """Use ujson to do deep_copy""" import ujson try: return ujson.loads(ujson.dumps(data)) except Exception: return copy.deepcopy(data) |
def _memoizeArgsOnly (max_cache_size=1000): """Python 2.4 compatible memoize decorator. It creates a cache that has a maximum size. If the cache exceeds the max, it is thrown out and a new one made. With such behavior, it is wise to set the cache just a little larger that the maximum expected need. Parameters: max_cach... |
def normalize(version_string, max_version_parts=4): """turn a string representing a version into a normalized version list. Version lists are directly comparable using standard operators such as >, <, ==, etc. Parameters: version_string - such as '3.5' or '3.6.3plugin3' max_version_parts - version strings are comprised... |
def _do_denormalize (version_tuple): """separate action function to allow for the memoize decorator. Lists, the most common thing passed in to the 'denormalize' below are not hashable. """ version_parts_list = [] for parts_tuple in itertools.imap(None,*([iter(version_tuple)]*4)): version_part = ''.join(fn(x) for fn, x ... |
def compare (v1, v2): """old style __cmp__ function returning -1, 0, 1""" v1_norm = normalize(v1) v2_norm = normalize(v2) if v1_norm < v2_norm: return -1 if v1_norm > v2_norm: return 1 return 0 |
def current_revision(self): """ :return: The current :class:`revision.data.Revision`. :rtype: :class:`revision.data.Revision` """ if self.current_index is None: return None if len(self.revisions) > self.current_index: return self.revisions[self.current_index] return None |
def load(self, revision_path): """ Load revision file. :param revision_path: :type revision_path: str """ if not os.path.exists(revision_path): raise RuntimeError("revision file does not exist.") with open(revision_path, mode='r') as f: text = f.read() rev_strings = text.split("## ") for rev_string in rev_strings: if l... |
def checkout(self, revision_id): """ :param revision_id: :class:`revision.data.Revision` ID. :type revision_id: str """ index = 0 found = False for revision in self.revisions: if revision.revision_id == revision_id: self.current_index = index found = True index += 1 if not found: raise RuntimeError("") |
def insert(self, revision, index): """ Insert a :class:`revision.data.Revision` at a given index. :param revision: :type revision: :class:`revision.data.Revision` :param index: :type index: int """ if not isinstance(revision, Revision): raise InvalidArgType() for rev in self.revisions: if rev == revision: return self s... |
def from_ast( pyast_node, node=None, node_cls=None, Node=Node, iter_fields=ast.iter_fields, AST=ast.AST): '''Convert the ast tree to a tater tree. ''' node_cls = node_cls or Node node = node or node_cls() name = pyast_node.__class__.__name__ attrs = [] for field, value in iter_fields(pyast_node): if name == 'Dict': for... |
def generic_visit(self, node, iter_fields=ast.iter_fields, AST=ast.AST): """Called if no explicit visitor function exists for a node. """ for field, value in iter_fields(node): if isinstance(value, list): for item in value: if isinstance(item, AST): self.visit(item) elif isinstance(value, AST): self.visit(value) |
def _validateAttrs(self, keys): """prove that all attributes are defined appropriately""" badAttrsMsg = "" for k in keys: if k not in self.attrs: badAttrsMsg += "Attribute key '%s' is not a valid attribute"%(k) if badAttrsMsg: raise ValueError("Encountered invalid attributes. ALLOWED: %s%s%s"\ %(list(self.attrs), os.li... |
def load(self, ladderName): """retrieve the ladder settings from saved disk file""" self.name = ladderName # preset value to load self.filename with open(self.filename, "rb") as f: data = f.read() self.__dict__.update( json.loads(data) ) |
def update(self, attrs): """update attributes initialized with the proper type""" self._validateAttrs(attrs) for k,v in attrs.items(): typecast = type( getattr(self, k) ) if typecast==bool and v=="False": newval = False # "False" evalued as boolean is True because its length > 0 else: newval = typecast(v.lower()) setat... |
def import_localities(path, delimiter=';'): """ Import localities from a CSV file. :param path: Path to the CSV file containing the localities. """ creates = [] updates = [] with open(path, mode="r") as infile: reader = csv.DictReader(infile, delimiter=str(delimiter)) with atomic(): for row in reader: row['point'] = Po... |
def get_netid_subscriptions(netid, subscription_codes): """ Returns a list of uwnetid.subscription objects corresponding to the netid and subscription code or list provided """ url = _netid_subscription_url(netid, subscription_codes) response = get_resource(url) return _json_to_subscriptions(response) |
def select_subscription(subs_code, subscriptions): """ Return the uwnetid.subscription object with the subs_code. """ if subs_code and subscriptions: for subs in subscriptions: if (subs.subscription_code == subs_code): return subs return None |
def modify_subscription_status(netid, subscription_code, status): """ Post a subscription 'modify' action for the given netid and subscription_code """ url = _netid_subscription_url(netid, subscription_code) body = { 'action': 'modify', 'value': str(status) } response = post_resource(url, json.dumps(body)) return _json... |
def update_subscription(netid, action, subscription_code, data_field=None): """ Post a subscription action for the given netid and subscription_code """ url = '{0}/subscription.json'.format(url_version()) action_list = [] if isinstance(subscription_code, list): for code in subscription_code: action_list.append(_set_act... |
def _netid_subscription_url(netid, subscription_codes): """ Return UWNetId resource for provided netid and subscription code or code list """ return "{0}/{1}/subscription/{2}".format( url_base(), netid, (','.join([str(n) for n in subscription_codes]) if isinstance(subscription_codes, (list, tuple)) else subscription_co... |
def _json_to_subscriptions(response_body): """ Returns a list of Subscription objects """ data = json.loads(response_body) subscriptions = [] for subscription_data in data.get("subscriptionList", []): subscriptions.append(Subscription().from_json( data.get('uwNetID'), subscription_data)) return subscriptions |
def _json_to_subscription_post_response(response_body): """ Returns a list of SubscriptionPostResponse objects """ data = json.loads(response_body) response_list = [] for response_data in data.get("responseList", []): response_list.append(SubscriptionPostResponse().from_json( data.get('uwNetID'), response_data)) return... |
def has_permission(self, request, view): """Check list and create permissions based on sign and filters.""" if view.suffix == 'Instance': return True filter_and_actions = self._get_filter_and_actions( request.query_params.get('sign'), view.action, '{}.{}'.format( view.queryset.model._meta.app_label, view.queryset.model... |
def has_object_permission(self, request, view, obj=None): """Check object permissions based on filters.""" filter_and_actions = self._get_filter_and_actions( request.query_params.get('sign'), view.action, '{}.{}'.format(obj._meta.app_label, obj._meta.model_name)) if not filter_and_actions: return False qs = view.querys... |
def add_file_argument(self, *args, **kwargs): """ Add an argument that represents the location of a file :param args: :param kwargs: :return: """ rval = self.add_argument(*args, **kwargs) self.file_args.append(rval) return rval |
def add_argument(self, *args, **kwargs): """ Add an argument incorporating the default value into the help string :param args: :param kwargs: :return: """ defhelp = kwargs.pop("help", None) defaults = kwargs.pop("default", None) default = defaults if self.use_defaults else None if not defhelp or default is None or kwar... |
def decode_file_args(self, argv: List[str]) -> List[str]: """ Preprocess a configuration file. The location of the configuration file is stored in the parser so that the FileOrURI action can add relative locations. :param argv: raw options list :return: options list with '--conf' references replaced with file contents ... |
def p_Interface(p): """Interface : interface IDENTIFIER Inheritance "{" InterfaceMembers "}" ";" """ p[0] = model.Interface(name=p[2], parent=p[3], members=p[5]) |
def p_Dictionary(p): """Dictionary : dictionary IDENTIFIER Inheritance "{" DictionaryMembers "}" ";" """ p[0] = model.Dictionary(name=p[2], parent=p[3], members=p[5]) |
def p_DictionaryMember(p): """DictionaryMember : Type IDENTIFIER Default ";" """ p[0] = model.DictionaryMember(type=p[1], name=p[2], default=p[3]) |
def p_DefaultValue_string(p): """DefaultValue : STRING""" p[0] = model.Value(type=model.Value.STRING, value=p[1]) |
def p_Exception(p): """Exception : exception IDENTIFIER Inheritance "{" ExceptionMembers "}" ";" """ p[0] = model.Exception(name=p[2], parent=p[3], members=p[5]) |
def p_CallbackRest(p): """CallbackRest : IDENTIFIER "=" ReturnType "(" ArgumentList ")" ";" """ p[0] = model.Callback(name=p[1], return_type=p[3], arguments=p[5]) |
def p_Typedef(p): """Typedef : typedef ExtendedAttributeList Type IDENTIFIER ";" """ p[0] = model.Typedef(type_extended_attributes=p[2], type=p[3], name=p[4]) |
def p_Const(p): """Const : const ConstType IDENTIFIER "=" ConstValue ";" """ p[0] = model.Const(type=p[2], name=p[3], value=p[5]) |
def p_ConstValue_boolean(p): """ConstValue : BooleanLiteral""" p[0] = model.Value(type=model.Value.BOOLEAN, value=p[1]) |
def p_ConstValue_integer(p): """ConstValue : INTEGER""" p[0] = model.Value(type=model.Value.INTEGER, value=p[1]) |
def p_ConstValue_float(p): """ConstValue : FLOAT""" p[0] = model.Value(type=model.Value.FLOAT, value=p[1]) |
def p_ConstValue_null(p): """ConstValue : null""" p[0] = model.Value(type=model.Value.NULL, value=p[1]) |
def p_Attribute(p): """Attribute : Inherit ReadOnly attribute Type IDENTIFIER ";" """ p[0] = model.Attribute(inherit=p[1], readonly=p[2], type=p[4], name=p[5]) |
def p_OperationRest(p): """OperationRest : ReturnType OptionalIdentifier "(" ArgumentList ")" ";" """ p[0] = model.Operation(return_type=p[1], name=p[2], arguments=p[4]) |
def p_OptionalOrRequiredArgument_optional(p): """OptionalOrRequiredArgument : optional Type IDENTIFIER Default""" p[0] = model.OperationArgument( type=p[2], name=p[3], optional=True, default=p[4]) |
def p_OptionalOrRequiredArgument(p): """OptionalOrRequiredArgument : Type Ellipsis IDENTIFIER""" p[0] = model.OperationArgument(type=p[1], ellipsis=p[2], name=p[3]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.