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 store(self): """ Store and return packages for upgrading """
data = repo_data(self.PACKAGES_TXT, "slack", self.flag) black = BlackList().packages(pkgs=data[0], repo="slack") for name, loc, comp, uncomp in zip(data[0], data[1], data[2], data[3]): status(0.0003) repo_pkg_name = split_package(name)[0] if (not os.path.isfi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kernel(self): """ Check if kernel upgraded if true then reinstall "lilo" """
for core in self.upgrade_all: if "kernel" in core: if self.meta.default_answer in ["y", "Y"]: answer = self.meta.default_answer else: print("") self.msg.template(78) print("| {0}*** HIGHL...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def slackpkg_update(self): """This replace slackpkg ChangeLog.txt file with new from Slackware official mirrors after update distribution. """
NEW_ChangeLog_txt = URL(mirrors("ChangeLog.txt", "")).reading() if os.path.isfile(self.meta.slackpkg_lib_path + "ChangeLog.txt.old"): os.remove(self.meta.slackpkg_lib_path + "ChangeLog.txt.old") if os.path.isfile(self.meta.slackpkg_lib_path + "ChangeLog.txt"): shutil.cop...
<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_lists(self): """Update packages list and ChangeLog.txt file after upgrade distribution """
print("{0}Update the package lists ?{1}".format( self.meta.color["GREEN"], self.meta.color["ENDC"])) print("=" * 79) if self.msg.answer() in ["y", "Y"]: Update().repository(["slack"])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_head(path, log_file, log_time): """ write headers to log file """
with open(path + log_file, "w") as log: log.write("#" * 79 + "\n\n") log.write("File : " + log_file + "\n") log.write("Path : " + path + "\n") log.write("Date : " + time.strftime("%d/%m/%Y") + "\n") log.write("Time : " + log_time + "\n\n") log.write("#" * 79 + "\n\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 log_end(path, log_file, sum_time): """ append END tag to a log file """
with open(path + log_file, "a") as log: log.seek(2) log.write("#" * 79 + "\n\n") log.write("Time : " + time.strftime("%H:%M:%S") + "\n") log.write("Total build time : {0}\n".format(sum_time)) log.write(" " * 38 + "E N D\n\n") log.write("#" * 79 + "\n\n") log....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_time(start_time): """ Calculate build time per package """
diff_time = round(time.time() - start_time, 2) if diff_time <= 59.99: sum_time = str(diff_time) + " Sec" elif diff_time > 59.99 and diff_time <= 3599.99: sum_time = round(diff_time / 60, 2) sum_time_list = re.findall(r"\d+", str(sum_time)) sum_time = ("{0} Min {1} Sec".forma...
<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_md5_dict(self): """Create md5 dictionary per source """
self.sbo_md5 = {} md5_lists = SBoGrep(self.prgnam).checksum() for src, md5 in zip(self.sources, md5_lists): self.sbo_md5[src] = md5
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _makeflags(self): """Set variable MAKEFLAGS with the numbers of processors """
if self.meta.makeflags in ["on", "ON"]: cpus = multiprocessing.cpu_count() os.environ["MAKEFLAGS"] = "-j{0}".format(cpus)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pass_variable(self): """Return enviroment variables """
pass_var = [] for var in os.environ.keys(): expVAR = var.split("_") if expVAR[0] == self.prgnam.upper() and expVAR[1] != "PATH": pass_var.append("{0}={1}".format(expVAR[1], os.environ[var])) return pass_var
<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_sbo_tar_gz(self): """Delete slackbuild tar.gz file after untar """
if not self.auto and os.path.isfile(self.meta.build_path + self.script): os.remove(self.meta.build_path + self.script)
<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_dir(self): """Delete old folder if exists before start build """
if not self.auto and os.path.isdir(self.meta.build_path + self.prgnam): shutil.rmtree(self.meta.build_path + self.prgnam)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listed(self): """Print blacklist packages """
print("\nPackages in the blacklist:\n") for black in self.get_black(): if black: print("{0}{1}{2}".format(self.meta.color["GREEN"], black, self.meta.color["ENDC"])) self.quit = True if self.quit: pr...
<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, pkgs): """Add blacklist packages if not exist """
blacklist = self.get_black() pkgs = set(pkgs) print("\nAdd packages in the blacklist:\n") with open(self.blackfile, "a") as black_conf: for pkg in pkgs: if pkg not in blacklist: print("{0}{1}{2}".format(self.meta.color["GREEN"], pkg, ...
<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, pkgs): """Remove packages from blacklist """
print("\nRemove packages from the blacklist:\n") with open(self.blackfile, "w") as remove: for line in self.black_conf.splitlines(): if line not in pkgs: remove.write(line + "\n") else: print("{0}{1}{2}".format(self.met...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def packages(self, pkgs, repo): """Return packages in blacklist or by repository """
self.black = [] for bl in self.get_black(): pr = bl.split(":") for pkg in pkgs: self.__priority(pr, repo, pkg) self.__blackpkg(bl, repo, pkg) return self.black
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __priority(self, pr, repo, pkg): """Add packages in blacklist by priority """
if (pr[0] == repo and pr[1].startswith("*") and pr[1].endswith("*")): if pr[1][1:-1] in pkg: self.black.append(self.__add(repo, pkg)) elif pr[0] == repo and pr[1].endswith("*"): if pkg.startswith(pr[1][:-1]): self.black.append(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 __blackpkg(self, bl, repo, pkg): """Add packages in blacklist """
if bl.startswith("*") and bl.endswith("*"): if bl[1:-1] in pkg: self.black.append(self.__add(repo, pkg)) elif bl.endswith("*"): if pkg.startswith(bl[:-1]): self.black.append(self.__add(repo, pkg)) elif bl.startswith("*"): if pk...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def view(self): """Print package description by repository """
print("") # new line at start description, count = "", 0 if self.repo == "sbo": description = SBoGrep(self.name).description() else: PACKAGES_TXT = Utils().read_file(self.lib) for line in PACKAGES_TXT.splitlines(): if line.startswith...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """Download files using wget or other downloader. Optional curl, aria2c and httpie """
dwn_count = 1 self._directory_prefix() for dwn in self.url: # get file name from url and fix passing char '+' self.file_name = dwn.split("/")[-1].replace("%2B", "+") if dwn.startswith("file:///"): source_dir = dwn[7:-7].replace(slack_ver(), "...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_tarfile(self, output_filename, source_dir): """Create .tar.gz file """
with tarfile.open(output_filename, "w:gz") as tar: tar.add(source_dir, arcname=os.path.basename(source_dir))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _directory_prefix(self): """Downloader options for specific directory """
if self.downder == "wget": self.dir_prefix = "--directory-prefix=" elif self.downder == "aria2c": self.dir_prefix = "--dir="
<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_downloaded(self): """Check if file downloaded """
if not os.path.isfile(self.path + self.file_name): print("") self.msg.template(78) print("| Download '{0}' file [ {1}FAILED{2} ]".format( self.file_name, self.meta.color["RED"], self.meta.color["ENDC"])) self.msg.template(78) ...
<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_certificate(self): """Check for certificates options for wget """
if (self.file_name.startswith("jdk-") and self.repo == "sbo" and self.downder == "wget"): certificate = (' --no-check-certificate --header="Cookie: ' 'oraclelicense=accept-securebackup-cookie"') self.msg.template(78) print("| '{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 slack_package(prgnam): """Return maximum binary Slackware package from output directory """
binaries, cache, binary = [], "0", "" for pkg in find_package(prgnam, _meta_.output): if pkg.startswith(prgnam) and pkg[:-4].endswith("_SBo"): binaries.append(pkg) for bins in binaries: if LooseVersion(bins) > LooseVersion(cache): binary = bins cache = bi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def server(self): """Returns the size of remote files """
try: tar = urllib2.urlopen(self.registry) meta = tar.info() return int(meta.getheaders("Content-Length")[0]) except (urllib2.URLError, IndexError): return " "
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def units(comp_sum, uncomp_sum): """Calculate package size """
compressed = round((sum(map(float, comp_sum)) / 1024), 2) uncompressed = round((sum(map(float, uncomp_sum)) / 1024), 2) comp_unit = uncomp_unit = "Mb" if compressed > 1024: compressed = round((compressed / 1024), 2) comp_unit = "Gb" if uncompressed > 1024: uncompressed = rou...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def status(sec): """Toolbar progressive status """
if _meta_.prg_bar in ["on", "ON"]: syms = ["|", "/", "-", "\\"] for sym in syms: sys.stdout.write("\b{0}{1}{2}".format(_meta_.color["GREY"], sym, _meta_.color["ENDC"])) sys.stdout.flush() time.sleep(float(sec))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def continue_to_install(self): """Continue to install ? """
if (self.count_uni > 0 or self.count_upg > 0 or "--download-only" in self.flag or "--rebuild" in self.flag): if self.master_packages and self.msg.answer() in ["y", "Y"]: installs, upgraded = self.build_install() if "--download-only" in self.flag: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_masters(self): """Clear master slackbuilds if already exist in dependencies or if added to install two or more times """
self.master_packages = Utils().remove_dbs(self.master_packages) for mas in self.master_packages: if mas in self.dependencies: self.master_packages.remove(mas)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def matching(self): """Return found matching SBo packages """
for sbo in self.package_not_found: for pkg in self.data: if sbo in pkg and pkg not in self.blacklist: self.package_found.append(pkg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sbo_version_source(self, slackbuilds): """Create sbo name with version """
sbo_versions, sources = [], [] for sbo in slackbuilds: status(0.02) sbo_ver = "{0}-{1}".format(sbo, SBoGrep(sbo).version()) sbo_versions.append(sbo_ver) sources.append(SBoGrep(sbo).source()) return [sbo_versions, sources]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def one_for_all(self, deps): """Because there are dependencies that depend on other dependencies are created lists into other lists. Thus creating this loop crea...
requires, dependencies = [], [] deps.reverse() # Inverting the list brings the # dependencies in order to be installed. requires = Utils().dimensional_list(deps) dependencies = Utils().remove_dbs(requires) return dependencies
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tag(self, sbo): """Tag with color green if package already installed, color yellow for packages to upgrade and color red if not installed. """
# split sbo name with version and get name sbo_name = "-".join(sbo.split("-")[:-1]) find = GetFromInstalled(sbo_name).name() if find_package(sbo, self.meta.pkg_path): paint = self.meta.color["GREEN"] self.count_ins += 1 if "--rebuild" in self.flag: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_arch(self, src): """Looks if sources unsupported or untested from arch else select arch. """
arch = self.arch for item in self.unst: if item in src: arch = item return arch
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filenames(self, sources): """Return filenames from sources links """
filename = [] for src in sources: filename.append(src.split("/")[-1]) return filename
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def not_downgrade(self, prgnam): """Don't downgrade packages if sbo version is lower than installed"""
name = "-".join(prgnam.split("-")[:-1]) sbo_ver = prgnam.split("-")[-1] ins_ver = GetFromInstalled(name).version()[1:] if not ins_ver: ins_ver = "0" if LooseVersion(sbo_ver) < LooseVersion(ins_ver): self.msg.template(78) print("| Package {0} 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 sbosrcarsh(self, prgnam, sbo_link, src_link): """Alternative repository for sbo sources"""
sources = [] name = "-".join(prgnam.split("-")[:-1]) category = "{0}/{1}/".format(sbo_link.split("/")[-2], name) for link in src_link: source = link.split("/")[-1] sources.append("{0}{1}{2}".format(self.meta.sbosrcarch_link, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prog_version(): """Print version, license and email """
print("Version : {0}\n" "Licence : {1}\n" "Email : {2}\n" "Maintainer: {3}".format(_meta_.__version__, _meta_.__license__, _meta_.__email__, _meta_.__maintainer__))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pkg_not_found(self, bol, pkg, message, eol): """Print message when package not found """
print("{0}No such package {1}: {2}{3}".format(bol, pkg, message, eol))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_FAILED(self, prgnam): """Print error message if build failed """
self.template(78) print("| Some error on the package {0} [ {1}FAILED{2} ]".format( prgnam, self.meta.color["RED"], self.meta.color["ENDC"])) self.template(78) print("| See the log file in '{0}/var/log/slpkg/sbo/build_logs{1}' " "directory or read the README fil...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def security_pkg(self, pkg): """Warning message for some special reasons """
print("") self.template(78) print("| {0}{1}*** WARNING ***{2}").format( " " * 27, self.meta.color["RED"], self.meta.color["ENDC"]) self.template(78) print("| Before proceed with the package '{0}' will you must read\n" "| the README file. You can use the...
<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(self, install, upgrade): """Reference list with packages installed and upgraded """
self.template(78) print("| Total {0} {1} installed and {2} {3} upgraded".format( len(install), self.pkg(len(install)), len(upgrade), self.pkg(len(upgrade)))) self.template(78) for installed, upgraded in itertools.izip_longest(install, upgrade): if upg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def matching(self, packages): """Message for matching packages """
print("\nNot found package with the name [ {0}{1}{2} ]. " "Matching packages:\nNOTE: Not dependenc" "ies are resolved\n".format(self.meta.color["CYAN"], "".join(packages), self.meta.color["ENDC"]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mirrors(name, location): """ Select Slackware official mirror packages based architecture and version. """
rel = _meta_.slack_rel ver = slack_ver() repo = Repo().slack() if _meta_.arch == "x86_64": if rel == "stable": http = repo + "slackware64-{0}/{1}{2}".format(ver, location, name) else: http = repo + "slackware64-{0}/{1}{2}".format(rel, location, name) elif _me...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select(self): """Select Slackware command """
print("\nDetected Slackware binary package for installation:\n") for pkg in self.packages: print(" " + pkg.split("/")[-1]) print("") self.msg.template(78) print("| Choose a Slackware command:") self.msg.template(78) for com in sorted(self.commands): ...
<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): """Execute Slackware command """
if self.choice in self.commands.keys(): if self.choice == "i": PackageManager(self.packages).install("") elif self.choice in ["u", "r"]: PackageManager(self.packages).upgrade( self.commands[self.choice][11:])
<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_enabled(self): """Read enable repositories """
for line in self.conf.splitlines(): line = line.lstrip() if self.tag in line: self.tag_line = True if (line and self.tag_line and not line.startswith("#") and self.tag not in line): self.enabled.append(line) self.ta...
<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_disabled(self): """Read disable repositories """
for line in self.conf.splitlines(): line = line.lstrip() if self.tag in line: self.tag_line = True if self.tag_line and line.startswith("#"): line = "".join(line.split("#")).strip() self.disabled.append(line) self.tag_l...
<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_repos(self): """Update repositories.conf file with enabled or disabled repositories """
with open("{0}{1}".format(self.meta.conf_path, self.repositories_conf), "w") as new_conf: for line in self.conf.splitlines(): line = line.lstrip() if self.tag in line: self.tag_line = True if 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 reference(self): """Reference enable repositories """
total_enabled = ", ".join(self.selected) if len(total_enabled) < 1: total_enabled = ("{0}Are you crazy? This is a package " "manager for packages :p{1}".format( self.meta.color["RED"], self.meta.c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sbo_search_pkg(name): """Search for package path from SLACKBUILDS.TXT file and return url """
repo = Repo().default_repository()["sbo"] sbo_url = "{0}{1}/".format(repo, slack_ver()) SLACKBUILDS_TXT = Utils().read_file( _meta_.lib_path + "sbo_repo/SLACKBUILDS.TXT") for line in SLACKBUILDS_TXT.splitlines(): if line.startswith("SLACKBUILD LOCATION"): sbo_name = (line[23...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def router_main(self): ''' Main method for router; we stay in a loop in this method, receiving packets until the end of time. ''' while True: gotpkt = True try: timestamp,dev,pkt = self.net.recv_packet(timeout=1.0) except No...
<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_source_files(input_path, excludes): """ Get a list of filenames for all Java source files within the given directory. """
java_files = [] input_path = os.path.normpath(os.path.abspath(input_path)) for dirpath, dirnames, filenames in os.walk(input_path): if is_excluded(dirpath, excludes): del dirnames[:] continue for filename in filenames: if filename.endswith(".java"): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def from_bytes(rawbytes): ''' Takes a byte string as a parameter and returns a list of IPOption objects. ''' ipopts = IPOptionList() i = 0 while i < len(rawbytes): opttype = rawbytes[i] optcopied = opttype >> 7 # high order 1 bit ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def to_bytes(self): ''' Takes a list of IPOption objects and returns a packed byte string of options, appropriately padded if necessary. ''' raw = b'' if not self._options: return raw for ipopt in self._options: raw += ipopt.to_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 _start_usercode(entryfunction, netobj, codeargdict): ''' figure out how to correctly start the user code. warn if args are passed on the command line, but the code doesn't accept them. ''' # p22, python3 lang ref numargs = entryfunction.__code__.co_argcount takenet = numargs >= 1 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def interface_by_name(self, name): ''' Given a device name, return the corresponding interface object ''' if name in self._devinfo: return self._devinfo[name] raise KeyError("No device named {}".format(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 interface_by_ipaddr(self, ipaddr): ''' Given an IP address, return the interface that 'owns' this address ''' ipaddr = IPAddr(ipaddr) for devname,iface in self._devinfo.items(): if iface.ipaddr == ipaddr: return iface raise KeyError("No dev...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def interface_by_macaddr(self, macaddr): ''' Given a MAC address, return the interface that 'owns' this address ''' macaddr = EthAddr(macaddr) for devname,iface in self._devinfo.items(): if iface.ethaddr == macaddr: return iface raise KeyError(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def from_bytes(rawbytes): ''' Takes a byte string as a parameter and returns a list of ICMPv6Option objects. ''' icmpv6popts = ICMPv6OptionList() i = 0 while i < len(rawbytes): opttype = rawbytes[i] optnum = ICMPv6OptionNumber(opttype) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def to_bytes(self): ''' Takes a list of ICMPv6Option objects and returns a packed byte string of options, appropriately padded if necessary. ''' raw = b'' if not self._options: return raw for icmpv6popt in self._options: raw += icmpv6popt.t...
<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_bitmap(bitmap, xenum): ''' Given an integer bitmap and an enumerated type, build a set that includes zero or more enumerated type values corresponding to the bitmap. ''' unpacked = set() for enval in xenum: if enval.value & bitmap == enval.value: unpacked.add(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _make_wildcard_attr_map(): ''' Create a dictionary that maps an attribute name in OpenflowMatch with a non-prefix-related wildcard bit from the above OpenflowWildcard enumeration. ''' _xmap = {} for wc in OpenflowWildcard: if not wc.name.endswith('All') and \ not wc.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 matches_packet(self, pkt): ''' Return True if the given packet matches this match object. ''' match = [] wildbits = _make_bitmap(self._wildcards) for mf,pkttuple in OpenflowMatch._match_field_to_packet.items(): mf = "_{}".format(mf) # if the a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def build_from_packet(pkt): ''' Build and return a new OpenflowMatch object based on the packet object passed as a parameter. ''' m = OpenflowMatch() for mf,pkttuple in OpenflowMatch._match_field_to_packet.items(): for pktcls,field in pkttuple: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pre_serialize(self, raw, pkt, i): ''' Set length of the header based on ''' self.length = len(raw) + OpenflowHeader._MINLEN
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def discoverdevs(self): ''' Find all the pcap-eligible devices on the local system. ''' if len(self._interfaces): raise PcapException("Device discovery should only be done once.") ppintf = self._ffi.new("pcap_if_t * *") errbuf = self._ffi.new("cha...
<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_bpf_filter_on_all_devices(filterstr): ''' Long method name, but self-explanatory. Set the bpf filter on all devices that have been opened. ''' with PcapLiveDevice._lock: for dev in PcapLiveDevice._OpenDevices.values(): _PcapFfi.instance()._set...
<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_ip_arp_request(srchw, srcip, targetip): ''' Create and return a packet containing an Ethernet header and ARP header. ''' ether = Ethernet() ether.src = srchw ether.dst = SpecialEthAddr.ETHER_BROADCAST.value ether.ethertype = EtherType.ARP arp = Arp() arp.operation = Ar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def setup_logging(debug, logfile=None): ''' Setup logging format and log level. ''' if debug: level = logging.DEBUG else: level = logging.INFO if logfile is not None: logging.basicConfig(format="%(asctime)s %(levelname)8s %(message)s", datefmt="%H:%M:%S %Y/%m/%d", level=l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _spawn_threads(self): ''' Internal method. Creates threads to handle low-level network receive. ''' for devname,pdev in self._pcaps.items(): t = threading.Thread(target=LLNetReal._low_level_dispatch, args=(pdev, devname, self._pktqueue)) t.start() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _make_pcaps(self): ''' Internal method. Create libpcap devices for every network interface we care about and set them in non-blocking mode. ''' self._pcaps = {} for devname,intf in self._devinfo.items(): if intf.iftype == InterfaceType.Loopback: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _sig_handler(self, signum, stack): ''' Handle process INT signal. ''' log_debug("Got SIGINT.") if signum == signal.SIGINT: LLNetReal.running = False if self._pktqueue.qsize() == 0: # put dummy pkt in queue to unblock a ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _low_level_dispatch(pcapdev, devname, pktqueue): ''' Thread entrypoint for doing low-level receive and dispatch for a single pcap device. ''' while LLNetReal.running: # a non-zero timeout value is ok here; this is an # independent thread that handles i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __output_see(self, see): """ Convert the argument to a @see tag to rest """
if see.startswith('<a href'): # HTML link -- <a href="...">...</a> return self.__html_to_rst(see) elif '"' in see: # Plain text return see else: # Type reference (default) return ':java:ref:`%s`' % (see.replace('#', '.').r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile_type_document(self, imports_block, package, name, declaration): """ Compile a complete document, documenting a type and its members """
outer_type = name.rpartition('.')[0] document = util.Document() document.add(imports_block) document.add_heading(name, '=') method_summary = util.StringBuilder() document.add_object(method_summary) package_dir = util.Directive('java:package', package) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile(self, ast): """ Compile autodocs for the given Java syntax tree. Documents will be returned documenting each separate type. """
documents = {} imports = util.StringBuilder() for imp in ast.imports: if imp.static or imp.wildcard: continue package_parts = [] cls_parts = [] for part in imp.path.split('.'): if cls_parts or part[0].isupper():...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checksum (data, start = 0, skip_word = None): """ Calculate standard internet checksum over data starting at start'th byte skip_word: If specified, it's the ...
if len(data) % 2 != 0: arr = array.array('H', data[:-1]) else: arr = array.array('H', data) if skip_word is not None: for i in range(0, len(arr)): if i == skip_word: continue start += arr[i] else: for i in range(0, len(arr)): start += arr[i] if len(data) % 2 != 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 javadoc_role(name, rawtext, text, lineno, inliner, options={}, content=[]): """ Role for linking to external Javadoc """
has_explicit_title, title, target = split_explicit_title(text) title = utils.unescape(title) target = utils.unescape(target) if not has_explicit_title: target = target.lstrip('~') if title[0] == '~': title = title[1:].rpartition('.')[2] app = inliner.document.setting...
<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, port, pkt): ''' Add new input port + packet to buffer. ''' id = len(self._buffer) + 1 if id > self._buffsize: raise FullBuffer() self._buffer[id] = (port, deepcopy(pkt)) return 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 _handle_datapath(self, inport, packet): ''' Handle single packet on the data plane. ''' inport = self._switchyard_net.port_by_name(inport) portnum = inport.ifnum log_info("Processing packet: {}->{}".format(portnum, packet)) actions = None for tnum,t i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def to_bytes(self): ''' Return packed byte representation of the TCP header. ''' header = self._make_header(self._checksum) return header + self._options.to_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 infer_netmask (addr): """ Uses network classes to guess the number of network bits """
addr = int(addr) if addr == 0: # Special case -- default network return 32-32 # all bits wildcarded if (addr & (1 << 31)) == 0: # Class A return 32-24 if (addr & (3 << 30)) == 2 << 30: # Class B return 32-16 if (addr & (7 << 29)) == 6 << 29: # Class C return 32-8 if (addr & ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isBridgeFiltered (self): """ Checks if address is an IEEE 802.1D MAC Bridge Filtered MAC Group Address This range is 01-80-C2-00-00-00 to 01-80-C2-00-00-0F. ...
return ((self.__value[0] == 0x01) and (self.__value[1] == 0x80) and (self.__value[2] == 0xC2) and (self.__value[3] == 0x00) and (self.__value[4] == 0x00) and (self.__value[5] <= 0x0F))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def toStr (self, separator = ':'): """ Returns the address as string consisting of 12 hex chars separated by separator. """
return separator.join(('{:02x}'.format(x) for x in self.__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 to_bytes(self): ''' Return packed byte representation of the Ethernet header. ''' return struct.pack(Ethernet._PACKFMT, self._dst.packed, self._src.packed, self._ethertype.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 _init(): ''' Internal switchyard static initialization method. ''' if ApplicationLayer._isinit: return ApplicationLayer._isinit = True ApplicationLayer._to_app = {} ApplicationLayer._from_app = Queue()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def recv_from_app(timeout=_default_timeout): ''' Called by a network stack implementer to receive application-layer data for sending on to a remote location. Can optionally take a timeout value. If no data are available, raises NoPackets exception. Returns a 2-tuple:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def send_to_app(proto, local_addr, remote_addr, data): ''' Called by a network stack implementer to push application-layer data "up" from the stack. Arguments are protocol number, local_addr (a 2-tuple of IP address and port), remote_addr (a 2-tuple of IP address and port), and ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _registry_update(s, oldid): ''' Internal method used to update an existing socket registry when the socket is re-bound to a different local port number. Requires the socket object and old sockid. Returns None. ''' with _lock: sock_queue = ApplicationLaye...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _unregister_socket(s): ''' Internal method used to remove the socket from AppLayer registry. Warns if the "upward" socket queue has any left-over data. ''' with _lock: sock_queue = ApplicationLayer._to_app.pop(s._sockid()) if not sock_queue.empty(): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def bind(self, address): ''' Alter the local address with which this socket is associated. The address parameter is a 2-tuple consisting of an IP address and port number. NB: this method fails and returns -1 if the requested port to bind to is already in use but does *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 recv(self, buffersize, flags=0): ''' Receive data on the socket. The buffersize and flags arguments are currently ignored. Only returns the data. ''' _,_,data = self._recv(buffersize) return 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 settimeout(self, timeout): ''' Set the timeout value for this socket. ''' if timeout is None: self._block = True elif float(timeout) == 0.0: self._block = False else: self._timeout = float(timeout) self._block = 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 to_bytes(self): ''' Return packed byte representation of the ARP header. ''' return struct.pack(Arp._PACKFMT, self._hwtype.value, self._prototype.value, self._hwaddrlen, self._protoaddrlen, self._operation.value, self._senderhwaddr.packed, self._senderprotoaddr.packed, self._targethw...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process_table_cells(self, table): """ Compile all the table cells. Returns a list of rows. The rows may have different lengths because of column spans. """
rows = [] for i, tr in enumerate(table.find_all('tr')): row = [] for c in tr.contents: cell_type = getattr(c, 'name', None) if cell_type not in ('td', 'th'): continue rowspan = int(c.attrs.get('rowspan', 1)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def import_or_die(module_name, entrypoint_names): ''' Import user code; return reference to usercode function. (str) -> function reference ''' log_debug("Importing {}".format(module_name)) module_name = os.path.abspath(module_name) if module_name.endswith('.py'): module_name,ext = 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 _runcmd(progargs, stdinput=None): ''' Run the command progargs with optional input to be fed in to stdin. ''' stdin = None if stdinput is not None: assert(isinstance(stdinput, list)) stdin=PIPE err = 0 output = b'' log_debug("Calling {} with input {}".format(' '.join...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def block(self): ''' pfctl -a switchyard -f- < rules.txt pfctl -a switchyard -F rules pfctl -t switchyard -F r ''' st,output = _runcmd("/sbin/pfctl -aswitchyard -f -", self._rules) log_debug("Installing rules: {}".format(output))