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 load_schema(ldif_file): """ Load a schema from the given file into the SamDB """
samdb = samdb_connect() dn = samdb.domain_dn() samdb.transaction_start() try: setup_add_ldif(samdb, ldif_file, { "DOMAINDN": dn, }) except: samdb.transaction_cancel() raise samdb.transaction_commit()
<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_child(self, child): """ Add a child node """
if not isinstance(child, DependencyNode): raise TypeError('"child" must be a DependencyNode') self._children.append(child)
<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_children(self, children): """ Add multiple children """
if not isinstance(children, list): raise TypeError('"children" must be a list') for child in children: self.add_child(child)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def head_values(self): """ Return set of the head values """
values = set() for head in self._heads: values.add(head.value) return values
<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_head(self, head): """ Add head Node """
if not isinstance(head, DependencyNode): raise TypeError('"head" must be a DependencyNode') self._heads.append(head)
<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_parser(parser): """Update the parser object for the shell. Arguments: parser: An instance of argparse.ArgumentParser. """
def __stdin(s): if s is None: return None if s == '-': return sys.stdin return open(s, 'r', encoding = 'utf8') parser.add_argument('--root-prompt', metavar = 'STR', default = 'PlayBoy', help = 'the root prompt string') pars...
<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(): """ Internal function to install the module finder. """
global finder if finder is None: finder = ModuleFinder() if finder not in sys.meta_path: sys.meta_path.insert(0, finder)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_module(self, name, path=None): """ Called when an import is made. If there are hooks waiting for this module to be imported then we stop the normal impo...
if name in self.loaded_modules: return None hooks = self.post_load_hooks.get(name, None) if hooks: 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_module(self, name): """ If we get this far, then there are hooks waiting to be called on import of this module. We manually load the module and then run...
self.loaded_modules.append(name) try: __import__(name, {}, {}, []) mod = sys.modules[name] self._run_hooks(name, mod) except: self.loaded_modules.pop() raise return mod
<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_hooks(self, name, module): """ Run all hooks for a module. """
hooks = self.post_load_hooks.pop(name, []) for hook in hooks: hook(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 index_repeatmasker_alignment_by_id(fh, out_fh, vebrose=False): """Build an index for a repeat-masker alignment file by repeat-masker ID."""
def extract_UID(rm_alignment): return rm_alignment.meta[multipleAlignment.RM_ID_KEY] index = IndexedFile(fh, repeat_masker_alignment_iterator, extract_UID) index.write_index(out_fh)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def index_genome_alignment_by_locus(fh, out_fh, verbose=False): """Build an index for a genome alig. using coords in ref genome as keys."""
bound_iter = functools.partial(genome_alignment_iterator, reference_species="hg19", index_friendly=True) hash_func = JustInTimeGenomeAlignmentBlock.build_hash idx = IndexedFile(fh, bound_iter, hash_func) idx.write_index(out_fh, verbose=verbose)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lookup_genome_alignment_index(index_fh, indexed_fh, out_fh=sys.stdout, key=None, verbose=False): """Load a GA index and its indexed file and extract one or m...
# load the genome alignment as a JIT object bound_iter = functools.partial(genome_alignment_iterator, reference_species="hg19", index_friendly=True) hash_func = JustInTimeGenomeAlignmentBlock.build_hash idx = IndexedFile(record_iterator=bound_iter, record_hash_function=hash_fun...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getUI_build_index(prog_name, args): """ build and return a UI object for the 'build' option. :param args: raw arguments to parse """
programName = prog_name long_description = "Build an index for one or more files." short_description = long_description ui = CLI(programName, short_description, long_description) ui.minArgs = 0 ui.maxArgs = -1 ui.addOption(Option(short="o", long="output", argName="filename", descri...
<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_indexer(in_fns, selected_type=None): """Determine which indexer to use based on input files and type option."""
indexer = None if selected_type is not None: indexer = get_indexer_by_filetype(selected_type) else: if len(in_fns) == 0: raise IndexError("reading from stdin, unable to guess input file " + "type, use -t option to set manually.\n") else: extension = set([os.path.spl...
<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_lookup(in_fn, selected_type=None): """Determine which lookup func to use based on inpt files and type option."""
lookup_func = None if selected_type is not None: lookup_func = get_lookup_by_filetype(selected_type) else: extension = os.path.splitext(in_fn)[1] lookup_func = get_lookup_by_file_extension(extension) assert(lookup_func is not None) return lookup_func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_surveys(): # noqa: E501 """list the surveys available List the surveys available # noqa: E501 :rtype: List[Survey] """
pm = PrecisionMapper(login=_LOGIN, password=_PASSWORD) pm.sign_in() surveys = pm.get_surveys() shared_surveys = pm.get_shared_surveys() survey_list = [] for survey in surveys+shared_surveys: survey_obj = Survey( date=survey.date, image_nb=survey.image_nb, locati...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pg2df(res): ''' takes a getlog requests result returns a table as df ''' # parse res soup = BeautifulSoup(res.text) if u'Pas de r\xe9ponse pour cette recherche.' in soup.text: pass # <-- don't pass ! else: params = urlparse.parse_qs(urlparse.urlsplit...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getlog(start, end, deplist=['00'], modlist=['M0'], xlsx=None): ''' batch gets changelogs for cogs ''' # entry point url api = 'http://www.insee.fr/fr/methodes/nomenclatures/cog/recherche_historique.asp' # build payloads if modlist == ['M0']: modlist = ['MA', 'MB', 'MC', 'MD',...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def currency_format(cents): """Format currency with symbol and decimal points. >> currency_format(-600) - $6.00 TODO: Add localization support. """
try: cents = int(cents) except ValueError: return cents negative = (cents < 0) if negative: cents = -1 * cents if cents < 100: dollars = 0 else: dollars = cents / 100 cents = cents % 100 centstr = str(cents) if len(centstr) < 2: ...
<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_website_affected(self, website): """ Tell if the website is affected by the domain change """
if self.domain is None: return True if not self.include_subdomains: return self.domain in website['subdomains'] else: dotted_domain = "." + self.domain for subdomain in website['subdomains']: if subdomain == self.domain or subdomai...
<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_affected_domains(self): """ Return a list of all affected domain and subdomains """
results = set() dotted_domain = ("." + self.domain) if self.domain else None for website in self.websites: for subdomain in website['subdomains']: if self.domain is None or subdomain == self.domain or \ (self.include_subdomains and subdomain.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 secured_apps_copy(self, apps): """ Given the http app list of a website, return what should be in the secure version """
return [[app_name, path] for app_name, path in apps if app_name not in (self.LETSENCRYPT_VERIFY_APP_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 create_le_verification_app(self): """ Create the let's encrypt app to verify the ownership of the domain """
if self.LETSENCRYPT_VERIFY_APP_NAME in self._apps: logger.debug( "The LE verification APP already exists as %s" % self.LETSENCRYPT_VERIFY_APP_NAME ) verification_app = self._apps[self.LETSENCRYPT_VERIFY_APP_NAME] else: logger.info("Creatin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sync_certificates(self, subdomains=None): """ Check all certificates available in acme in the host and sync them with the webfaction certificates """
result = run(".acme.sh/acme.sh --list", quiet=True) logger.info("Syncing Webfaction certificates") for acme_certificate_description in result.split('\n')[1:]: main_domain = acme_certificate_description.split()[0] if subdomains and main_domain not in subdomains: ...
<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_remote_content(filepath): """ A handy wrapper to get a remote file content """
with hide('running'): temp = BytesIO() get(filepath, temp) content = temp.getvalue().decode('utf-8') return content.strip()
<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_main_domain(self, website): """ Given a list of subdomains, return the main domain of them If the subdomain are across multiple domain, then we cannot ha...
subdomains = website['subdomains'] main_domains = set() for sub in subdomains: for d in self._domains: if sub == d or sub.endswith("." + d): main_domains.add(d) if len(main_domains) > 1: logger.error( "The secur...
<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_stroke_freq(Ax, Az, fs_a, nperseg, peak_thresh, stroke_ratio=None): '''Determine stroke frequency to use as a cutoff for filtering Args ---- Ax: numpy.ndarray, shape (n,) x-axis accelermeter data (longitudinal) Ay: numpy.ndarray, shape (n,) x-axis accelermeter data (lateral)...
<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_stroke_glide_indices(A_g_hf, fs_a, J, t_max): '''Get stroke and glide indices from high-pass accelerometer data Args ---- A_g_hf: 1-D ndarray Animal frame triaxial accelerometer matrix at sampling rate fs_a. fs_a: int Number of accelerometer samples per second J: float...
<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_updates( self, display_all_distributions=False, verbose=False ): # pragma: no cover """ When called, get the environment updates and write updates to a C...
if verbose: logging.basicConfig( stream=sys.stdout, level=logging.INFO, format='%(message)s', ) logging.info('Checking installed packages for updates...') updates = self._get_environment_updates( display_al...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def csv_writer(csvfile): """ Get a CSV writer for the version of python that is being run. """
if sys.version_info >= (3,): writer = csv.writer(csvfile, delimiter=',', lineterminator='\n') else: writer = csv.writer(csvfile, delimiter=b',', lineterminator='\n') return writer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_updates_to_csv(self, updates): """ Given a list of updates, write the updates out to the provided CSV file. Args: updates (list): List of Update objec...
with open(self._csv_file_name, 'w') as csvfile: csvwriter = self.csv_writer(csvfile) csvwriter.writerow(CSV_COLUMN_HEADERS) for update in updates: row = [ update.name, update.current_version, update...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_new_config(self, updates): """ Given a list of updates, write the updates out to the provided configuartion file. Args: updates (list): List of Update...
with open(self._new_config, 'w') as config_file: for update in updates: line = '{0}=={1} # The installed version is: {2}\n'.format( update.name, update.new_version, update.current_version ) ...
<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_environment_updates(self, display_all_distributions=False): """ Check all pacakges installed in the environment to see if there are any updates availalb...
updates = [] for distribution in self.pip.get_installed_distributions(): versions = self.get_available_versions(distribution.project_name) max_version = max(versions.keys()) if versions else UNKNOW_NUM update = None distribution_version = self._parse_ve...
<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_available_versions(self, project_name): """ Query PyPI to see if package has any available versions. Args: project_name (str): The name the project on P...
available_versions = self.pypi_client.package_releases(project_name) if not available_versions: available_versions = self.pypi_client.package_releases( project_name.capitalize() ) # ``dict()`` for Python 2.6 syntax. return dict( (sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_version(version): """ Parse a version string. Args: version (str): A string representing a version e.g. '1.9rc2' Returns: tuple: major, minor, patch ...
parsed_version = parse_version(version) return tuple( int(dot_version) for dot_version in parsed_version.base_version.split('.') ) + (parsed_version.is_prerelease,)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def support(self, version): """ return `True` if current python version match version passed. raise a deprecation warning if only PY2 or PY3 is supported as you ...
if not self._known_version(version): warn("unknown feature: %s"%version) return True else: if not self._get_featureset_support(version): warn("You are not supporting %s anymore "%str(version), UserWarning, self.level) if self._alone_versi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _default_warner(self, message, stacklevel=1): """ default warner function use a pending deprecation warning, and correct for the correct stacklevel """
return warnings.warn(message, PendingDeprecationWarning, stacklevel=stacklevel+4)
<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_if_complete(self, url, json_response): """ Check if a request has been completed and return the redirect URL if it has @type url: str @type json_respo...
if '__done' in json_response and isinstance(json_response, list): mr_parts = list(urlparse(url)) mr_query = parse_qs(mr_parts[4]) mr_query['mr'] = '"' + str(json_response[0]) + '"' mr_parts[4] = urlencode(mr_query, True) mr_link = urlunparse(mr_parts)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def entry_index(request, limit=0, template='djournal/entry_index.html'): '''Returns a reponse of a fixed number of entries; all of them, by default. ''' entries = Entry.public.all() if limit > 0: entries = entries[:limit] context = { 'entries': entries, } return render_to_res...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def entry_detail(request, slug, template='djournal/entry_detail.html'): '''Returns a response of an individual entry, for the given slug.''' entry = get_object_or_404(Entry.public, slug=slug) context = { 'entry': entry, } return render_to_response( template, context, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def tagged_entry_index(request, slug, template='djournal/tagged_entry_index.html'): '''Returns a response of all entries tagged with a given tag.''' tag = get_object_or_404(Tag, slug=slug) entries = Entry.public.filter(tags__in=[tag]) context = { 'entries': entries, 'tag': 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 getErrorComponent(result, tag): """get total error contribution for component with specific tag"""
return math.sqrt(sum( (error*2)**2 for (var, error) in result.error_components().items() if var.tag == 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 getEdges(npArr): """get np array of bin edges"""
edges = np.concatenate(([0], npArr[:,0] + npArr[:,2])) return np.array([Decimal(str(i)) for i in edges])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getMaskIndices(mask): """get lower and upper index of mask"""
return [ list(mask).index(True), len(mask) - 1 - list(mask)[::-1].index(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 getCocktailSum(e0, e1, eCocktail, uCocktail): """get the cocktail sum for a given data bin range"""
# get mask and according indices mask = (eCocktail >= e0) & (eCocktail <= e1) # data bin range wider than single cocktail bin if np.any(mask): idx = getMaskIndices(mask) # determine coinciding flags eCl, eCu = eCocktail[idx[0]], eCocktail[idx[1]] not_coinc_low, not_coinc_upp = (eCl != e0), (eCu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def break_sandbox(): """Patches sandbox to add match-all regex to sandbox whitelist """
class EvilCM(object): def __enter__(self): return self def __exit__(self, exc_type, exc, tb): import re tb.tb_next.tb_next.tb_next.tb_frame.f_locals[ 'self']._enabled_regexes.append(re.compile('.*')) return True try: impor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self, *args, **kwargs): """Executes the action."""
timeout = kwargs.pop("timeout", -1) run_async = kwargs.pop("run_async", False) self._is_running = True result = None if self._action_lock.acquire(False): self._state = ACTION_PENDING self._action_event = threading.Event() self.spine.send_comma...
<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_interrupt(self, method=None, **kwargs): """ Decorator that turns a function or controller method into an action interrupt. """
def action_wrap(f): action_id = kwargs.get("action_id", f.__name__) name = kwargs.get("name", action_id) if inspect.ismethod(f): # not "." in f.__qualname__: self._interrupt = _ActionInterrupt(f) self._ui_parameters["interrupt_enabled...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _freezer_lookup(freezer_string): """ Translate a string that may be a freezer name into the internal freezer constant :param freezer_string :return: """
sanitized = freezer_string.lower().strip() for freezer in FREEZER.ALL: freezer_instance = freezer() freezer_name = six.text_type(freezer_instance) if freezer_name == six.text_type(sanitized): return freezer else: if sanitized != freezer_string: 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 resolve_freezer(freezer): """ Locate the appropriate freezer given FREEZER or string input from the programmer. :param freezer: FREEZER constant or string fo...
# Set default freezer if there was none if not freezer: return _Default() # Allow character based lookups as well if isinstance(freezer, six.string_types): cls = _freezer_lookup(freezer) return cls() # Allow plain class definition lookups (we instantiate the class) if ...
<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_packages(cls, include_packages): """ Split an iterable of packages into packages that need to be passed through, and those that need to have their dis...
passthrough_includes = set([ six.text_type(package.__name__) for package in include_packages if not hasattr(package, '__file__') ]) package_file_paths = dict([ (six.text_type(os.path.abspath(package.__file__)), six.text_type(package.__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 parse_json_qry(qry_str): """ Parses a json query string into its parts args: qry_str: query string params: variables passed into the string """
def param_analyzer(param_list): rtn_list = [] for param in param_list: parts = param.strip().split("=") try: rtn_list.append(\ JsonQryProcessor[parts[0].strip().lower()](parts[1])) except IndexError: rtn_li...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json_qry(dataset, qry_str, params={}): """ Takes a json query string and returns the results args: dataset: RdfDataset to query against qry_str: query string...
# if qry_str.startswith("$.bf_itemOf[rdf_type=bf_Print].='print',\n"): # pdb.set_trace() if not '$' in qry_str: qry_str = ".".join(['$', qry_str.strip()]) dallor_val = params.get("$", dataset) if isinstance(dallor_val, rdflib.URIRef): dallor_val = Uri(dallor_val) if qry_str....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def readMixedArray(self): """ Read mixed array. @rtype: L{pyamf.MixedArray} """
# TODO: something with the length/strict self.stream.read_ulong() # length obj = pyamf.MixedArray() self.context.addObject(obj) attrs = self.readObjectAttributes(obj) for key in attrs.keys(): try: key = int(key) except ValueErro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def readTypedObject(self): """ Reads an aliased ActionScript object from the stream and attempts to 'cast' it into a python class. @see: L{pyamf.register_class} ...
class_alias = self.readString() try: alias = self.context.getClassAlias(class_alias) except pyamf.UnknownClassAlias: if self.strict: raise alias = pyamf.TypedObjectClassAlias(class_alias) obj = alias.createInstance(codec=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 readObject(self): """ Reads an anonymous object from the data stream. @rtype: L{ASObject<pyamf.ASObject>} """
obj = pyamf.ASObject() self.context.addObject(obj) obj.update(self.readObjectAttributes(obj)) return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def readReference(self): """ Reads a reference from the data stream. @raise pyamf.ReferenceError: Unknown reference. """
idx = self.stream.read_ushort() o = self.context.getObject(idx) if o is None: raise pyamf.ReferenceError('Unknown reference %d' % (idx,)) return o
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def readDate(self): """ Reads a UTC date from the data stream. Client and servers are responsible for applying their own timezones. Date: C{0x0B T7 T6} .. C{T0 Z...
ms = self.stream.read_double() / 1000.0 self.stream.read_short() # tz # Timezones are ignored d = util.get_datetime(ms) if self.timezone_offset: d = d + self.timezone_offset self.context.addObject(d) return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def readLongString(self): """ Read UTF8 string. """
l = self.stream.read_ulong() bytes = self.stream.read(l) return self.context.getStringForBytes(bytes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def readXML(self): """ Read XML. """
data = self.readLongString() root = xml.fromstring(data) self.context.addObject(root) return root
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeList(self, a): """ Write array to the stream. @param a: The array data to be encoded to the AMF0 data stream. """
if self.writeReference(a) != -1: return self.context.addObject(a) self.writeType(TYPE_ARRAY) self.stream.write_ulong(len(a)) for data in a: self.writeElement(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeNumber(self, n): """ Write number to the data stream . @param n: The number data to be encoded to the AMF0 data stream. """
self.writeType(TYPE_NUMBER) self.stream.write_double(float(n))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeBoolean(self, b): """ Write boolean to the data stream. @param b: The boolean data to be encoded to the AMF0 data stream. """
self.writeType(TYPE_BOOL) if b: self.stream.write_uchar(1) else: self.stream.write_uchar(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 writeBytes(self, s): """ Write a string of bytes to the data stream. """
l = len(s) if l > 0xffff: self.writeType(TYPE_LONGSTRING) else: self.writeType(TYPE_STRING) if l > 0xffff: self.stream.write_ulong(l) else: self.stream.write_ushort(l) self.stream.write(s)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeString(self, u): """ Write a unicode to the data stream. """
s = self.context.getBytesForString(u) self.writeBytes(s)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeReference(self, o): """ Write reference to the data stream. @param o: The reference data to be encoded to the AMF0 datastream. """
idx = self.context.getObjectReference(o) if idx == -1 or idx > 65535: return -1 self.writeType(TYPE_REFERENCE) self.stream.write_ushort(idx) return idx
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeMixedArray(self, o): """ Write mixed array to the data stream. @type o: L{pyamf.MixedArray} """
if self.writeReference(o) != -1: return self.context.addObject(o) self.writeType(TYPE_MIXEDARRAY) # TODO: optimise this # work out the highest integer index try: # list comprehensions to save the day max_index = max([y[0] for y in o....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeObject(self, o): """ Write a Python object to the stream. @param o: The object data to be encoded to the AMF0 data stream. """
if self.writeReference(o) != -1: return self.context.addObject(o) alias = self.context.getClassAlias(o.__class__) alias.compile() if alias.amf3: self.writeAMF3(o) return if alias.anonymous: self.writeType(TYPE_OBJECT) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeDate(self, d): """ Writes a date to the data stream. @type d: Instance of C{datetime.datetime} @param d: The date to be encoded to the AMF0 data stream....
if isinstance(d, datetime.time): raise pyamf.EncodeError('A datetime.time instance was found but ' 'AMF0 has no way to encode time objects. Please use ' 'datetime.datetime instead (got:%r)' % (d,)) # According to the Red5 implementation of AMF0, dates refere...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeXML(self, e): """ Writes an XML instance. """
self.writeType(TYPE_XML) data = xml.tostring(e) if isinstance(data, unicode): data = data.encode('utf-8') self.stream.write_ulong(len(data)) self.stream.write(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def des(clas,keyblob,valblob): "deserialize. translate publish message, basically" raise NotImplementedError("don't use tuples, it breaks __eq__. this function probably isn't used in real life") raw_keyvals=msgpack.loads(keyblob) (namespace,version),keyvals=raw_keyvals[:2],raw_keyvals[2:] if na...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def wait(self): "wait for a message, respecting timeout" data=self.getcon().recv(256) # this can raise socket.timeout if not data: raise PubsubDisco if self.reset: self.reset=False # i.e. ack it. reset is used to tell the wait-thread there was a reconnect (though it's plausible that this neve...
<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_access_token(self): """ get a valid access token """
if self.is_access_token_expired(): if is_debug_enabled(): debug('requesting new access_token') token = get_access_token(username=self.username, password=self.password, client_id=self.client_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 find_lines(self, line): """Find all lines matching a given line."""
for other_line in self.lines: if other_line.match(line): yield other_line
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, line): """Delete all lines matching the given line."""
nb = 0 for block in self.blocks: nb += block.remove(line) return nb
<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(self, key, value): """Add a new value for a key. This differs from __setitem__ in adding a new value instead of updating the list of values, thus avoidin...
self.configfile.add(self.name, key, 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_section(self, name, create=True): """Retrieve a section by name. Create it on first access."""
try: return self.sections[name] except KeyError: if not create: raise section = Section(name) self.sections[name] = section return section
<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_line(self, section, line): """Retrieve all lines compatible with a given line."""
try: section = self._get_section(section, create=False) except KeyError: return [] return section.find_lines(line)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iter_lines(self, section): """Iterate over all lines in a section. This will skip 'header' lines. """
try: section = self._get_section(section, create=False) except KeyError: return for block in section: for line in block: yield line
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enter_block(self, name): """Mark 'entering a block'."""
section = self._get_section(name) block = self.current_block = section.new_block() self.blocks.append(block) return block
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert_line(self, line): """Insert a new line"""
if self.current_block is not None: self.current_block.append(line) else: self.header.append(line)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_line(self, line): """Read one line."""
if line.kind == ConfigLine.KIND_HEADER: self.enter_block(line.header) else: self.insert_line(line)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self, fileobj, name_hint='', parser=None): """Fill from a file-like object."""
self.current_block = None # Reset current block parser = parser or Parser() for line in parser.parse(fileobj, name_hint=name_hint): self.handle_line(line)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_line(self, section, line): """Remove all instances of a line. Returns: int: the number of lines removed """
try: s = self._get_section(section, create=False) except KeyError: # No such section, skip. return 0 return s.remove(line)
<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_or_update(self, section, key, value): """Update the key or, if no previous value existed, add it. Returns: int: Number of updated lines. """
updates = self.update(section, key, value) if updates == 0: self.add(section, key, value) return updates
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cache_set(key, value, timeout=None, refreshed=False): """ Wrapper for ``cache.set``. Stores the cache entry packed with the desired cache expiry time. When t...
if timeout is None: timeout = settings.CACHE_MIDDLEWARE_SECONDS refresh_time = timeout + time() real_timeout = timeout + settings.CACHE_SET_DELAY_SECONDS packed = (value, refresh_time, refreshed) return cache.set(_hashed_key(key), packed, real_timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cache_installed(): """ Returns ``True`` if a cache backend is configured, and the cache middleware classes or subclasses thereof are present. This will be ev...
has_key = bool(getattr(settings, "NEVERCACHE_KEY", "")) def flatten(seqs): return (item for seq in seqs for item in seq) middleware_classes = map(import_string, get_middleware_setting()) middleware_ancestors = set(flatten(map(getmro, middleware_classes))) yacms_cache_middleware_classes =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cache_key_prefix(request): """ Cache key for yacms's cache middleware. Adds the current device and site ID. """
cache_key = "%s.%s.%s." % ( settings.CACHE_MIDDLEWARE_KEY_PREFIX, current_site_id(), device_from_request(request) or "default", ) return _i18n_cache_key_suffix(request, cache_key)
<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_cache_bypass(url): """ Adds the current time to the querystring of the URL to force a cache reload. Used for when a form post redirects back to a page th...
if not cache_installed(): return url hash_str = "" if "#" in url: url, hash_str = url.split("#", 1) hash_str = "#" + hash_str url += "?" if "?" not in url else "&" return url + "t=" + str(time()).replace(".", "") + hash_str
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dbus_get_object(bus_name, object_name): """ Fetches DBUS proxy object given the specified parameters. `bus_name` Name of the bus interface. `object_name` Ob...
try: bus = dbus.SessionBus() obj = bus.get_object(bus_name, object_name) return obj except (NameError, dbus.exceptions.DBusException): 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 _dbus_get_interface(bus_name, object_name, interface_name): """ Fetches DBUS interface proxy object given the specified parameters. `bus_name` Name of the bu...
try: obj = _dbus_get_object(bus_name, object_name) if not obj: raise NameError return dbus.Interface(obj, interface_name) except (NameError, dbus.exceptions.DBusException): 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 _pidgin_status(status, message): """ Updates status and message for Pidgin IM application. `status` Status type. `message` Status message. """
try: iface = _dbus_get_interface('im.pidgin.purple.PurpleService', '/im/pidgin/purple/PurpleObject', 'im.pidgin.purple.PurpleInterface') if iface: # create new transient status code = PIDGIN_CODE_MAP[s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _empathy_status(status, message): """ Updates status and message for Empathy IM application. `status` Status type. `message` Status message. """
ACCT_IFACE = 'org.freedesktop.Telepathy.Account' DBUS_PROP_IFACE = 'org.freedesktop.DBus.Properties' ACCT_MAN_IFACE = 'org.freedesktop.Telepathy.AccountManager' ACCT_MAN_PATH = '/org/freedesktop/Telepathy/AccountManager' SP_IFACE = ('org.freedesktop.Telepathy.' 'Connection.Interfac...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _linux_skype_status(status, message): """ Updates status and message for Skype IM application on Linux. `status` Status type. `message` Status message. """
try: iface = _dbus_get_interface('com.Skype.API', '/com/Skype', 'com.Skype.API') if iface: # authenticate if iface.Invoke('NAME focus') != 'OK': msg = 'User denied authorization' ...
<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_status(self, status, message=''): """ Updates the status and message on all supported IM apps. `status` Status type (See ``VALID_STATUSES``). `message` ...
message = message.strip() # fetch away message from provided id if message.startswith(':'): msg_id = message[1:] message = self.messages.get(msg_id, '') message = message.encode('utf-8', 'replace') # attempt to set status for each supported applicatio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_option(self, option, block_name, *values): """ Parse status, end_status, timer_status and status_msg options. """
if option.endswith('status'): status = values[0] if status not in self.VALID_STATUSES: raise ValueError(u'Invalid IM status "{0}"'.format(status)) if len(values) > 2: raise TypeError if option == 'status': option...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GetNumCoresOnHosts(hosts, private_key): """ Returns list of the number of cores for each host requested in hosts. """
results = runner.Runner(host_list=hosts, private_key=private_key, module_name='setup').run() num_cores_list = [] for _, props in results['contacted'].iteritems(): cores = props['ansible_facts']['ansible_processor_cores'] val = 0 try: val = int(cores) except ValueEr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def RunPlaybookOnHosts(playbook_path, hosts, private_key, extra_vars=None): """ Runs the playbook and returns True if it completes successfully on all hosts. """
inventory = ansible_inventory.Inventory(hosts) if not inventory.list_hosts(): raise RuntimeError("Host list is empty.") stats = callbacks.AggregateStats() verbose = 0 playbook_cb = ansible.callbacks.PlaybookCallbacks(verbose=verbose) runner_cb = ansible.callbacks.PlaybookRunnerCallbacks(stats, verbose=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def RunPlaybookOnHost(playbook_path, host, private_key, extra_vars=None): """ Runs the playbook and returns True if it completes successfully on a single host. "...
return RunPlaybookOnHosts(playbook_path, [host], private_key, extra_vars)