text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_path(): """ Add any new modules that are directories to the PATH """
sitedirs = getsyssitepackages() for sitedir in sitedirs: env_path = os.environ['PATH'].split(os.pathsep) for module in allowed_modules: p = join(sitedir, module) if isdir(p) and not p in env_path: os.environ['PATH'] += env_t(os.pathsep + p)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install_importer(): """ If in a virtualenv then load spec files to decide which modules can be imported from system site-packages and install path hook. """
logging.debug('install_importer') if not in_venv(): logging.debug('No virtualenv active py:[%s]', sys.executable) return False if disable_vext: logging.debug('Vext disabled by environment variable') return False if GatekeeperFinder.PATH_TRIGGER not in sys.path: try: load_specs() sys.path.append(GatekeeperFinder.PATH_TRIGGER) sys.path_hooks.append(GatekeeperFinder) except Exception as e: """ Dont kill other programmes because of a vext error """ logger.info(str(e)) if logger.getEffectiveLevel() == logging.DEBUG: raise logging.debug("importer installed") return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_module(self, name): """ Only lets modules in allowed_modules be loaded, others will get an ImportError """
# Get the name relative to SITEDIR .. filepath = self.module_info[1] fullname = splitext( \ relpath(filepath, self.sitedir) \ )[0].replace(os.sep, '.') modulename = filename_to_module(fullname) if modulename not in allowed_modules: if remember_blocks: blocked_imports.add(fullname) if log_blocks: raise ImportError("Vext blocked import of '%s'" % modulename) else: # Standard error message raise ImportError("No module named %s" % modulename) if name not in sys.modules: try: logger.debug("load_module %s %s", name, self.module_info) module = imp.load_module(name, *self.module_info) except Exception as e: logger.debug(e) raise sys.modules[fullname] = module return sys.modules[fullname]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate(g: Graph, schema: Union[str, ShExJ.Schema], focus: Optional[Union[str, URIRef, IRIREF]], start: Optional[Union[str, URIRef, IRIREF, START, START_TYPE]]=None, debug_trace: bool = False) -> Tuple[bool, Optional[str]]: """ Evaluate focus node `focus` in graph `g` against shape `shape` in ShEx schema `schema` :param g: Graph containing RDF :param schema: ShEx Schema -- if str, it will be parsed :param focus: focus node in g. If not specified, all URI subjects in G will be evaluated. :param start: Starting shape. If omitted, the Schema start shape is used :param debug_trace: Turn on debug tracing :return: None if success or failure reason if failure """
if isinstance(schema, str): schema = SchemaLoader().loads(schema) if schema is None: return False, "Error parsing schema" if not isinstance(focus, URIRef): focus = URIRef(str(focus)) if start is None: start = str(schema.start) if schema.start else None if start is None: return False, "No starting shape" if not isinstance(start, IRIREF) and start is not START and start is not START_TYPE: start = IRIREF(str(start)) cntxt = Context(g, schema) cntxt.debug_context.debug = debug_trace map_ = FixedShapeMap() map_.add(ShapeAssociation(focus, start)) test_result, reasons = isValid(cntxt, map_) return test_result, '\n'.join(reasons)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_sysdeps(vext_files): """ Check that imports in 'test_imports' succeed otherwise display message in 'install_hints' """
@run_in_syspy def run(*modules): result = {} for m in modules: if m: try: __import__(m) result[m] = True except ImportError: result[m] = False return result success = True for vext_file in vext_files: with open(vext_file) as f: vext = open_spec(f) install_hint = " ".join(vext.get('install_hints', ['System dependencies not found'])) modules = vext.get('test_import', '') logger.debug("%s test imports of: %s", vext_file, modules) result = run(*modules) if logging.getLogger().getEffectiveLevel() == logging.DEBUG: for k, v in result.items(): logger.debug("%s: %s", k, v) if not all(result.values()): success = False print(install_hint) return success
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_collection(g: Graph, subj: Union[URIRef, BNode], max_entries: int = None, nentries: int = 0) -> Optional[List[str]]: """ Return the turtle representation of subj as a collection :param g: Graph containing subj :param subj: subject of list :param max_entries: maximum number of list elements to return, None means all :param nentries: used for recursion :return: List of formatted entries if subj heads a well formed collection else None """
if subj == RDF.nil: return [')'] if max_entries is not None and nentries >= max_entries: return [' ...', ')'] cadr = cdr = None for p, o in g.predicate_objects(subj): if p == RDF.first and cadr is None: cadr = o elif p == RDF.rest and cdr is None: cdr = o else: return None # technically this can't happen but it doesn't hurt to address it if cadr == RDF.nil and cdr is None: return [] elif cadr is not None and cdr is not None: return [(' ' if nentries else '(') + cadr.n3(g.namespace_manager)] + format_collection(g, cdr, max_entries, nentries+1) else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upgrade_setuptools(): """ setuptools 12.2 can trigger a really nasty bug that eats all memory, so upgrade it to 18.8, which is known to be good. """
# Note - I tried including the higher version in # setup_requires, but was still able to trigger # the bug. - stu.axon global MIN_SETUPTOOLS r = None try: r = pkg_resources.require(["setuptools"])[0] except DistributionNotFound: # ok, setuptools will be installed later return if StrictVersion(r.version) >= StrictVersion(MIN_SETUPTOOLS): return else: print("Upgrading setuptools...") subprocess.call("%s -mpip install 'setuptools>=%s'" % (sys.executable, MIN_SETUPTOOLS), shell=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ Need to find any pre-existing vext contained in dependent packages and install them example: you create a setup.py with install_requires["vext.gi"]: - vext.gi gets installed using bdist_egg - vext itself is now called with bdist_egg and we end up here Vext now needs to find and install .vext files in vext.gi [or any other files that depend on vext] :return: """
logger.debug("vext InstallLib [started]") # Find packages that depend on vext and check for .vext files... logger.debug("find_vext_files") vext_files = self.find_vext_files() logger.debug("manually_install_vext: ", vext_files) self.manually_install_vext(vext_files) logger.debug("enable vext") self.enable_vext() logger.debug("install_lib.run") install_lib.run(self) logger.debug("vext InstallLib [finished]")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_servers(self, servers): """ Iter to a list of servers and instantiate Protocol class. :param servers: A list of servers :type servers: list :return: Returns nothing :rtype: None """
if isinstance(servers, six.string_types): servers = [servers] assert servers, "No memcached servers supplied" self._servers = [Protocol( server=server, username=self.username, password=self.password, compression=self.compression, socket_timeout=self.socket_timeout, pickle_protocol=self.pickle_protocol, pickler=self.pickler, unpickler=self.unpickler, ) for server in servers]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_in_syspy(f): """ Decorator to run a function in the system python :param f: :return: """
fname = f.__name__ code_lines = inspect.getsource(f).splitlines() code = dedent("\n".join(code_lines[1:])) # strip this decorator # add call to the function and print it's result code += dedent("""\n import sys args = sys.argv[1:] result = {fname}(*args) print("%r" % result) """).format(fname=fname) env = os.environ python = findsyspy() logger.debug("Create function for system python\n%s" % code) def call_f(*args): cmd = [python, '-c', code] + list(args) output = subprocess.check_output(cmd, env=env).decode('utf-8') result = ast.literal_eval(output) return result return call_f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cas(self, key, value, cas, time=0, compress_level=-1): """ Set a value for a key on server if its CAS value matches cas. :param key: Key's name :type key: six.string_types :param value: A value to be stored on server. :type value: object :param cas: The CAS value previously obtained from a call to get*. :type cas: int :param time: Time in seconds that your key will expire. :type time: int :param compress_level: How much to compress. 0 = no compression, 1 = fastest, 9 = slowest but best, -1 = default compression level. :type compress_level: int :return: True in case of success and False in case of failure :rtype: bool """
server = self._get_server(key) return server.cas(key, value, cas, time, compress_level)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def matchesCardinality(cntxt: Context, T: RDFGraph, expr: Union[ShExJ.tripleExpr, ShExJ.tripleExprLabel], c: DebugContext) -> bool: """ Evaluate cardinality expression expr has a cardinality of min and/or max not equal to 1, where a max of -1 is treated as unbounded, and T can be partitioned into k subsets T1, T2,…Tk such that min ≤ k ≤ max and for each Tn, matches(Tn, expr, m) by the remaining rules in this list. """
# TODO: Cardinality defaults into spec min_ = expr.min if expr.min is not None else 1 max_ = expr.max if expr.max is not None else 1 cardinality_text = f"{{{min_},{'*' if max_ == -1 else max_}}}" if c.debug and (min_ != 0 or len(T) != 0): print(f"{cardinality_text} matching {len(T)} triples") if min_ == 0 and len(T) == 0: return True if isinstance(expr, ShExJ.TripleConstraint): if len(T) < min_: if len(T) > 0: _fail_triples(cntxt, T) cntxt.fail_reason = f" {len(T)} triples less than {cardinality_text}" else: cntxt.fail_reason = f" No matching triples found for predicate {cntxt.n3_mapper.n3(expr.predicate)}" return False elif 0 <= max_ < len(T): _fail_triples(cntxt, T) cntxt.fail_reason = f" {len(T)} triples exceeds max {cardinality_text}" return False else: return all(matchesTripleConstraint(cntxt, t, expr) for t in T) else: for partition in _partitions(T, min_, max_): if all(matchesExpr(cntxt, part, expr) for part in partition): return True if min_ != 1 or max_ != 1: _fail_triples(cntxt, T) cntxt.fail_reason = f" {len(T)} triples cannot be partitioned into {cardinality_text} passing groups" return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def matchesExpr(cntxt: Context, T: RDFGraph, expr: ShExJ.tripleExpr, _: DebugContext) -> bool: """ Evaluate the expression """
if isinstance(expr, ShExJ.OneOf): return matchesOneOf(cntxt, T, expr) elif isinstance(expr, ShExJ.EachOf): return matchesEachOf(cntxt, T, expr) elif isinstance(expr, ShExJ.TripleConstraint): return matchesCardinality(cntxt, T, expr) elif isinstance_(expr, ShExJ.tripleExprLabel): return matchesTripleExprRef(cntxt, T, expr) else: raise Exception("Unknown expression")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, key, get_cas=False): """ Get a key from server. :param key: Key's name :type key: six.string_types :param get_cas: If true, return (value, cas), where cas is the new CAS value. :type get_cas: boolean :return: Returns a key data from server. :rtype: object """
for server in self.servers: value, cas = server.get(key) if value is not None: if get_cas: return value, cas else: return value if get_cas: return None, None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gets(self, key): """ Get a key from server, returning the value and its CAS key. This method is for API compatibility with other implementations. :param key: Key's name :type key: six.string_types :return: Returns (key data, value), or (None, None) if the value is not in cache. :rtype: object """
for server in self.servers: value, cas = server.get(key) if value is not None: return value, cas return None, None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_result(self, rval: bool) -> None: """ Set the result of the evaluation. If the result is true, prune all of the children that didn't cut it :param rval: Result of evaluation """
self.result = rval if self.result: self.nodes = [pn for pn in self.nodes if pn.result]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reference_of(selector: shapeLabel, cntxt: Union[Context, ShExJ.Schema] ) -> Optional[ShExJ.shapeExpr]: """ Return the shape expression in the schema referenced by selector, if any :param cntxt: Context node or ShEx Schema :param selector: identifier of element to select within the schema :return: """
schema = cntxt.schema if isinstance(cntxt, Context) else cntxt if selector is START: return schema.start for expr in schema.shapes: if not isinstance(expr, ShExJ.ShapeExternal) and expr.id == selector: return expr return schema.start if schema.start is not None and schema.start.id == selector else None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def triple_reference_of(label: ShExJ.tripleExprLabel, cntxt: Context) -> Optional[ShExJ.tripleExpr]: """ Search for the label in a Schema """
te: Optional[ShExJ.tripleExpr] = None if cntxt.schema.start is not None: te = triple_in_shape(cntxt.schema.start, label, cntxt) if te is None: for shapeExpr in cntxt.schema.shapes: te = triple_in_shape(shapeExpr, label, cntxt) if te: break return te
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def triple_in_shape(expr: ShExJ.shapeExpr, label: ShExJ.tripleExprLabel, cntxt: Context) \ -> Optional[ShExJ.tripleExpr]: """ Search for the label in a shape expression """
te = None if isinstance(expr, (ShExJ.ShapeOr, ShExJ.ShapeAnd)): for expr2 in expr.shapeExprs: te = triple_in_shape(expr2, label, cntxt) if te is not None: break elif isinstance(expr, ShExJ.ShapeNot): te = triple_in_shape(expr.shapeExpr, label, cntxt) elif isinstance(expr, ShExJ.shapeExprLabel): se = reference_of(expr, cntxt) if se is not None: te = triple_in_shape(se, label, cntxt) return te
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def integer_partition(size: int, nparts: int) -> Iterator[List[List[int]]]: """ Partition a list of integers into a list of partitions """
for part in algorithm_u(range(size), nparts): yield part
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_simple_literal(n: Node) -> bool: """ simple literal denotes a plain literal with no language tag. """
return is_typed_literal(n) and cast(Literal, n).datatype is None and cast(Literal, n).language is None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print(self, txt: str, hold: bool=False) -> None: """ Conditionally print txt :param txt: text to print :param hold: If true, hang on to the text until another print comes through :param hold: If true, drop both print statements if another hasn't intervened :return: """
if hold: self.held_prints[self.trace_depth] = txt elif self.held_prints[self.trace_depth]: if self.max_print_depth > self.trace_depth: print(self.held_prints[self.trace_depth]) print(txt) self.max_print_depth = self.trace_depth del self.held_prints[self.trace_depth] else: print(txt) self.max_print_depth = self.trace_depth
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self) -> None: """ Reset the context preceeding an evaluation """
self.evaluating = set() self.assumptions = {} self.known_results = {} self.current_node = None self.evaluate_stack = [] self.bnode_map = {}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _gen_schema_xref(self, expr: Optional[Union[ShExJ.shapeExprLabel, ShExJ.shapeExpr]]) -> None: """ Generate the schema_id_map :param expr: root shape expression """
if expr is not None and not isinstance_(expr, ShExJ.shapeExprLabel) and 'id' in expr and expr.id is not None: abs_id = self._resolve_relative_uri(expr.id) if abs_id not in self.schema_id_map: self.schema_id_map[abs_id] = expr if isinstance(expr, (ShExJ.ShapeOr, ShExJ.ShapeAnd)): for expr2 in expr.shapeExprs: self._gen_schema_xref(expr2) elif isinstance(expr, ShExJ.ShapeNot): self._gen_schema_xref(expr.shapeExpr) elif isinstance(expr, ShExJ.Shape): if expr.expression is not None: self._gen_te_xref(expr.expression)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tripleExprFor(self, id_: ShExJ.tripleExprLabel) -> ShExJ.tripleExpr: """ Return the triple expression that corresponds to id """
return self.te_id_map.get(id_)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shapeExprFor(self, id_: Union[ShExJ.shapeExprLabel, START]) -> Optional[ShExJ.shapeExpr]: """ Return the shape expression that corresponds to id """
rval = self.schema.start if id_ is START else self.schema_id_map.get(str(id_)) return rval
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_shapes(self, expr: ShExJ.shapeExpr, f: Callable[[Any, ShExJ.shapeExpr, "Context"], None], arg_cntxt: Any, visit_center: _VisitorCenter = None, follow_inner_shapes: bool=True) -> None: """ Visit expr and all of its "descendant" shapes. :param expr: root shape expression :param f: visitor function :param arg_cntxt: accompanying context for the visitor function :param visit_center: Recursive visit context. (Not normally supplied on an external call) :param follow_inner_shapes: Follow nested shapes or just visit on outer level """
if visit_center is None: visit_center = _VisitorCenter(f, arg_cntxt) has_id = getattr(expr, 'id', None) is not None if not has_id or not (visit_center.already_seen_shape(expr.id) or visit_center.actively_visiting_shape(expr.id)): # Visit the root expression if has_id: visit_center.start_visiting_shape(expr.id) f(arg_cntxt, expr, self) # Traverse the expression and visit its components if isinstance(expr, (ShExJ.ShapeOr, ShExJ.ShapeAnd)): for expr2 in expr.shapeExprs: self.visit_shapes(expr2, f, arg_cntxt, visit_center, follow_inner_shapes=follow_inner_shapes) elif isinstance(expr, ShExJ.ShapeNot): self.visit_shapes(expr.shapeExpr, f, arg_cntxt, visit_center, follow_inner_shapes=follow_inner_shapes) elif isinstance(expr, ShExJ.Shape): if expr.expression is not None and follow_inner_shapes: self.visit_triple_expressions(expr.expression, lambda ac, te, cntxt: self._visit_shape_te(te, visit_center), arg_cntxt, visit_center) elif isinstance_(expr, ShExJ.shapeExprLabel): if not visit_center.actively_visiting_shape(str(expr)) and follow_inner_shapes: visit_center.start_visiting_shape(str(expr)) self.visit_shapes(self.shapeExprFor(expr), f, arg_cntxt, visit_center) visit_center.done_visiting_shape(str(expr)) if has_id: visit_center.done_visiting_shape(expr.id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _visit_te_shape(self, shape: ShExJ.shapeExpr, visit_center: _VisitorCenter) -> None: """ Visit a shape expression that was reached through a triple expression. This, in turn, is used to visit additional triple expressions that are referenced by the Shape :param shape: Shape reached through triple expression traverse :param visit_center: context used in shape visitor """
if isinstance(shape, ShExJ.Shape) and shape.expression is not None: visit_center.f(visit_center.arg_cntxt, shape.expression, self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def type_last(self, obj: JsonObj) -> JsonObj: """ Move the type identifiers to the end of the object for print purposes """
def _tl_list(v: List) -> List: return [self.type_last(e) if isinstance(e, JsonObj) else _tl_list(e) if isinstance(e, list) else e for e in v if e is not None] rval = JsonObj() for k in as_dict(obj).keys(): v = obj[k] if v is not None and k not in ('type', '_context'): rval[k] = _tl_list(v) if isinstance(v, list) else self.type_last(v) if isinstance(v, JsonObj) else v if 'type' in obj and obj.type: rval.type = obj.type return rval
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def satisfiesExternal(cntxt: Context, n: Node, se: ShExJ.ShapeExternal, c: DebugContext) -> bool: """ Se is a ShapeExternal and implementation-specific mechansims not defined in this specification indicate success. """
if c.debug: print(f"id: {se.id}") extern_shape = cntxt.external_shape_for(se.id) if extern_shape: return satisfies(cntxt, n, extern_shape) cntxt.fail_reason = f"{se.id}: Shape is not in Schema" return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize_uri(u: URI) -> URIRef: """ Return a URIRef for a str or URIRef """
return u if isinstance(u, URIRef) else URIRef(str(u))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize_uriparm(p: URIPARM) -> List[URIRef]: """ Return an optional list of URIRefs for p"""
return normalize_urilist(p) if isinstance(p, List) else \ normalize_urilist([p]) if isinstance(p, (str, URIRef)) else p
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize_startparm(p: STARTPARM) -> List[Union[type(START), START_TYPE, URIRef]]: """ Return the startspec for p """
if not isinstance(p, list): p = [p] return [normalize_uri(e) if isinstance(e, str) and e is not START else e for e in p]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rdf(self, rdf: Optional[Union[str, Graph]]) -> None: """ Set the RDF DataSet to be evaulated. If ``rdf`` is a string, the presence of a return is the indicator that it is text instead of a location. :param rdf: File name, URL, representation of rdflib Graph """
if isinstance(rdf, Graph): self.g = rdf else: self.g = Graph() if isinstance(rdf, str): if '\n' in rdf or '\r' in rdf: self.g.parse(data=rdf, format=self.rdf_format) elif ':' in rdf: self.g.parse(location=rdf, format=self.rdf_format) else: self.g.parse(source=rdf, format=self.rdf_format)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def schema(self, shex: Optional[Union[str, ShExJ.Schema]]) -> None: """ Set the schema to be used. Schema can either be a ShExC or ShExJ string or a pre-parsed schema. :param shex: Schema """
self.pfx = None if shex is not None: if isinstance(shex, ShExJ.Schema): self._schema = shex else: shext = shex.strip() loader = SchemaLoader() if ('\n' in shex or '\r' in shex) or shext[0] in '#<_: ': self._schema = loader.loads(shex) else: self._schema = loader.load(shex) if isinstance(shex, str) else shex if self._schema is None: raise ValueError("Unable to parse shex file") self.pfx = PrefixLibrary(loader.schema_text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_base(path: str) -> str: """ Convert path, which can be a URL or a file path into a base URI :param path: file location or url :return: file location or url sans actual name """
if ':' in path: parts = urlparse(path) parts_dict = parts._asdict() parts_dict['path'] = os.path.split(parts.path)[0] if '/' in parts.path else '' return urlunparse(ParseResult(**parts_dict)) + '/' else: return (os.path.split(path)[0] if '/' in path else '') + '/'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_socket(self, size): """ Reads data from socket. :param size: Size in bytes to be read. :return: Data from socket """
value = b'' while len(value) < size: data = self.connection.recv(size - len(value)) if not data: break value += data # If we got less data than we requested, the server disconnected. if len(value) < size: raise socket.error() return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_response(self): """ Get memcached response from socket. :return: A tuple with binary values from memcached. :rtype: tuple """
try: self._open_connection() if self.connection is None: # The connection wasn't opened, which means we're deferring a reconnection attempt. # Raise a socket.error, so we'll return the same server_disconnected message as we # do below. raise socket.error('Delaying reconnection attempt') header = self._read_socket(self.HEADER_SIZE) (magic, opcode, keylen, extlen, datatype, status, bodylen, opaque, cas) = struct.unpack(self.HEADER_STRUCT, header) assert magic == self.MAGIC['response'] extra_content = None if bodylen: extra_content = self._read_socket(bodylen) return (magic, opcode, keylen, extlen, datatype, status, bodylen, opaque, cas, extra_content) except socket.error as e: self._connection_error(e) # (magic, opcode, keylen, extlen, datatype, status, bodylen, opaque, cas, extra_content) message = str(e) return (self.MAGIC['response'], -1, 0, 0, 0, self.STATUS['server_disconnected'], 0, 0, 0, message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticate(self, username, password): """ Authenticate user on server. :param username: Username used to be authenticated. :type username: six.string_types :param password: Password used to be authenticated. :type password: six.string_types :return: True if successful. :raises: InvalidCredentials, AuthenticationNotSupported, MemcachedException :rtype: bool """
self._username = username self._password = password # Reopen the connection with the new credentials. self.disconnect() self._open_connection() return self.authenticated
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize(self, value, compress_level=-1): """ Serializes a value based on its type. :param value: Something to be serialized :type value: six.string_types, int, long, object :param compress_level: How much to compress. 0 = no compression, 1 = fastest, 9 = slowest but best, -1 = default compression level. :type compress_level: int :return: Serialized type :rtype: str """
flags = 0 if isinstance(value, binary_type): flags |= self.FLAGS['binary'] elif isinstance(value, text_type): value = value.encode('utf8') elif isinstance(value, int) and isinstance(value, bool) is False: flags |= self.FLAGS['integer'] value = str(value) elif isinstance(value, long) and isinstance(value, bool) is False: flags |= self.FLAGS['long'] value = str(value) else: flags |= self.FLAGS['object'] buf = BytesIO() pickler = self.pickler(buf, self.pickle_protocol) pickler.dump(value) value = buf.getvalue() if compress_level != 0 and len(value) > self.COMPRESSION_THRESHOLD: if compress_level is not None and compress_level > 0: # Use the specified compression level. compressed_value = self.compression.compress(value, compress_level) else: # Use the default compression level. compressed_value = self.compression.compress(value) # Use the compressed value only if it is actually smaller. if compressed_value and len(compressed_value) < len(value): value = compressed_value flags |= self.FLAGS['compressed'] return flags, value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deserialize(self, value, flags): """ Deserialized values based on flags or just return it if it is not serialized. :param value: Serialized or not value. :type value: six.string_types, int :param flags: Value flags :type flags: int :return: Deserialized value :rtype: six.string_types|int """
FLAGS = self.FLAGS if flags & FLAGS['compressed']: # pragma: no branch value = self.compression.decompress(value) if flags & FLAGS['binary']: return value if flags & FLAGS['integer']: return int(value) elif flags & FLAGS['long']: return long(value) elif flags & FLAGS['object']: buf = BytesIO(value) unpickler = self.unpickler(buf) return unpickler.load() if six.PY3: return value.decode('utf8') # In Python 2, mimic the behavior of the json library: return a str # unless the value contains unicode characters. # in Python 2, if value is a binary (e.g struct.pack("<Q") then decode will fail try: value.decode('ascii') except UnicodeDecodeError: try: return value.decode('utf8') except UnicodeDecodeError: return value else: return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def noop(self): """ Send a NOOP command :return: Returns the status. :rtype: int """
logger.debug('Sending NOOP') data = struct.pack(self.HEADER_STRUCT + self.COMMANDS['noop']['struct'], self.MAGIC['request'], self.COMMANDS['noop']['command'], 0, 0, 0, 0, 0, 0, 0) self._send(data) (magic, opcode, keylen, extlen, datatype, status, bodylen, opaque, cas, extra_content) = self._get_response() logger.debug('Value Length: %d. Body length: %d. Data type: %d', extlen, bodylen, datatype) if status != self.STATUS['success']: logger.debug('NOOP failed (status is %d). Message: %s' % (status, extra_content)) return int(status)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_multi(self, mappings, time=100, compress_level=-1): """ Set multiple keys with its values on server. If a key is a (key, cas) tuple, insert as if cas(key, value, cas) had been called. :param mappings: A dict with keys/values :type mappings: dict :param time: Time in seconds that your key will expire. :type time: int :param compress_level: How much to compress. 0 = no compression, 1 = fastest, 9 = slowest but best, -1 = default compression level. :type compress_level: int :return: True :rtype: bool """
mappings = mappings.items() msg = [] for key, value in mappings: if isinstance(key, tuple): key, cas = key else: cas = None if cas == 0: # Like cas(), if the cas value is 0, treat it as compare-and-set against not # existing. command = 'addq' else: command = 'setq' flags, value = self.serialize(value, compress_level=compress_level) m = struct.pack(self.HEADER_STRUCT + self.COMMANDS[command]['struct'] % (len(key), len(value)), self.MAGIC['request'], self.COMMANDS[command]['command'], len(key), 8, 0, 0, len(key) + len(value) + 8, 0, cas or 0, flags, time, str_to_bytes(key), value) msg.append(m) m = struct.pack(self.HEADER_STRUCT + self.COMMANDS['noop']['struct'], self.MAGIC['request'], self.COMMANDS['noop']['command'], 0, 0, 0, 0, 0, 0, 0) msg.append(m) if six.PY2: msg = ''.join(msg) else: msg = b''.join(msg) self._send(msg) opcode = -1 retval = True while opcode != self.COMMANDS['noop']['command']: (magic, opcode, keylen, extlen, datatype, status, bodylen, opaque, cas, extra_content) = self._get_response() if status != self.STATUS['success']: retval = False if status == self.STATUS['server_disconnected']: break return retval
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _incr_decr(self, command, key, value, default, time): """ Function which increments and decrements. :param key: Key's name :type key: six.string_types :param value: Number to be (de|in)cremented :type value: int :param default: Default value if key does not exist. :type default: int :param time: Time in seconds to expire key. :type time: int :return: Actual value of the key on server :rtype: int """
time = time if time >= 0 else self.MAXIMUM_EXPIRE_TIME self._send(struct.pack(self.HEADER_STRUCT + self.COMMANDS[command]['struct'] % len(key), self.MAGIC['request'], self.COMMANDS[command]['command'], len(key), 20, 0, 0, len(key) + 20, 0, 0, value, default, time, str_to_bytes(key))) (magic, opcode, keylen, extlen, datatype, status, bodylen, opaque, cas, extra_content) = self._get_response() if status not in (self.STATUS['success'], self.STATUS['server_disconnected']): raise MemcachedException('Code: %d Message: %s' % (status, extra_content), status) if status == self.STATUS['server_disconnected']: return 0 return struct.unpack('!Q', extra_content)[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def incr(self, key, value, default=0, time=1000000): """ Increment a key, if it exists, returns its actual value, if it doesn't, return 0. :param key: Key's name :type key: six.string_types :param value: Number to be incremented :type value: int :param default: Default value if key does not exist. :type default: int :param time: Time in seconds to expire key. :type time: int :return: Actual value of the key on server :rtype: int """
return self._incr_decr('incr', key, value, default, time)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decr(self, key, value, default=0, time=100): """ Decrement a key, if it exists, returns its actual value, if it doesn't, return 0. Minimum value of decrement return is 0. :param key: Key's name :type key: six.string_types :param value: Number to be decremented :type value: int :param default: Default value if key does not exist. :type default: int :param time: Time in seconds to expire key. :type time: int :return: Actual value of the key on server :rtype: int """
return self._incr_decr('decr', key, value, default, time)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_multi(self, keys): """ Delete multiple keys from server in one command. :param keys: A list of keys to be deleted :type keys: list :return: True in case of success and False in case of failure. :rtype: bool """
logger.debug('Deleting keys %r', keys) if six.PY2: msg = '' else: msg = b'' for key in keys: msg += struct.pack( self.HEADER_STRUCT + self.COMMANDS['delete']['struct'] % len(key), self.MAGIC['request'], self.COMMANDS['delete']['command'], len(key), 0, 0, 0, len(key), 0, 0, str_to_bytes(key)) msg += struct.pack( self.HEADER_STRUCT + self.COMMANDS['noop']['struct'], self.MAGIC['request'], self.COMMANDS['noop']['command'], 0, 0, 0, 0, 0, 0, 0) self._send(msg) opcode = -1 retval = True while opcode != self.COMMANDS['noop']['command']: (magic, opcode, keylen, extlen, datatype, status, bodylen, opaque, cas, extra_content) = self._get_response() if status != self.STATUS['success']: retval = False if status == self.STATUS['server_disconnected']: break return retval
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_shex(self, schema: str) -> "PrefixLibrary": """ Add a ShExC schema to the library :param schema: ShExC schema text, URL or file name :return: prefix library object """
if '\n' in schema or '\r' in schema or ' ' in schema: shex = schema else: shex = load_shex_file(schema) for line in shex.split('\n'): line = line.strip() m = re.match(r'PREFIX\s+(\S+):\s+<(\S+)>', line) if not m: m = re.match(r"@prefix\s+(\S+):\s+<(\S+)>\s+\.", line) if m: setattr(self, m.group(1).upper(), Namespace(m.group(2))) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_bindings(self, g: Graph) -> "PrefixLibrary": """ Add bindings in the library to the graph :param g: graph to add prefixes to :return: PrefixLibrary object """
for prefix, namespace in self: g.bind(prefix.lower(), namespace) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self, schema_file: Union[str, TextIO], schema_location: Optional[str]=None) -> ShExJ.Schema: """ Load a ShEx Schema from schema_location :param schema_file: name or file-like object to deserialize :param schema_location: URL or file name of schema. Used to create the base_location :return: ShEx Schema represented by schema_location """
if isinstance(schema_file, str): schema_file = self.location_rewrite(schema_file) self.schema_text = load_shex_file(schema_file) else: self.schema_text = schema_file.read() if self.base_location: self.root_location = self.base_location elif schema_location: self.root_location = os.path.dirname(schema_location) + '/' else: self.root_location = None return self.loads(self.schema_text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loads(self, schema_txt: str) -> ShExJ.Schema: """ Parse and return schema as a ShExJ Schema :param schema_txt: ShExC or ShExJ representation of a ShEx Schema :return: ShEx Schema representation of schema """
self.schema_text = schema_txt if schema_txt.strip()[0] == '{': # TODO: figure out how to propagate self.base_location into this parse return cast(ShExJ.Schema, loads(schema_txt, ShExJ)) else: return generate_shexj.parse(schema_txt, self.base_location)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _run(self): '''Continually poll TWS''' stop = self._stop_evt connected = self._connected_evt tws = self._tws fd = tws.fd() pollfd = [fd] while not stop.is_set(): while (not connected.is_set() or not tws.isConnected()) and not stop.is_set(): connected.clear() backoff = 0 retries = 0 while not connected.is_set() and not stop.is_set(): if tws.reconnect_auto and not tws.reconnect(): if backoff < self.MAX_BACKOFF: retries += 1 backoff = min(2**(retries + 1), self.MAX_BACKOFF) connected.wait(backoff / 1000.) else: connected.wait(1) fd = tws.fd() pollfd = [fd] if fd > 0: try: evtin, _evtout, evterr = select.select(pollfd, [], pollfd, 1) except select.error: connected.clear() continue else: if fd in evtin: try: if not tws.checkMessages(): tws.eDisconnect(stop_polling=False) continue except (SystemExit, SystemError, KeyboardInterrupt): break except: try: self._wrapper.pyError(*sys.exc_info()) except: print_exc() elif fd in evterr: connected.clear() continue
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def error(self, id, errorCode, errorString): '''Error during communication with TWS''' if errorCode == 165: # Historical data sevice message sys.stderr.write("TWS INFO - %s: %s\n" % (errorCode, errorString)) elif errorCode >= 501 and errorCode < 600: # Socket read failed sys.stderr.write("TWS CLIENT-ERROR - %s: %s\n" % (errorCode, errorString)) elif errorCode >= 100 and errorCode < 1100: sys.stderr.write("TWS ERROR - %s: %s\n" % (errorCode, errorString)) elif errorCode >= 1100 and errorCode < 2100: sys.stderr.write("TWS SYSTEM-ERROR - %s: %s\n" % (errorCode, errorString)) elif errorCode in (2104, 2106, 2108): sys.stderr.write("TWS INFO - %s: %s\n" % (errorCode, errorString)) elif errorCode >= 2100 and errorCode <= 2110: sys.stderr.write("TWS WARNING - %s: %s\n" % (errorCode, errorString)) else: sys.stderr.write("TWS ERROR - %s: %s\n" % (errorCode, errorString))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pyError(self, type, value, traceback): '''Handles an error thrown during invocation of an EWrapper method. Arguments are those provided by sys.exc_info() ''' sys.stderr.write("Exception thrown during EWrapper method dispatch:\n") print_exception(type, value, traceback)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _decompress(self, compressed_payload): '''Decompress a compressed payload into this payload wrapper. Note that the decompressed buffer is saved in self._data and the counts array is not yet allocated. Args: compressed_payload (string) a payload in zlib compressed form Exception: HdrCookieException: the compressed payload has an invalid cookie HdrLengthException: the decompressed size is too small for the HdrPayload structure or is not aligned or is too large for the passed payload class HdrHistogramSettingsException: mismatch in the significant figures, lowest and highest trackable value ''' # make sure this instance is pristine if self._data: raise RuntimeError('Cannot decompress to an instance with payload') # Here it is important to keep a reference to the decompressed # string so that it does not get garbage collected self._data = zlib.decompress(compressed_payload) len_data = len(self._data) counts_size = len_data - payload_header_size if payload_header_size > counts_size > MAX_COUNTS_SIZE: raise HdrLengthException('Invalid size:' + str(len_data)) # copy the first bytes for the header self.payload = PayloadHeader.from_buffer_copy(self._data) cookie = self.payload.cookie if get_cookie_base(cookie) != V2_ENCODING_COOKIE_BASE: raise HdrCookieException('Invalid cookie: %x' % cookie) word_size = get_word_size_in_bytes_from_cookie(cookie) if word_size != V2_MAX_WORD_SIZE_IN_BYTES: raise HdrCookieException('Invalid V2 cookie: %x' % cookie)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def encode(self): '''Compress the associated encodable payload, prepend the header then encode with base64 if requested Returns: the b64 encoded wire encoding of the histogram (as a string) or the compressed payload (as a string, if b64 wrappinb is disabled) ''' # only compress the first non zero buckets # if histogram is empty we do not encode any counter if self.histogram.total_count: relevant_length = \ self.histogram.get_counts_array_index(self.histogram.max_value) + 1 else: relevant_length = 0 cpayload = self.payload.compress(relevant_length) if self.b64_wrap: self.header.length = len(cpayload) header_str = ctypes.string_at(addressof(self.header), ext_header_size) return base64.b64encode(header_str + cpayload) return cpayload
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def record_value(self, value, count=1): '''Record a new value into the histogram Args: value: the value to record (must be in the valid range) count: incremental count (defaults to 1) ''' if value < 0: return False counts_index = self._counts_index_for(value) if (counts_index < 0) or (self.counts_len <= counts_index): return False self.counts[counts_index] += count self.total_count += count self.min_value = min(self.min_value, value) self.max_value = max(self.max_value, value) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def record_corrected_value(self, value, expected_interval, count=1): '''Record a new value into the histogram and correct for coordinated omission if needed Args: value: the value to record (must be in the valid range) expected_interval: the expected interval between 2 value samples count: incremental count (defaults to 1) ''' while True: if not self.record_value(value, count): return False if value <= expected_interval or expected_interval <= 0: return True value -= expected_interval
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_value_at_percentile(self, percentile): '''Get the value for a given percentile Args: percentile: a float in [0.0..100.0] Returns: the value for the given percentile ''' count_at_percentile = self.get_target_count_at_percentile(percentile) total = 0 for index in range(self.counts_len): total += self.get_count_at_index(index) if total >= count_at_percentile: value_at_index = self.get_value_from_index(index) if percentile: return self.get_highest_equivalent_value(value_at_index) return self.get_lowest_equivalent_value(value_at_index) return 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_percentile_to_value_dict(self, percentile_list): '''A faster alternative to query values for a list of percentiles. Args: percentile_list: a list of percentiles in any order, dups will be ignored each element in the list must be a float value in [0.0 .. 100.0] Returns: a dict of percentile values indexed by the percentile ''' result = {} total = 0 percentile_list_index = 0 count_at_percentile = 0 # remove dups and sort percentile_list = list(set(percentile_list)) percentile_list.sort() for index in range(self.counts_len): total += self.get_count_at_index(index) while True: # recalculate target based on next requested percentile if not count_at_percentile: if percentile_list_index == len(percentile_list): return result percentile = percentile_list[percentile_list_index] percentile_list_index += 1 if percentile > 100: return result count_at_percentile = self.get_target_count_at_percentile(percentile) if total >= count_at_percentile: value_at_index = self.get_value_from_index(index) if percentile: result[percentile] = self.get_highest_equivalent_value(value_at_index) else: result[percentile] = self.get_lowest_equivalent_value(value_at_index) count_at_percentile = 0 else: break return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def reset(self): '''Reset the histogram to a pristine state ''' for index in range(self.counts_len): self.counts[index] = 0 self.total_count = 0 self.min_value = sys.maxsize self.max_value = 0 self.start_time_stamp_msec = sys.maxsize self.end_time_stamp_msec = 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_counts_array_index(self, value): '''Return the index in the counts array for a given value ''' if value < 0: raise ValueError("Histogram recorded value cannot be negative.") bucket_index = self._get_bucket_index(value) sub_bucket_index = self._get_sub_bucket_index(value, bucket_index) # Calculate the index for the first entry in the bucket: bucket_base_index = (bucket_index + 1) << self.sub_bucket_half_count_magnitude # The following is the equivalent of ((bucket_index + 1) * sub_bucket_half_count) # Calculate the offset in the bucket (can be negative for first bucket): offset_in_bucket = sub_bucket_index - self.sub_bucket_half_count # The following is the equivalent of # ((sub_bucket_index - sub_bucket_half_count) + bucket_base_index return bucket_base_index + offset_in_bucket
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_jsonschema_from_file(self, json_string, path_to_schema): """ Validate JSON according to schema, loaded from a file. *Args:*\n _json_string_ - JSON string;\n _path_to_schema_ - path to file with JSON schema; *Raises:*\n JsonValidatorError *Example:*\n | *Settings* | *Value* | | Library | JsonValidator | | *Test Cases* | *Action* | *Argument* | *Argument* | | Simple | Validate jsonschema from file | {"foo":bar} | ${CURDIR}${/}schema.json | """
schema = open(path_to_schema).read() load_input_json = self.string_to_json(json_string) try: load_schema = json.loads(schema) except ValueError as e: raise JsonValidatorError('Error in schema: {}'.format(e)) self._validate_json(load_input_json, load_schema)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_jsonschema(self, json_string, input_schema): """ Validate JSON according to schema. *Args:*\n _json_string_ - JSON string;\n _input_schema_ - schema in string format; *Raises:*\n JsonValidatorError *Example:*\n | *Settings* | *Value* | | Library | JsonValidator | | Library | OperatingSystem | | *Test Cases* | *Action* | *Argument* | *Argument* | | Simple | ${schema}= | OperatingSystem.Get File | ${CURDIR}${/}schema_valid.json | | | Validate jsonschema | {"foo":bar} | ${schema} | """
load_input_json = self.string_to_json(json_string) try: load_schema = json.loads(input_schema) except ValueError as e: raise JsonValidatorError('Error in schema: {}'.format(e)) self._validate_json(load_input_json, load_schema)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_json(self, json_string, expr, value, index=0): """ Replace the value in the JSON string. *Args:*\n _json_string_ - JSON string;\n _expr_ - JSONPath expression for determining the value to be replaced;\n _value_ - the value to be replaced with;\n _index_ - index for selecting item within a match list, default value is 0;\n *Returns:*\n Changed JSON in dictionary format. *Example:*\n | *Settings* | *Value* | | Library | JsonValidator | | Library | OperatingSystem | | *Test Cases* | *Action* | *Argument* | *Argument* | | Update element | ${json_example}= | OperatingSystem.Get File | ${CURDIR}${/}json_example.json | | | ${json_update}= | Update_json | ${json_example} | $..color | changed | """
load_input_json = self.string_to_json(json_string) matches = self._json_path_search(load_input_json, expr) datum_object = matches[int(index)] if not isinstance(datum_object, DatumInContext): raise JsonValidatorError("Nothing found by the given json-path") path = datum_object.path # Edit the directory using the received data # If the user specified a list if isinstance(path, Index): datum_object.context.value[datum_object.path.index] = value # If the user specified a value of type (string, bool, integer or complex) elif isinstance(path, Fields): datum_object.context.value[datum_object.path.fields[0]] = value return load_input_json
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def sanitize(value): ''' Sanitizes strings according to SANITIZER_ALLOWED_TAGS, SANITIZER_ALLOWED_ATTRIBUTES and SANITIZER_ALLOWED_STYLES variables in settings. Example usage: {% load sanitizer %} {{ post.content|escape_html }} ''' if isinstance(value, basestring): value = bleach.clean(value, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES, styles=ALLOWED_STYLES, strip=False) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def strip_filter(value): ''' Strips HTML tags from strings according to SANITIZER_ALLOWED_TAGS, SANITIZER_ALLOWED_ATTRIBUTES and SANITIZER_ALLOWED_STYLES variables in settings. Example usage: {% load sanitizer %} {{ post.content|strip_html }} ''' if isinstance(value, basestring): value = bleach.clean(value, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES, styles=ALLOWED_STYLES, strip=True) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def escape_html(value, allowed_tags=[], allowed_attributes=[], allowed_styles=[]): """ Template tag to sanitize string values. It accepts lists of allowed tags, attributes or styles in comma separated string or list format. For example: {% load sanitizer %} {% escape_html '<a href="">bar</a> <script>alert('baz')</script>' "a,img' 'href',src' %} Will output: <a href="">bar</a> &lt;cript&gt;alert('baz')&lt;/script&gt; On django 1.4 you could also use keyword arguments: {% escape_html '<a href="">bar</a>' allowed_tags="a,img' allowed_attributes='href',src' %} """
if isinstance(value, basestring): value = bleach.clean(value, tags=allowed_tags, attributes=allowed_attributes, styles=allowed_styles, strip=False) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strip_html(value, allowed_tags=[], allowed_attributes=[], allowed_styles=[]): """ Template tag to strip html from string values. It accepts lists of allowed tags, attributes or stylesin comma separated string or list format. For example: {% load sanitizer %} {% strip_html '<a href="">bar</a> <script>alert('baz')</script>' "a,img' 'href',src' %} Will output: <a href="">bar</a> alert('baz'); On django 1.4 you could also use keyword arguments: {% strip_html '<a href="">bar</a>' allowed_tags="a,img' allowed_attributes='href',src' %} """
if isinstance(value, basestring): value = bleach.clean(value, tags=allowed_tags, attributes=allowed_attributes, styles=allowed_styles, strip=True) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def censor(input_text): """ Returns the input string with profanity replaced with a random string of characters plucked from the censor_characters pool. """
ret = input_text words = get_words() for word in words: curse_word = re.compile(re.escape(word), re.IGNORECASE) cen = "".join(get_censor_char() for i in list(word)) ret = curse_word.sub(cen, ret) return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def convert(csv, json, **kwargs): '''Convert csv to json. csv: filename or file-like object json: filename or file-like object if csv is '-' or None: stdin is used for input if json is '-' or None: stdout is used for output ''' csv_local, json_local = None, None try: if csv == '-' or csv is None: csv = sys.stdin elif isinstance(csv, str): csv = csv_local = open(csv, 'r') if json == '-' or json is None: json = sys.stdout elif isinstance(json, str): json = json_local = open(json, 'w') data = load_csv(csv, **kwargs) save_json(data, json, **kwargs) finally: if csv_local is not None: csv_local.close() if json_local is not None: json_local.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_dicts(self, sentence): """Add new sentence to generate dictionaries. :param sentence: A list of strings representing the sentence. """
self.dict_generator(sentence=sentence) self.word_dict, self.char_dict = None, None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_dicts(self, word_dict, char_dict): """Set with custom dictionaries. :param word_dict: The word dictionary. :param char_dict: The character dictionary. """
self.word_dict = word_dict self.char_dict = char_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_dicts(self): """Get word and character dictionaries. :return word_dict, char_dict: """
if self.word_dict is None: self.word_dict, self.char_dict, self.max_word_len = self.dict_generator(return_dict=True) return self.word_dict, self.char_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_dicts_generator(word_min_freq=4, char_min_freq=2, word_ignore_case=False, char_ignore_case=False): """Get word and character dictionaries from sentences. :param word_min_freq: The minimum frequency of a word. :param char_min_freq: The minimum frequency of a character. :param word_ignore_case: Word will be transformed to lower case before saving to dictionary. :param char_ignore_case: Character will be transformed to lower case before saving to dictionary. :return gen: A closure that accepts sentences and returns the dictionaries. """
word_count, char_count = {}, {} def get_dicts(sentence=None, return_dict=False): """Update and return dictionaries for each sentence. :param sentence: A list of strings representing the sentence. :param return_dict: Returns the dictionaries if it is True. :return word_dict, char_dict, max_word_len: """ if sentence is not None: for word in sentence: if not word: continue if word_ignore_case: word_key = word.lower() else: word_key = word word_count[word_key] = word_count.get(word_key, 0) + 1 for char in word: if char_ignore_case: char_key = char.lower() else: char_key = char char_count[char_key] = char_count.get(char_key, 0) + 1 if not return_dict: return None word_dict, char_dict = {'': 0, '<UNK>': 1}, {'': 0, '<UNK>': 1} max_word_len = 0 for word, count in word_count.items(): if count >= word_min_freq: word_dict[word] = len(word_dict) max_word_len = max(max_word_len, len(word)) for char, count in char_count.items(): if count >= char_min_freq: char_dict[char] = len(char_dict) return word_dict, char_dict, max_word_len return get_dicts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_word_list_eng(text): """A naive function that extracts English words from raw texts. :param text: The raw text. :return words: A list of strings. """
words, index = [''], 0 while index < len(text): while index < len(text) and ('a' <= text[index] <= 'z' or 'A' <= text[index] <= 'Z'): words[-1] += text[index] index += 1 if words[-1]: words.append('') while index < len(text) and not ('a' <= text[index] <= 'z' or 'A' <= text[index] <= 'Z'): if text[index] != ' ': words[-1] += text[index] index += 1 if words[-1]: words.append('') if not words[-1]: words.pop() return words
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_embedding_weights_from_file(word_dict, file_path, ignore_case=False): """Load pre-trained embeddings from a text file. Each line in the file should look like this: The `feature_dim_i` should be a floating point number. :param word_dict: A dict that maps words to indice. :param file_path: The location of the text file containing the pre-trained embeddings. :param ignore_case: Whether ignoring the case of the words. :return weights: A numpy array. """
pre_trained = {} with codecs.open(file_path, 'r', 'utf8') as reader: for line in reader: line = line.strip() if not line: continue parts = line.split() if ignore_case: parts[0] = parts[0].lower() pre_trained[parts[0]] = list(map(float, parts[1:])) embd_dim = len(next(iter(pre_trained.values()))) weights = [[0.0] * embd_dim for _ in range(max(word_dict.values()) + 1)] for word, index in word_dict.items(): if not word: continue if ignore_case: word = word.lower() if word in pre_trained: weights[index] = pre_trained[word] else: weights[index] = numpy.random.random((embd_dim,)).tolist() return numpy.asarray(weights)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_backends(): """Loads all backends"""
global _BACKENDS, _ACTIVE_BACKENDS try: from .cffi_backend import CFFIBackend except ImportError: pass else: _BACKENDS.append(CFFIBackend) from .ctypes_backend import CTypesBackend from .null_backend import NullBackend _BACKENDS.append(CTypesBackend) _ACTIVE_BACKENDS = _BACKENDS[:] # null isn't active by default _BACKENDS.append(NullBackend)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_backend(name): """Returns the backend by name or raises KeyError"""
for backend in _BACKENDS: if backend.NAME == name: return backend raise KeyError("Backend %r not available" % name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pprint(obj, file_=None): """Prints debug information for various public objects like methods, functions, constructors etc. """
if file_ is None: file_ = sys.stdout # functions, methods if callable(obj) and hasattr(obj, "_code"): obj._code.pprint(file_) return # classes if isinstance(obj, type) and hasattr(obj, "_constructors"): constructors = obj._constructors for names, func in sorted(constructors.items()): func._code.pprint(file_) return raise TypeError("unkown type")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_field_type(info): """A field python type"""
type_ = info.get_type() cls = get_field_class(type_) field = cls(info, type_, None) field.setup() return field.py_type
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def child_get(self, child, *prop_names): """Returns a list of child property values for the given names."""
return [self.child_get_property(child, name) for name in prop_names]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_tag(self, tag_name=None, **properties): """Creates a tag and adds it to the tag table of the TextBuffer. :param str tag_name: Name of the new tag, or None :param **properties: Keyword list of properties and their values :returns: A new tag. This is equivalent to creating a Gtk.TextTag and then adding the tag to the buffer's tag table. The returned tag is owned by the buffer's tag table. If ``tag_name`` is None, the tag is anonymous. If ``tag_name`` is not None, a tag called ``tag_name`` must not already exist in the tag table for this buffer. Properties are passed as a keyword list of names and values (e.g. foreground='DodgerBlue', weight=Pango.Weight.BOLD) """
tag = Gtk.TextTag(name=tag_name, **properties) self._get_or_create_tag_table().add(tag) return tag
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _convert_value(self, column, value): '''Convert value to a GObject.Value of the expected type''' if isinstance(value, GObject.Value): return value return GObject.Value(self.get_column_type(column), value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_value(self, iter, column, value): """Set the value of the child model"""
# Delegate to child model iter = self.convert_iter_to_child_iter(iter) self.get_model().set_value(iter, column, value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_foreign_module(namespace): """Returns the module or raises ForeignError"""
if namespace not in _MODULES: try: module = importlib.import_module("." + namespace, __package__) except ImportError: module = None _MODULES[namespace] = module module = _MODULES.get(namespace) if module is None: raise ForeignError("Foreign %r structs not supported" % namespace) return module
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_foreign_struct(namespace, name): """Returns a ForeignStruct implementation or raises ForeignError"""
get_foreign_module(namespace) try: return ForeignStruct.get(namespace, name) except KeyError: raise ForeignError("Foreign %s.%s not supported" % (namespace, name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def require_foreign(namespace, symbol=None): """Raises ImportError if the specified foreign module isn't supported or the needed dependencies aren't installed. e.g.: check_foreign('cairo', 'Context') """
try: if symbol is None: get_foreign_module(namespace) else: get_foreign_struct(namespace, symbol) except ForeignError as e: raise ImportError(e)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create(self, format, args): """Create a GVariant object from given format and argument list. This method recursively calls itself for complex structures (arrays, dictionaries, boxed). Return a tuple (variant, rest_format, rest_args) with the generated GVariant, the remainder of the format string, and the remainder of the arguments. If args is None, then this won't actually consume any arguments, and just parse the format string and generate empty GVariant structures. This is required for creating empty dictionaries or arrays. """
# leaves (simple types) constructor = self._LEAF_CONSTRUCTORS.get(format[0]) if constructor: if args is not None: if not args: raise TypeError('not enough arguments for GVariant format string') v = constructor(args[0]) return (v, format[1:], args[1:]) else: return (None, format[1:], None) if format[0] == '(': return self._create_tuple(format, args) if format.startswith('a{'): return self._create_dict(format, args) if format[0] == 'a': return self._create_array(format, args) raise NotImplementedError('cannot handle GVariant type ' + format)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_tuple(self, format, args): """Handle the case where the outermost type of format is a tuple."""
format = format[1:] # eat the '(' if args is None: # empty value: we need to call _create() to parse the subtype rest_format = format while rest_format: if rest_format.startswith(')'): break rest_format = self._create(rest_format, None)[1] else: raise TypeError('tuple type string not closed with )') rest_format = rest_format[1:] # eat the ) return (None, rest_format, None) else: if not args or not isinstance(args[0], tuple): raise TypeError('expected tuple argument') builder = GLib.VariantBuilder.new(variant_type_from_string('r')) for i in range(len(args[0])): if format.startswith(')'): raise TypeError('too many arguments for tuple signature') (v, format, _) = self._create(format, args[0][i:]) builder.add_value(v) args = args[1:] if not format.startswith(')'): raise TypeError('tuple type string not closed with )') rest_format = format[1:] # eat the ) return (builder.end(), rest_format, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_dict(self, format, args): """Handle the case where the outermost type of format is a dict."""
builder = None if args is None or not args[0]: # empty value: we need to call _create() to parse the subtype, # and specify the element type precisely rest_format = self._create(format[2:], None)[1] rest_format = self._create(rest_format, None)[1] if not rest_format.startswith('}'): raise TypeError('dictionary type string not closed with }') rest_format = rest_format[1:] # eat the } element_type = format[:len(format) - len(rest_format)] builder = GLib.VariantBuilder.new(variant_type_from_string(element_type)) else: builder = GLib.VariantBuilder.new(variant_type_from_string('a{?*}')) for k, v in args[0].items(): (key_v, rest_format, _) = self._create(format[2:], [k]) (val_v, rest_format, _) = self._create(rest_format, [v]) if not rest_format.startswith('}'): raise TypeError('dictionary type string not closed with }') rest_format = rest_format[1:] # eat the } entry = GLib.VariantBuilder.new(variant_type_from_string('{?*}')) entry.add_value(key_v) entry.add_value(val_v) builder.add_value(entry.end()) if args is not None: args = args[1:] return (builder.end(), rest_format, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_array(self, format, args): """Handle the case where the outermost type of format is an array."""
builder = None if args is None or not args[0]: # empty value: we need to call _create() to parse the subtype, # and specify the element type precisely rest_format = self._create(format[1:], None)[1] element_type = format[:len(format) - len(rest_format)] builder = GLib.VariantBuilder.new(variant_type_from_string(element_type)) else: builder = GLib.VariantBuilder.new(variant_type_from_string('a*')) for i in range(len(args[0])): (v, rest_format, _) = self._create(format[1:], args[0][i:]) builder.add_value(v) if args is not None: args = args[1:] return (builder.end(), rest_format, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unpack(self): """Decompose a GVariant into a native Python object."""
LEAF_ACCESSORS = { 'b': self.get_boolean, 'y': self.get_byte, 'n': self.get_int16, 'q': self.get_uint16, 'i': self.get_int32, 'u': self.get_uint32, 'x': self.get_int64, 't': self.get_uint64, 'h': self.get_handle, 'd': self.get_double, 's': self.get_string, 'o': self.get_string, # object path 'g': self.get_string, # signature } # simple values la = LEAF_ACCESSORS.get(self.get_type_string()) if la: return la() # tuple if self.get_type_string().startswith('('): res = [self.get_child_value(i).unpack() for i in range(self.n_children())] return tuple(res) # dictionary if self.get_type_string().startswith('a{'): res = {} for i in range(self.n_children()): v = self.get_child_value(i) res[v.get_child_value(0).unpack()] = v.get_child_value(1).unpack() return res # array if self.get_type_string().startswith('a'): return [self.get_child_value(i).unpack() for i in range(self.n_children())] # variant (just unbox transparently) if self.get_type_string().startswith('v'): return self.get_variant().unpack() # maybe if self.get_type_string().startswith('m'): m = self.get_maybe() return m.unpack() if m else None raise NotImplementedError('unsupported GVariant type ' + self.get_type_string())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split_signature(klass, signature): """Return a list of the element signatures of the topmost signature tuple. If the signature is not a tuple, it returns one element with the entire signature. If the signature is an empty tuple, the result is []. This is useful for e. g. iterating over method parameters which are passed as a single Variant. """
if signature == '()': return [] if not signature.startswith('('): return [signature] result = [] head = '' tail = signature[1:-1] # eat the surrounding () while tail: c = tail[0] head += c tail = tail[1:] if c in ('m', 'a'): # prefixes, keep collecting continue if c in ('(', '{'): # consume until corresponding )/} level = 1 up = c if up == '(': down = ')' else: down = '}' while level > 0: c = tail[0] head += c tail = tail[1:] if c == up: level += 1 elif c == down: level -= 1 # otherwise we have a simple type result.append(head) head = '' return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_from_memory(cls, data): """Takes bytes and returns a GITypelib, or raises GIError"""
size = len(data) copy = g_memdup(data, size) ptr = cast(copy, POINTER(guint8)) try: with gerror(GIError) as error: return GITypelib._new_from_memory(ptr, size, error) except GIError: free(copy) raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_type(cls, ptr): """Get the subtype class for a pointer"""
# fall back to the base class if unknown return cls.__types.get(lib.g_base_info_get_type(ptr), cls)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_method(info, target_cls, virtual=False, dont_replace=False): """Add a method to the target class"""
# escape before prefixing, like pygobject name = escape_identifier(info.name) if virtual: name = "do_" + name attr = VirtualMethodAttribute(info, target_cls, name) else: attr = MethodAttribute(info, target_cls, name) if dont_replace and hasattr(target_cls, name): return setattr(target_cls, name, attr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def InterfaceAttribute(iface_info): """Creates a GInterface class"""
# Create a new class cls = type(iface_info.name, (InterfaceBase,), dict(_Interface.__dict__)) cls.__module__ = iface_info.namespace # GType cls.__gtype__ = PGType(iface_info.g_type) # Properties cls.props = PropertyAttribute(iface_info) # Signals cls.signals = SignalsAttribute(iface_info) # Add constants for constant in iface_info.get_constants(): constant_name = constant.name attr = ConstantAttribute(constant) setattr(cls, constant_name, attr) # Add methods for method_info in iface_info.get_methods(): add_method(method_info, cls) # VFuncs for vfunc_info in iface_info.get_vfuncs(): add_method(vfunc_info, cls, virtual=True) cls._sigs = {} is_info = iface_info.get_iface_struct() if is_info: iface_struct = import_attribute(is_info.namespace, is_info.name) else: iface_struct = None def get_iface_struct(cls): if not iface_struct: return None ptr = cls.__gtype__._type.default_interface_ref() if not ptr: return None return iface_struct._from_pointer(addressof(ptr.contents)) setattr(cls, "_get_iface_struct", classmethod(get_iface_struct)) return cls
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_class_from_gtype(gtype): """Create a new class for a gtype not in the gir. The caller is responsible for caching etc. """
if gtype.is_a(PGType.from_name("GObject")): parent = gtype.parent.pytype if parent is None or parent == PGType.from_name("void"): return interfaces = [i.pytype for i in gtype.interfaces] bases = tuple([parent] + interfaces) cls = type(gtype.name, bases, dict()) cls.__gtype__ = gtype return cls elif gtype.is_a(PGType.from_name("GEnum")): from pgi.enum import GEnumBase return GEnumBase
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ObjectAttribute(obj_info): """Creates a GObject class. It inherits from the base class and all interfaces it implements. """
if obj_info.name == "Object" and obj_info.namespace == "GObject": cls = Object else: # Get the parent class parent_obj = obj_info.get_parent() if parent_obj: attr = import_attribute(parent_obj.namespace, parent_obj.name) bases = (attr,) else: bases = (object,) # Get all object interfaces ifaces = [] for interface in obj_info.get_interfaces(): attr = import_attribute(interface.namespace, interface.name) # only add interfaces if the base classes don't have it for base in bases: if attr in base.__mro__: break else: ifaces.append(attr) # Combine them to a base class list if ifaces: bases = tuple(list(bases) + ifaces) # Create a new class cls = type(obj_info.name, bases, dict()) cls.__module__ = obj_info.namespace # Set root to unowned= False and InitiallyUnowned=True if obj_info.namespace == "GObject": if obj_info.name == "InitiallyUnowned": cls._unowned = True elif obj_info.name == "Object": cls._unowned = False # GType cls.__gtype__ = PGType(obj_info.g_type) if not obj_info.fundamental: # Constructor cache cls._constructors = {} # Properties setattr(cls, PROPS_NAME, PropertyAttribute(obj_info)) # Signals cls.signals = SignalsAttribute(obj_info) # Signals cls.__sigs__ = {} for sig_info in obj_info.get_signals(): signal_name = sig_info.name cls.__sigs__[signal_name] = sig_info # Add constants for constant in obj_info.get_constants(): constant_name = constant.name attr = ConstantAttribute(constant) setattr(cls, constant_name, attr) # Fields for field in obj_info.get_fields(): field_name = escape_identifier(field.name) attr = FieldAttribute(field_name, field) setattr(cls, field_name, attr) # Add methods for method_info in obj_info.get_methods(): # we implement most of the base object ourself add_method(method_info, cls, dont_replace=cls is Object) # VFuncs for vfunc_info in obj_info.get_vfuncs(): add_method(vfunc_info, cls, virtual=True) cs_info = obj_info.get_class_struct() if cs_info: class_struct = import_attribute(cs_info.namespace, cs_info.name) else: class_struct = None # XXX ^ 2 def get_class_struct(cls, type_=None): """Returns the class struct casted to the passed type""" if type_ is None: type_ = class_struct if type_ is None: return None ptr = cls.__gtype__._type.class_ref() return type_._from_pointer(ptr) setattr(cls, "_get_class_struct", classmethod(get_class_struct)) return cls