text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Delete old folder if exists before start build <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:> Add blacklist packages if not exist <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, self.meta.color["ENDC"])) black_conf.write(pkg + "\n") self.quit = True black_conf.close() if self.quit: print("")
<SYSTEM_TASK:> Remove packages from blacklist <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.meta.color["RED"], line, self.meta.color["ENDC"])) self.quit = True remove.close() if self.quit: print("")
<SYSTEM_TASK:> Return packages in blacklist or by repository <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:> Add packages in blacklist by priority <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.__add(repo, pkg)) elif pr[0] == repo and pr[1].startswith("*"): if pkg.endswith(pr[1][1:]): self.black.append(self.__add(repo, pkg)) elif pr[0] == repo and "*" not in pr[1]: self.black.append(self.__add(repo, pkg))
<SYSTEM_TASK:> Print package description by repository <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(self.name + ":"): description += line[len(self.name) + 2:] + "\n" count += 1 if count == 11: break if description: print("{0}{1}{2}".format(self.COLOR, description, self.meta.color["ENDC"])) else: self.msg.pkg_not_found("", self.name, "No matching", "\n") raise SystemExit(1) if description and self.repo == "sbo": print("")
<SYSTEM_TASK:> Download files using wget or other downloader. <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(), "") self._make_tarfile(self.file_name, source_dir) self._check_certificate() print("\n[{0}/{1}][ {2}Download{3} ] --> {4}\n".format( dwn_count, len(self.url), self.meta.color["GREEN"], self.meta.color["ENDC"], self.file_name)) if self.downder in ["wget"]: subprocess.call("{0} {1} {2}{3} {4}".format( self.downder, self.downder_options, self.dir_prefix, self.path, dwn), shell=True) if self.downder in ["aria2c"]: subprocess.call("{0} {1} {2}{3} {4}".format( self.downder, self.downder_options, self.dir_prefix, self.path[:-1], dwn), shell=True) elif self.downder in ["curl", "http"]: subprocess.call("{0} {1} {2}{3} {4}".format( self.downder, self.downder_options, self.path, self.file_name, dwn), shell=True) self._check_if_downloaded() dwn_count += 1
<SYSTEM_TASK:> Downloader options for specific directory <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:> Return maximum binary Slackware package from output directory <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 = binary if not binary: Msg().build_FAILED(prgnam) raise SystemExit(1) return ["".join(_meta_.output + binary)]
<SYSTEM_TASK:> Returns the size of remote files <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:> Clear master slackbuilds if already exist in dependencies <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:> Return found matching SBo packages <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:> Create sbo name with version <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:> Because there are dependencies that depend on other <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 create one-dimensional list and remove double packages from dependencies. """
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:> Tag with color green if package already installed, <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: self.count_upg += 1 elif sbo_name == find: paint = self.meta.color["YELLOW"] self.count_upg += 1 else: paint = self.meta.color["RED"] self.count_uni += 1 return paint
<SYSTEM_TASK:> Looks if sources unsupported or untested <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:> Don't downgrade packages if sbo version is lower than <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} don't downgrade, " "setting by user".format(name)) self.msg.template(78) return True
<SYSTEM_TASK:> Print version, license and email <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:> Print message when package not found <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:> Print error message if build failed <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 file".format( self.meta.color["CYAN"], self.meta.color["ENDC"])) self.template(78) print("")
<SYSTEM_TASK:> Warning message for some special reasons <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 command " "'slpkg -n {1}'").format(pkg, pkg) self.template(78) print("")
<SYSTEM_TASK:> Reference list with packages installed <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 upgraded: print("| Package {0} upgraded successfully".format(upgraded)) if installed: print("| Package {0} installed successfully".format(installed)) self.template(78) print("")
<SYSTEM_TASK:> Message for matching packages <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:> Select Slackware official mirror packages <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 _meta_.arch.startswith("arm"): if rel == "stable": http = repo + "slackwarearm-{0}/{1}{2}".format(ver, location, name) else: http = repo + "slackwarearm-{0}/{1}{2}".format(rel, location, name) else: if rel == "stable": http = repo + "slackware-{0}/{1}{2}".format(ver, location, name) else: http = repo + "slackware-{0}/{1}{2}".format(rel, location, name) return http
<SYSTEM_TASK:> Execute Slackware command <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:> Read enable repositories <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.tag_line = False
<SYSTEM_TASK:> Update repositories.conf file with enabled or disabled <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.tag_line and line.startswith("#"): repo = "".join(line.split("#")).strip() if repo in self.selected: new_conf.write(line.replace(line, repo + "\n")) continue if (self.tag_line and not line.startswith("#") and line != self.tag): repo = line.strip() if repo not in self.selected: new_conf.write(line.replace(line, "# " + line + "\n")) continue new_conf.write(line + "\n")
<SYSTEM_TASK:> Get a list of filenames for all Java source files within the given <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"): java_files.append(os.path.join(dirpath, filename)) return java_files
<SYSTEM_TASK:> Convert the argument to a @see tag to rest <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('#', '.').replace(' ', ''),)
<SYSTEM_TASK:> Compile a complete document, documenting a type and its members <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) package_dir.add_option('noindex') document.add_object(package_dir) # Add type-level documentation type_dir = self.compile_type(declaration) if outer_type: type_dir.add_option('outertype', outer_type) document.add_object(type_dir) if isinstance(declaration, javalang.tree.EnumDeclaration): enum_constants = list(declaration.body.constants) enum_constants.sort(key=lambda c: c.name) document.add_heading('Enum Constants') for enum_constant in enum_constants: if self.member_headers: document.add_heading(enum_constant.name, '^') c = self.compile_enum_constant(name, enum_constant) c.add_option('outertype', name) document.add_object(c) fields = list(filter(self.filter, declaration.fields)) if fields: document.add_heading('Fields', '-') fields.sort(key=lambda f: f.declarators[0].name) for field in fields: if self.member_headers: document.add_heading(field.declarators[0].name, '^') f = self.compile_field(field) f.add_option('outertype', name) document.add_object(f) constructors = list(filter(self.filter, declaration.constructors)) if constructors: document.add_heading('Constructors', '-') constructors.sort(key=lambda c: c.name) for constructor in constructors: if self.member_headers: document.add_heading(constructor.name, '^') c = self.compile_constructor(constructor) c.add_option('outertype', name) document.add_object(c) methods = list(filter(self.filter, declaration.methods)) if methods: document.add_heading('Methods', '-') methods.sort(key=lambda m: m.name) for method in methods: if self.member_headers: document.add_heading(method.name, '^') m = self.compile_method(method) m.add_option('outertype', name) document.add_object(m) return document
<SYSTEM_TASK:> Compile autodocs for the given Java syntax tree. Documents will be <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(): cls_parts.append(part) else: package_parts.append(part) # If the import's final part wasn't capitalized, # append it to the class parts anyway so sphinx doesn't complain. if cls_parts == []: cls_parts.append(package_parts.pop()) package = '.'.join(package_parts) cls = '.'.join(cls_parts) imports.append(util.Directive('java:import', package + ' ' + cls).build()) import_block = imports.build() if not ast.package: raise ValueError('File must have package declaration') package = ast.package.name type_declarations = [] for path, node in ast.filter(javalang.tree.TypeDeclaration): if not self.filter(node): continue classes = [n.name for n in path if isinstance(n, javalang.tree.TypeDeclaration)] classes.append(node.name) name = '.'.join(classes) type_declarations.append((package, name, node)) for package, name, declaration in type_declarations: full_name = package + '.' + name document = self.compile_type_document(import_block, package, name, declaration) documents[full_name] = (package, name, document.build()) return documents
<SYSTEM_TASK:> Calculate standard internet checksum over data starting at start'th byte <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 word offset of a word in data to "skip" (as if it were zero). The purpose is when data is received data which contains a computed checksum that you are trying to verify -- you want to skip that word since it was zero when the checksum was initially calculated. """
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: start += struct.unpack('H', data[-1:]+b'\x00')[0] # Specify order? start = (start >> 16) + (start & 0xffff) start += (start >> 16) #while start >> 16: # start = (start >> 16) + (start & 0xffff) return ntohs(~start & 0xffff)
<SYSTEM_TASK:> Role for linking to external Javadoc <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.settings.env.app ref = get_javadoc_ref(app, rawtext, target) if not ref: raise ValueError("no Javadoc source found for %s in javadoc_url_map" % (target,)) ref.append(nodes.Text(title, title)) return [ref], []
<SYSTEM_TASK:> Uses network classes to guess the number of network bits <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 & (15 << 28)) == 14 << 28: # Class D (Multicast) return 32-0 # exact match # Must be a Class E (Experimental) return 32-0
<SYSTEM_TASK:> Checks if address is an IEEE 802.1D MAC Bridge Filtered MAC Group Address <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. MAC frames that have a destination MAC address within this range are not relayed by bridges conforming to IEEE 802.1D """
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:> Returns the address as string consisting of 12 hex chars separated <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:> Compile all the table cells. <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)) colspan = int(c.attrs.get('colspan', 1)) contents = self._process_children(c).strip() if cell_type == 'th' and i > 0: contents = self._inline('**', contents) row.append(Cell(cell_type, rowspan, colspan, contents)) rows.append(row) return rows
<SYSTEM_TASK:> Verify token when configuring webhook from facebook dev. <END_TASK> <USER_TASK:> Description: def get(self, request, hook_id): """ Verify token when configuring webhook from facebook dev. MessengerBot.id is used for verification """
try: bot = caching.get_or_set(MessengerBot, hook_id) except MessengerBot.DoesNotExist: logger.warning("Hook id %s not associated to a bot" % hook_id) return Response(status=status.HTTP_404_NOT_FOUND) if request.query_params.get('hub.verify_token') == str(bot.id): return Response(int(request.query_params.get('hub.challenge'))) return Response('Error, wrong validation token')
<SYSTEM_TASK:> This function name was changed in Django 1.10 and removed in 2.0. <END_TASK> <USER_TASK:> Description: def _format_value(self, value): """This function name was changed in Django 1.10 and removed in 2.0."""
# Use renamed format_name() for Django versions >= 1.10. if hasattr(self, 'format_value'): return super(DateTimePicker, self).format_value(value) # Use old _format_name() for Django versions < 1.10. else: return super(DateTimePicker, self)._format_value(value)
<SYSTEM_TASK:> Get the authorization URL for your application, given the application's <END_TASK> <USER_TASK:> Description: def authorize_url(self, client_id, redirect_uri, scope, state=None): """Get the authorization URL for your application, given the application's client_id, redirect_uri, scope, and optional state data."""
params = [ ('client_id', client_id), ('redirect_uri', redirect_uri), ('scope', scope) ] if state: params.append(('state', state)) return "%s?%s" % (CreateSend.oauth_uri, urlencode(params))
<SYSTEM_TASK:> Exchange a provided OAuth code for an OAuth access token, 'expires in' <END_TASK> <USER_TASK:> Description: def exchange_token(self, client_id, client_secret, redirect_uri, code): """Exchange a provided OAuth code for an OAuth access token, 'expires in' value and refresh token."""
params = [ ('grant_type', 'authorization_code'), ('client_id', client_id), ('client_secret', client_secret), ('redirect_uri', redirect_uri), ('code', code), ] response = self._post('', urlencode(params), CreateSend.oauth_token_uri, "application/x-www-form-urlencoded") access_token, expires_in, refresh_token = None, None, None r = json_to_py(response) if hasattr(r, 'error') and hasattr(r, 'error_description'): err = "Error exchanging code for access token: " err += "%s - %s" % (r.error, r.error_description) raise Exception(err) access_token, expires_in, refresh_token = r.access_token, r.expires_in, r.refresh_token return [access_token, expires_in, refresh_token]
<SYSTEM_TASK:> Refresh an OAuth token given a refresh token. <END_TASK> <USER_TASK:> Description: def refresh_token(self): """Refresh an OAuth token given a refresh token."""
if (not self.auth_details or not 'refresh_token' in self.auth_details or not self.auth_details['refresh_token']): raise Exception( "auth_details['refresh_token'] does not contain a refresh token.") refresh_token = self.auth_details['refresh_token'] params = [ ('grant_type', 'refresh_token'), ('refresh_token', refresh_token) ] response = self._post('', urlencode(params), CreateSend.oauth_token_uri, "application/x-www-form-urlencoded") new_access_token, new_expires_in, new_refresh_token = None, None, None r = json_to_py(response) new_access_token, new_expires_in, new_refresh_token = r.access_token, r.expires_in, r.refresh_token self.auth({ 'access_token': new_access_token, 'refresh_token': new_refresh_token}) return [new_access_token, new_expires_in, new_refresh_token]
<SYSTEM_TASK:> Stub a web request for testing. <END_TASK> <USER_TASK:> Description: def stub_request(self, expected_url, filename, status=None, body=None): """Stub a web request for testing."""
self.fake_web = True self.faker = get_faker(expected_url, filename, status, body)
<SYSTEM_TASK:> Gets a person by client ID and email address. <END_TASK> <USER_TASK:> Description: def get(self, client_id=None, email_address=None): """Gets a person by client ID and email address."""
params = {"email": email_address or self.email_address} response = self._get("/clients/%s/people.json" % (client_id or self.client_id), params=params) return json_to_py(response)
<SYSTEM_TASK:> Adds a person to a client. Password is optional and if not supplied, an invitation will be emailed to the person <END_TASK> <USER_TASK:> Description: def add(self, client_id, email_address, name, access_level, password): """Adds a person to a client. Password is optional and if not supplied, an invitation will be emailed to the person"""
body = { "EmailAddress": email_address, "Name": name, "AccessLevel": access_level, "Password": password} response = self._post("/clients/%s/people.json" % client_id, json.dumps(body)) return json_to_py(response)
<SYSTEM_TASK:> Updates the details for a person. Password is optional and is only updated if supplied. <END_TASK> <USER_TASK:> Description: def update(self, new_email_address, name, access_level, password=None): """Updates the details for a person. Password is optional and is only updated if supplied."""
params = {"email": self.email_address} body = { "EmailAddress": new_email_address, "Name": name, "AccessLevel": access_level, "Password": password} response = self._put("/clients/%s/people.json" % self.client_id, body=json.dumps(body), params=params) # Update self.email_address, so this object can continue to be used # reliably self.email_address = new_email_address
<SYSTEM_TASK:> Creates a new campaign for a client. <END_TASK> <USER_TASK:> Description: def create(self, client_id, subject, name, from_name, from_email, reply_to, html_url, text_url, list_ids, segment_ids): """Creates a new campaign for a client. :param client_id: String representing the ID of the client for whom the campaign will be created. :param subject: String representing the subject of the campaign. :param name: String representing the name of the campaign. :param from_name: String representing the from name for the campaign. :param from_email: String representing the from address for the campaign. :param reply_to: String representing the reply-to address for the campaign. :param html_url: String representing the URL for the campaign HTML content. :param text_url: String representing the URL for the campaign text content. Note that text_url is optional and if None or an empty string, text content will be automatically generated from the HTML content. :param list_ids: Array of Strings representing the IDs of the lists to which the campaign will be sent. :param segment_ids: Array of Strings representing the IDs of the segments to which the campaign will be sent. :returns String representing the ID of the newly created campaign. """
body = { "Subject": subject, "Name": name, "FromName": from_name, "FromEmail": from_email, "ReplyTo": reply_to, "HtmlUrl": html_url, "TextUrl": text_url, "ListIDs": list_ids, "SegmentIDs": segment_ids} response = self._post("/campaigns/%s.json" % client_id, json.dumps(body)) self.campaign_id = json_to_py(response) return self.campaign_id
<SYSTEM_TASK:> Creates a new campaign for a client, from a template. <END_TASK> <USER_TASK:> Description: def create_from_template(self, client_id, subject, name, from_name, from_email, reply_to, list_ids, segment_ids, template_id, template_content): """Creates a new campaign for a client, from a template. :param client_id: String representing the ID of the client for whom the campaign will be created. :param subject: String representing the subject of the campaign. :param name: String representing the name of the campaign. :param from_name: String representing the from name for the campaign. :param from_email: String representing the from address for the campaign. :param reply_to: String representing the reply-to address for the campaign. :param list_ids: Array of Strings representing the IDs of the lists to which the campaign will be sent. :param segment_ids: Array of Strings representing the IDs of the segments to which the campaign will be sent. :param template_id: String representing the ID of the template on which the campaign will be based. :param template_content: Hash representing the content to be used for the editable areas of the template. See documentation at campaignmonitor.com/api/campaigns/#creating_a_campaign_from_template for full details of template content format. :returns String representing the ID of the newly created campaign. """
body = { "Subject": subject, "Name": name, "FromName": from_name, "FromEmail": from_email, "ReplyTo": reply_to, "ListIDs": list_ids, "SegmentIDs": segment_ids, "TemplateID": template_id, "TemplateContent": template_content} response = self._post("/campaigns/%s/fromtemplate.json" % client_id, json.dumps(body)) self.campaign_id = json_to_py(response) return self.campaign_id
<SYSTEM_TASK:> Sends a preview of this campaign. <END_TASK> <USER_TASK:> Description: def send_preview(self, recipients, personalize="fallback"): """Sends a preview of this campaign."""
body = { "PreviewRecipients": [recipients] if isinstance(recipients, str) else recipients, "Personalize": personalize} response = self._post(self.uri_for("sendpreview"), json.dumps(body))
<SYSTEM_TASK:> Sends this campaign. <END_TASK> <USER_TASK:> Description: def send(self, confirmation_email, send_date="immediately"): """Sends this campaign."""
body = { "ConfirmationEmail": confirmation_email, "SendDate": send_date} response = self._post(self.uri_for("send"), json.dumps(body))
<SYSTEM_TASK:> Retrieves the opens for this campaign. <END_TASK> <USER_TASK:> Description: def opens(self, date="", page=1, page_size=1000, order_field="date", order_direction="asc"): """Retrieves the opens for this campaign."""
params = { "date": date, "page": page, "pagesize": page_size, "orderfield": order_field, "orderdirection": order_direction} response = self._get(self.uri_for("opens"), params=params) return json_to_py(response)
<SYSTEM_TASK:> Gets the lists across a client to which a subscriber with a particular <END_TASK> <USER_TASK:> Description: def lists_for_email(self, email_address): """Gets the lists across a client to which a subscriber with a particular email address belongs."""
params = {"email": email_address} response = self._get(self.uri_for("listsforemail"), params=params) return json_to_py(response)
<SYSTEM_TASK:> Gets this client's suppression list. <END_TASK> <USER_TASK:> Description: def suppressionlist(self, page=1, page_size=1000, order_field="email", order_direction="asc"): """Gets this client's suppression list."""
params = { "page": page, "pagesize": page_size, "orderfield": order_field, "orderdirection": order_direction} response = self._get(self.uri_for("suppressionlist"), params=params) return json_to_py(response)
<SYSTEM_TASK:> Adds email addresses to a client's suppression list <END_TASK> <USER_TASK:> Description: def suppress(self, email): """Adds email addresses to a client's suppression list"""
body = { "EmailAddresses": [email] if isinstance(email, str) else email} response = self._post(self.uri_for("suppress"), json.dumps(body))
<SYSTEM_TASK:> Unsuppresses an email address by removing it from the the client's <END_TASK> <USER_TASK:> Description: def unsuppress(self, email): """Unsuppresses an email address by removing it from the the client's suppression list"""
params = {"email": email} response = self._put(self.uri_for("unsuppress"), body=" ", params=params)
<SYSTEM_TASK:> Sets the PAYG billing settings for this client. <END_TASK> <USER_TASK:> Description: def set_payg_billing(self, currency, can_purchase_credits, client_pays, markup_percentage, markup_on_delivery=0, markup_per_recipient=0, markup_on_design_spam_test=0): """Sets the PAYG billing settings for this client."""
body = { "Currency": currency, "CanPurchaseCredits": can_purchase_credits, "ClientPays": client_pays, "MarkupPercentage": markup_percentage, "MarkupOnDelivery": markup_on_delivery, "MarkupPerRecipient": markup_per_recipient, "MarkupOnDesignSpamTest": markup_on_design_spam_test} response = self._put(self.uri_for('setpaygbilling'), json.dumps(body))
<SYSTEM_TASK:> Sets the monthly billing settings for this client. <END_TASK> <USER_TASK:> Description: def set_monthly_billing(self, currency, client_pays, markup_percentage, monthly_scheme=None): """Sets the monthly billing settings for this client."""
body = { "Currency": currency, "ClientPays": client_pays, "MarkupPercentage": markup_percentage} if monthly_scheme is not None: body["MonthlyScheme"] = monthly_scheme response = self._put(self.uri_for( 'setmonthlybilling'), json.dumps(body))
<SYSTEM_TASK:> Transfer credits to or from this client. <END_TASK> <USER_TASK:> Description: def transfer_credits(self, credits, can_use_my_credits_when_they_run_out): """Transfer credits to or from this client. :param credits: An Integer representing the number of credits to transfer. This value may be either positive if you want to allocate credits from your account to the client, or negative if you want to deduct credits from the client back into your account. :param can_use_my_credits_when_they_run_out: A Boolean value representing which, if set to true, will allow the client to continue sending using your credits or payment details once they run out of credits, and if set to false, will prevent the client from using your credits to continue sending until you allocate more credits to them. :returns: An object of the following form representing the result: { AccountCredits # Integer representing credits in your account now ClientCredits # Integer representing credits in this client's account now } """
body = { "Credits": credits, "CanUseMyCreditsWhenTheyRunOut": can_use_my_credits_when_they_run_out} response = self._post(self.uri_for('credits'), json.dumps(body)) return json_to_py(response)
<SYSTEM_TASK:> assigns the primary contact for this client <END_TASK> <USER_TASK:> Description: def set_primary_contact(self, email): """assigns the primary contact for this client"""
params = {"email": email} response = self._put(self.uri_for('primarycontact'), params=params) return json_to_py(response)
<SYSTEM_TASK:> Gets the smart email list. <END_TASK> <USER_TASK:> Description: def smart_email_list(self, status="all", client_id=None): """Gets the smart email list."""
if client_id is None: response = self._get( "/transactional/smartEmail?status=%s" % status) else: response = self._get( "/transactional/smartEmail?status=%s&clientID=%s" % (status, client_id)) return json_to_py(response)
<SYSTEM_TASK:> Sends the smart email. <END_TASK> <USER_TASK:> Description: def smart_email_send(self, smart_email_id, to, consent_to_track, cc=None, bcc=None, attachments=None, data=None, add_recipients_to_list=None): """Sends the smart email."""
validate_consent_to_track(consent_to_track) body = { "To": to, "CC": cc, "BCC": bcc, "Attachments": attachments, "Data": data, "AddRecipientsToList": add_recipients_to_list, "ConsentToTrack": consent_to_track, } response = self._post("/transactional/smartEmail/%s/send" % smart_email_id, json.dumps(body)) return json_to_py(response)
<SYSTEM_TASK:> Sends a classic email. <END_TASK> <USER_TASK:> Description: def classic_email_send(self, subject, from_address, to, consent_to_track, client_id=None, cc=None, bcc=None, html=None, text=None, attachments=None, track_opens=True, track_clicks=True, inline_css=True, group=None, add_recipients_to_list=None): """Sends a classic email."""
validate_consent_to_track(consent_to_track) body = { "Subject": subject, "From": from_address, "To": to, "CC": cc, "BCC": bcc, "HTML": html, "Text": text, "Attachments": attachments, "TrackOpens": track_opens, "TrackClicks": track_clicks, "InlineCSS": inline_css, "Group": group, "AddRecipientsToList": add_recipients_to_list, "ConsentToTrack": consent_to_track, } if client_id is None: response = self._post( "/transactional/classicEmail/send", json.dumps(body)) else: response = self._post( "/transactional/classicEmail/send?clientID=%s" % client_id, json.dumps(body)) return json_to_py(response)
<SYSTEM_TASK:> Gets the list of classic email groups. <END_TASK> <USER_TASK:> Description: def classic_email_groups(self, client_id=None): """Gets the list of classic email groups."""
if client_id is None: response = self._get("/transactional/classicEmail/groups") else: response = self._get( "/transactional/classicEmail/groups?clientID=%s" % client_id) return json_to_py(response)
<SYSTEM_TASK:> Gets the details of this message. <END_TASK> <USER_TASK:> Description: def message_details(self, message_id, statistics=False): """Gets the details of this message."""
response = self._get( "/transactional/messages/%s?statistics=%s" % (message_id, statistics)) return json_to_py(response)
<SYSTEM_TASK:> Adds a rulegroup to this segment. <END_TASK> <USER_TASK:> Description: def add_rulegroup(self, rulegroup): """Adds a rulegroup to this segment."""
body = rulegroup response = self._post("/segments/%s/rules.json" % self.segment_id, json.dumps(body))
<SYSTEM_TASK:> Gets the active subscribers in this segment. <END_TASK> <USER_TASK:> Description: def subscribers(self, date="", page=1, page_size=1000, order_field="email", order_direction="asc", include_tracking_information=False): """Gets the active subscribers in this segment."""
params = { "date": date, "page": page, "pagesize": page_size, "orderfield": order_field, "orderdirection": order_direction, "includetrackinginformation": include_tracking_information } response = self._get(self.uri_for("active"), params=params) return json_to_py(response)
<SYSTEM_TASK:> Adds an administrator to an account. <END_TASK> <USER_TASK:> Description: def add(self, email_address, name): """Adds an administrator to an account."""
body = { "EmailAddress": email_address, "Name": name} response = self._post("/admins.json", json.dumps(body)) return json_to_py(response)
<SYSTEM_TASK:> Updates the details for an administrator. <END_TASK> <USER_TASK:> Description: def update(self, new_email_address, name): """Updates the details for an administrator."""
params = {"email": self.email_address} body = { "EmailAddress": new_email_address, "Name": name} response = self._put("/admins.json", body=json.dumps(body), params=params) # Update self.email_address, so this object can continue to be used # reliably self.email_address = new_email_address
<SYSTEM_TASK:> Deletes the administrator from the account. <END_TASK> <USER_TASK:> Description: def delete(self): """Deletes the administrator from the account."""
params = {"email": self.email_address} response = self._delete("/admins.json", params=params)
<SYSTEM_TASK:> Creates a new list for a client. <END_TASK> <USER_TASK:> Description: def create(self, client_id, title, unsubscribe_page, confirmed_opt_in, confirmation_success_page, unsubscribe_setting="AllClientLists"): """Creates a new list for a client."""
body = { "Title": title, "UnsubscribePage": unsubscribe_page, "ConfirmedOptIn": confirmed_opt_in, "ConfirmationSuccessPage": confirmation_success_page, "UnsubscribeSetting": unsubscribe_setting} response = self._post("/lists/%s.json" % client_id, json.dumps(body)) self.list_id = json_to_py(response) return self.list_id
<SYSTEM_TASK:> Creates a new custom field for this list. <END_TASK> <USER_TASK:> Description: def create_custom_field(self, field_name, data_type, options=[], visible_in_preference_center=True): """Creates a new custom field for this list."""
body = { "FieldName": field_name, "DataType": data_type, "Options": options, "VisibleInPreferenceCenter": visible_in_preference_center} response = self._post(self.uri_for("customfields"), json.dumps(body)) return json_to_py(response)
<SYSTEM_TASK:> Updates a custom field belonging to this list. <END_TASK> <USER_TASK:> Description: def update_custom_field(self, custom_field_key, field_name, visible_in_preference_center): """Updates a custom field belonging to this list."""
custom_field_key = quote(custom_field_key, '') body = { "FieldName": field_name, "VisibleInPreferenceCenter": visible_in_preference_center} response = self._put(self.uri_for("customfields/%s" % custom_field_key), json.dumps(body)) return json_to_py(response)
<SYSTEM_TASK:> Deletes a custom field associated with this list. <END_TASK> <USER_TASK:> Description: def delete_custom_field(self, custom_field_key): """Deletes a custom field associated with this list."""
custom_field_key = quote(custom_field_key, '') response = self._delete("/lists/%s/customfields/%s.json" % (self.list_id, custom_field_key))
<SYSTEM_TASK:> Updates the options of a multi-optioned custom field on this list. <END_TASK> <USER_TASK:> Description: def update_custom_field_options(self, custom_field_key, new_options, keep_existing_options): """Updates the options of a multi-optioned custom field on this list."""
custom_field_key = quote(custom_field_key, '') body = { "Options": new_options, "KeepExistingOptions": keep_existing_options} response = self._put(self.uri_for( "customfields/%s/options" % custom_field_key), json.dumps(body))
<SYSTEM_TASK:> Gets the active subscribers for this list. <END_TASK> <USER_TASK:> Description: def active(self, date="", page=1, page_size=1000, order_field="email", order_direction="asc", include_tracking_preference=False): """Gets the active subscribers for this list."""
params = { "date": date, "page": page, "pagesize": page_size, "orderfield": order_field, "orderdirection": order_direction, "includetrackingpreference": include_tracking_preference, } response = self._get(self.uri_for("active"), params=params) return json_to_py(response)
<SYSTEM_TASK:> Updates this list. <END_TASK> <USER_TASK:> Description: def update(self, title, unsubscribe_page, confirmed_opt_in, confirmation_success_page, unsubscribe_setting="AllClientLists", add_unsubscribes_to_supp_list=False, scrub_active_with_supp_list=False): """Updates this list."""
body = { "Title": title, "UnsubscribePage": unsubscribe_page, "ConfirmedOptIn": confirmed_opt_in, "ConfirmationSuccessPage": confirmation_success_page, "UnsubscribeSetting": unsubscribe_setting, "AddUnsubscribesToSuppList": add_unsubscribes_to_supp_list, "ScrubActiveWithSuppList": scrub_active_with_supp_list} response = self._put("/lists/%s.json" % self.list_id, json.dumps(body))
<SYSTEM_TASK:> Gets a subscriber by list ID and email address. <END_TASK> <USER_TASK:> Description: def get(self, list_id=None, email_address=None, include_tracking_preference=False): """Gets a subscriber by list ID and email address."""
params = { "email": email_address or self.email_address, "includetrackingpreference": include_tracking_preference, } response = self._get("/subscribers/%s.json" % (list_id or self.list_id), params=params) return json_to_py(response)
<SYSTEM_TASK:> Adds a subscriber to a subscriber list. <END_TASK> <USER_TASK:> Description: def add(self, list_id, email_address, name, custom_fields, resubscribe, consent_to_track, restart_subscription_based_autoresponders=False): """Adds a subscriber to a subscriber list."""
validate_consent_to_track(consent_to_track) body = { "EmailAddress": email_address, "Name": name, "CustomFields": custom_fields, "Resubscribe": resubscribe, "ConsentToTrack": consent_to_track, "RestartSubscriptionBasedAutoresponders": restart_subscription_based_autoresponders} response = self._post("/subscribers/%s.json" % list_id, json.dumps(body)) return json_to_py(response)
<SYSTEM_TASK:> Updates any aspect of a subscriber, including email address, name, and <END_TASK> <USER_TASK:> Description: def update(self, new_email_address, name, custom_fields, resubscribe, consent_to_track, restart_subscription_based_autoresponders=False): """Updates any aspect of a subscriber, including email address, name, and custom field data if supplied."""
validate_consent_to_track(consent_to_track) params = {"email": self.email_address} body = { "EmailAddress": new_email_address, "Name": name, "CustomFields": custom_fields, "Resubscribe": resubscribe, "ConsentToTrack": consent_to_track, "RestartSubscriptionBasedAutoresponders": restart_subscription_based_autoresponders} response = self._put("/subscribers/%s.json" % self.list_id, body=json.dumps(body), params=params) # Update self.email_address, so this object can continue to be used # reliably self.email_address = new_email_address
<SYSTEM_TASK:> Imports subscribers into a subscriber list. <END_TASK> <USER_TASK:> Description: def import_subscribers(self, list_id, subscribers, resubscribe, queue_subscription_based_autoresponders=False, restart_subscription_based_autoresponders=False): """Imports subscribers into a subscriber list."""
body = { "Subscribers": subscribers, "Resubscribe": resubscribe, "QueueSubscriptionBasedAutoresponders": queue_subscription_based_autoresponders, "RestartSubscriptionBasedAutoresponders": restart_subscription_based_autoresponders} try: response = self._post("/subscribers/%s/import.json" % list_id, json.dumps(body)) except BadRequest as br: # Subscriber import will throw BadRequest if some subscribers are not imported # successfully. If this occurs, we want to return the ResultData property of # the BadRequest exception (which is of the same "form" as the response we'd # receive upon a completely successful import) if hasattr(br.data, 'ResultData'): return br.data.ResultData else: raise br return json_to_py(response)
<SYSTEM_TASK:> Unsubscribes this subscriber from the associated list. <END_TASK> <USER_TASK:> Description: def unsubscribe(self): """Unsubscribes this subscriber from the associated list."""
body = { "EmailAddress": self.email_address} response = self._post("/subscribers/%s/unsubscribe.json" % self.list_id, json.dumps(body))
<SYSTEM_TASK:> Gets the historical record of this subscriber's trackable actions. <END_TASK> <USER_TASK:> Description: def history(self): """Gets the historical record of this subscriber's trackable actions."""
params = {"email": self.email_address} response = self._get("/subscribers/%s/history.json" % self.list_id, params=params) return json_to_py(response)
<SYSTEM_TASK:> Returns form input field of Field. <END_TASK> <USER_TASK:> Description: def set_input(self): """Returns form input field of Field. """
name = self.attrs.get("_override", self.widget.__class__.__name__) self.values["field"] = str(FIELDS.get(name, FIELDS.get(None))(self.field, self.attrs))
<SYSTEM_TASK:> Wrap current field with icon wrapper. <END_TASK> <USER_TASK:> Description: def set_icon(self): """Wrap current field with icon wrapper. This setter must be the last setter called. """
if not self.attrs.get("_icon"): return if "Date" in self.field.field.__class__.__name__: return self.values["field"] = INPUT_WRAPPER % { "field": self.values["field"], "help": self.values["help"], "style": "%sicon " % escape(pad(self.attrs.get("_align", ""))), "icon": format_html(ICON_TEMPLATE, self.attrs.get("_icon")), }
<SYSTEM_TASK:> Set field properties and custom classes. <END_TASK> <USER_TASK:> Description: def set_classes(self): """Set field properties and custom classes. """
# Custom field classes on field wrapper if self.attrs.get("_field_class"): self.values["class"].append(escape(self.attrs.get("_field_class"))) # Inline class if self.attrs.get("_inline"): self.values["class"].append("inline") # Disabled class if self.field.field.disabled: self.values["class"].append("disabled") # Required class if self.field.field.required and not self.attrs.get("_no_required"): self.values["class"].append("required") elif self.attrs.get("_required") and not self.field.field.required: self.values["class"].append("required")
<SYSTEM_TASK:> Render field as HTML. <END_TASK> <USER_TASK:> Description: def render(self): """Render field as HTML. """
self.widget.attrs = { k: v for k, v in self.attrs.items() if k[0] != "_" } self.set_input() if not self.attrs.get("_no_wrapper"): self.set_label() self.set_help() self.set_errors() self.set_classes() self.set_icon() # Must be the bottom-most setter self.values["class"] = pad(" ".join(self.values["class"])).lstrip() result = mark_safe(FIELD_WRAPPER % self.values) self.widget.attrs = self.attrs # Re-assign variables return result
<SYSTEM_TASK:> Create test friends for displaying. <END_TASK> <USER_TASK:> Description: def ready(self): """ Create test friends for displaying. """
from .models import Friend # Requires migrations, not necessary try: Friend.objects.get_or_create(first_name="Michael", last_name="1", age=22) Friend.objects.get_or_create(first_name="Joe", last_name="2", age=21) Friend.objects.get_or_create(first_name="Bill", last_name="3", age=20) except: pass
<SYSTEM_TASK:> Render BooleanField with label next to instead of above. <END_TASK> <USER_TASK:> Description: def render_booleanfield(field, attrs): """ Render BooleanField with label next to instead of above. """
attrs.setdefault("_no_label", True) # No normal label for booleanfields attrs.setdefault("_inline", True) # Checkbox should be inline field.field.widget.attrs["style"] = "display:hidden" # Hidden field return wrappers.CHECKBOX_WRAPPER % { "style": pad(attrs.get("_style", "")), "field": field, "label": format_html( wrappers.LABEL_TEMPLATE, field.html_name, mark_safe(field.label) ) }
<SYSTEM_TASK:> Render ChoiceField as 'div' dropdown rather than select for more <END_TASK> <USER_TASK:> Description: def render_choicefield(field, attrs, choices=None): """ Render ChoiceField as 'div' dropdown rather than select for more customization. """
# Allow custom choice list, but if no custom choice list then wrap all # choices into the `wrappers.CHOICE_TEMPLATE` if not choices: choices = format_html_join("", wrappers.CHOICE_TEMPLATE, get_choices(field)) # Accessing the widget attrs directly saves them for a new use after # a POST request field.field.widget.attrs["value"] = field.value() or attrs.get("value", "") return wrappers.DROPDOWN_WRAPPER % { "name": field.html_name, "attrs": pad(flatatt(field.field.widget.attrs)), "placeholder": attrs.get("placeholder") or get_placeholder_text(), "style": pad(attrs.get("_style", "")), "icon": format_html(wrappers.ICON_TEMPLATE, attrs.get("_dropdown_icon") or "dropdown"), "choices": choices }
<SYSTEM_TASK:> MultipleChoiceField uses its own field, but also uses a queryset. <END_TASK> <USER_TASK:> Description: def render_multiplechoicefield(field, attrs, choices=None): """ MultipleChoiceField uses its own field, but also uses a queryset. """
choices = format_html_join("", wrappers.CHOICE_TEMPLATE, get_choices(field)) return wrappers.MULTIPLE_DROPDOWN_WRAPPER % { "name": field.html_name, "field": field, "choices": choices, "placeholder": attrs.get("placeholder") or get_placeholder_text(), "style": pad(attrs.get("_style", "")), "icon": format_html(wrappers.ICON_TEMPLATE, attrs.get("_dropdown_icon") or "dropdown"), }
<SYSTEM_TASK:> Render a typical File Field. <END_TASK> <USER_TASK:> Description: def render_filefield(field, attrs): """ Render a typical File Field. """
field.field.widget.attrs["style"] = "display:none" if not "_no_label" in attrs: attrs["_no_label"] = True return wrappers.FILE_WRAPPER % { "field": field, "id": "id_" + field.name, "style": pad(attrs.get("_style", "")), "text": escape(attrs.get("_text", "Select File")), "icon": format_html(wrappers.ICON_TEMPLATE, attrs.get("_icon", "file outline")) }
<SYSTEM_TASK:> Iterate over the input iter values. Then repeat the last value <END_TASK> <USER_TASK:> Description: def _repeat_iter(input_iter): """Iterate over the input iter values. Then repeat the last value indefinitely. This is useful to repeat seed values when an insufficient number of seeds are provided. E.g. KISS(1) effectively becomes KISS(1, 1, 1, 1), rather than (if we just used default values) KISS(1, default-value, default-value, default-value) It is better to repeat the last seed value, rather than just using default values. Given two generators seeded with an insufficient number of seeds, repeating the last seed value means their states are more different from each other, with less correlation between their generated outputs. """
last_value = None for value in input_iter: last_value = value yield value if last_value is not None: while True: yield last_value
<SYSTEM_TASK:> For consistent cross-platform seeding, provide an integer seed. <END_TASK> <USER_TASK:> Description: def seed(self, x=None, *args): """For consistent cross-platform seeding, provide an integer seed. """
if x is None: # Use same random seed code copied from Python's random.Random try: x = long(_hexlify(_urandom(16)), 16) except NotImplementedError: import time x = long(time.time() * 256) # use fractional seconds elif not isinstance(x, _Integral): # Use the hash of the input seed object. Note this does not give # consistent results cross-platform--between Python versions or # between 32-bit and 64-bit systems. x = hash(x) self.rng_iterator.seed(x, *args, mix_extras=True)
<SYSTEM_TASK:> Set number of bits per float output <END_TASK> <USER_TASK:> Description: def setbpf(self, bpf): """Set number of bits per float output"""
self._bpf = min(bpf, self.BPF) self._rng_n = int((self._bpf + self.RNG_RANGE_BITS - 1) / self.RNG_RANGE_BITS)
<SYSTEM_TASK:> Return information about backend and its availability. <END_TASK> <USER_TASK:> Description: def get_info(cls): """Return information about backend and its availability. :return: A BackendInfo tuple if the import worked, none otherwise. """
mod = try_import(cls.mod_name) if not mod: return None version = getattr(mod, '__version__', None) or getattr(mod, 'version', None) return BackendInfo(version or 'deprecated', '')
<SYSTEM_TASK:> Find choices of a field, whether it has choices or has a queryset. <END_TASK> <USER_TASK:> Description: def get_choices(field): """ Find choices of a field, whether it has choices or has a queryset. Args: field (BoundField): Django form boundfield Returns: list: List of choices """
empty_label = getattr(field.field, "empty_label", False) needs_empty_value = False choices = [] # Data is the choices if hasattr(field.field, "_choices"): choices = field.field._choices # Data is a queryset elif hasattr(field.field, "_queryset"): queryset = field.field._queryset field_name = getattr(field.field, "to_field_name") or "pk" choices += ((getattr(obj, field_name), str(obj)) for obj in queryset) # Determine if an empty value is needed if choices and (choices[0][1] == BLANK_CHOICE_DASH[0][1] or choices[0][0]): needs_empty_value = True # Delete empty option if not choices[0][0]: del choices[0] # Remove dashed empty choice if empty_label == BLANK_CHOICE_DASH[0][1]: empty_label = None # Add custom empty value if empty_label or not field.field.required: if needs_empty_value: choices.insert(0, ("", empty_label or BLANK_CHOICE_DASH[0][1])) return choices
<SYSTEM_TASK:> Get class-level class list, including all super class's. <END_TASK> <USER_TASK:> Description: def get_class_list(cls) -> DOMTokenList: """Get class-level class list, including all super class's."""
cl = [] cl.append(DOMTokenList(cls, cls.class_)) if cls.inherit_class: for base_cls in cls.__bases__: if issubclass(base_cls, WdomElement): cl.append(base_cls.get_class_list()) # Reverse order so that parent's class comes to front <- why? cl.reverse() return DOMTokenList(cls, *cl)
<SYSTEM_TASK:> Append child node at the last of child nodes. <END_TASK> <USER_TASK:> Description: def appendChild(self, child: 'WdomElement') -> Node: """Append child node at the last of child nodes. If this instance is connected to the node on browser, the child node is also added to it. """
if self.connected: self._append_child_web(child) return self._append_child(child)
<SYSTEM_TASK:> Insert new child node before the reference child node. <END_TASK> <USER_TASK:> Description: def insertBefore(self, child: Node, ref_node: Node) -> Node: """Insert new child node before the reference child node. If the reference node is not a child of this node, raise ValueError. If this instance is connected to the node on browser, the child node is also added to it. """
if self.connected: self._insert_before_web(child, ref_node) return self._insert_before(child, ref_node)
<SYSTEM_TASK:> Remove the child node from this node. <END_TASK> <USER_TASK:> Description: def removeChild(self, child: Node) -> Node: """Remove the child node from this node. If the node is not a child of this node, raise ValueError. """
if self.connected: self._remove_child_web(child) return self._remove_child(child)