text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Returns a list of modules that this executable needs in order to run
<END_TASK>
<USER_TASK:>
Description:
def search_dependencies(self):
"""Returns a list of modules that this executable needs in order to run
properly. This includes special kind declarations for precision or derived
types, but not dependency executable calls.
""" |
#It is understood that this executable's module is obviously required. Just
#add any additional modules from the parameters.
result = [p.dependency() for p in self.ordered_parameters]
result.extend([v.dependency() for k, v in list(self.members.items())])
for ekey, anexec in list(self.executables.items()):
result.extend(anexec.search_dependencies())
return [m for m in result if m is not None and m != self.module.name] |
<SYSTEM_TASK:>
Unpickles all members of the specified dictionary.
<END_TASK>
<USER_TASK:>
Description:
def _unpickle_collection(self, collection):
"""Unpickles all members of the specified dictionary.""" |
for mkey in collection:
if isinstance(collection[mkey], list):
for item in collection[mkey]:
item.unpickle(self)
else:
collection[mkey].unpickle(self) |
<SYSTEM_TASK:>
Uses the specified line parser to parse the given line.
<END_TASK>
<USER_TASK:>
Description:
def rt_update(self, statement, linenum, mode, xparser):
"""Uses the specified line parser to parse the given line.
:arg statement: a string of lines that are part of a single statement.
:arg linenum: the line number of the first line in the list relative to
the entire module contents.
arg mode: either 'insert', 'replace' or 'delete'
:arg xparser: an instance of the executable parser from the real
time update module's line parser.
""" |
section = self.find_section(self.module.charindex(linenum, 1))
if section == "body":
xparser.parse_line(statement, self, mode)
elif section == "signature":
if mode == "insert":
xparser.parse_signature(statement, self) |
<SYSTEM_TASK:>
Changes the name of this executable and the reference to it in the
<END_TASK>
<USER_TASK:>
Description:
def update_name(self, name):
"""Changes the name of this executable and the reference to it in the
parent module.""" |
if name != self.name:
self.parent.executables[name] = self
del self.parent.executables[self.name]
self.name = name |
<SYSTEM_TASK:>
Returns the CustomType instance if this executable is an embedded
<END_TASK>
<USER_TASK:>
Description:
def is_type_target(self):
"""Returns the CustomType instance if this executable is an embedded
procedure in a custom type declaration; else False.
""" |
if self._is_type_target is None:
#All we need to do is search through the custom types in the parent
#module and see if any of their executables points to this method.
self._is_type_target = False
for tkey in self.module.types:
custype = self.module.types[tkey]
for execkey, execinst in custype.executables.items():
if execinst.target is self:
self._is_type_target = custype
break
if self._is_type_target:
break
return self._is_type_target |
<SYSTEM_TASK:>
Returns a list of code elements whose names are in the specified object.
<END_TASK>
<USER_TASK:>
Description:
def _get_assignments_in(self, filterlist, symbol = ""):
"""Returns a list of code elements whose names are in the specified object.
:arg filterlist: the list of symbols to check agains the assignments.
:arg symbol: when specified, return true if that symbol has its value
changed via an assignment.""" |
if symbol != "":
lsymbol = symbol
for assign in self._assignments:
target = assign.split("%")[0].lower()
if target == lsymbol:
return True
else:
result = []
for assign in self._assignments:
target = assign.split("%")[0].lower()
if target in filterlist:
result.append(assign)
return result |
<SYSTEM_TASK:>
Returns the ValueElement corresponding to the parameter
<END_TASK>
<USER_TASK:>
Description:
def get_parameter(self, index):
"""Returns the ValueElement corresponding to the parameter
at the specified index.""" |
result = None
if index < len(self.paramorder):
key = self.paramorder[index]
if key in self._parameters:
result = self._parameters[key]
return result |
<SYSTEM_TASK:>
Adds the specified parameter value to the list.
<END_TASK>
<USER_TASK:>
Description:
def add_parameter(self, parameter):
"""Adds the specified parameter value to the list.""" |
if parameter.name.lower() not in self.paramorder:
self.paramorder.append(parameter.name.lower())
self._parameters[parameter.name.lower()] = parameter |
<SYSTEM_TASK:>
Removes the specified parameter from the list.
<END_TASK>
<USER_TASK:>
Description:
def remove_parameter(self, parameter_name):
"""Removes the specified parameter from the list.""" |
if parameter_name in self.paramorder:
index = self.paramorder.index(parameter_name)
del self.paramorder[index]
if parameter_name in self._parameters:
del self._parameters[parameter_name] |
<SYSTEM_TASK:>
Returns a comma-separated list of the parameters in the executable definition.
<END_TASK>
<USER_TASK:>
Description:
def parameters_as_string(self):
"""Returns a comma-separated list of the parameters in the executable definition.""" |
params = ", ".join([ p.name for p in self.ordered_parameters ])
return params |
<SYSTEM_TASK:>
Adds the specified executable dependency to the list for this executable.
<END_TASK>
<USER_TASK:>
Description:
def add_dependency(self, value):
"""Adds the specified executable dependency to the list for this executable.""" |
if value.name in self.dependencies:
self.dependencies[value.name.lower()].append(value)
else:
self.dependencies[value.name.lower()] = [ value ] |
<SYSTEM_TASK:>
Updates the attributes for the function instance, handles name changes
<END_TASK>
<USER_TASK:>
Description:
def update(self, name, modifiers, dtype, kind):
"""Updates the attributes for the function instance, handles name changes
in the parent module as well.""" |
self.update_name(name)
self.modifiers = modifiers
self.dtype = dtype
self.kind = kind
self.update_dtype() |
<SYSTEM_TASK:>
Gets a string showing the return type and modifiers for the
<END_TASK>
<USER_TASK:>
Description:
def returns(self):
"""Gets a string showing the return type and modifiers for the
function in a nice display format.""" |
kind = "({}) ".format(self.kind) if self.kind is not None else ""
mods = ", ".join(self.modifiers) + " "
dtype = self.dtype if self.dtype is not None else ""
return "{}{}{}".format(dtype, kind, mods) |
<SYSTEM_TASK:>
Returns the signature definition for the subroutine.
<END_TASK>
<USER_TASK:>
Description:
def signature(self):
"""Returns the signature definition for the subroutine.""" |
mods = ", ".join(self.modifiers)
return "{} SUBROUTINE {}({})".format(mods, self.name,
self.parameters_as_string()) |
<SYSTEM_TASK:>
Updates the attributes for the subroutine instance, handles name changes
<END_TASK>
<USER_TASK:>
Description:
def update(self, name, modifiers):
"""Updates the attributes for the subroutine instance, handles name changes
in the parent module as well.""" |
self.update_name(name)
self.modifiers = modifiers |
<SYSTEM_TASK:>
Returns the code element that is the actual executable that this type
<END_TASK>
<USER_TASK:>
Description:
def target(self):
"""Returns the code element that is the actual executable that this type
executable points to.""" |
if self.pointsto is not None:
#It is in the format of module.executable.
xinst = self.module.parent.get_executable(self.pointsto.lower())
return xinst
else:
#The executable it points to is the same as its name.
fullname = "{}.{}".format(self.module.name, self.name)
return self.module.parent.get_executable(fullname.lower()) |
<SYSTEM_TASK:>
Returns the name of a member in this type that is non-custom
<END_TASK>
<USER_TASK:>
Description:
def fixedvar(self):
"""Returns the name of a member in this type that is non-custom
so that it would terminate the auto-class variable context chain.
""" |
possible = [m for m in self.members.values() if not m.is_custom]
#If any of the possible variables is not allocatable or pointer, it will always
#have a value and we can just use that.
sufficient = [m for m in possible if "allocatable" not in m.modifiers
and "pointer" not in m.modifiers]
if len(sufficient) > 0:
return [sufficient[0].name]
else:
return [m.name for m in possible] |
<SYSTEM_TASK:>
When True, this CustomType has at least one member that is of the same
<END_TASK>
<USER_TASK:>
Description:
def recursive(self):
"""When True, this CustomType has at least one member that is of the same
type as itself.
""" |
for m in self.members.values():
if m.kind is not None and m.kind.lower() == self.name.lower():
return True
else:
return False |
<SYSTEM_TASK:>
Updates the name of the custom type in this instance and its
<END_TASK>
<USER_TASK:>
Description:
def update_name(self, name):
"""Updates the name of the custom type in this instance and its
parent reference.""" |
if name != self.name:
self.parent.types[name] = self
del self.parent.types[self.name]
self.name = name |
<SYSTEM_TASK:>
Gets the list of parameters at the specified index in the calling argument
<END_TASK>
<USER_TASK:>
Description:
def get_parameter(self, index):
"""Gets the list of parameters at the specified index in the calling argument
list for each of the module procedures in the interface.
:arg index: the 0-based index of the parameter in the argument list.
""" |
result = []
for target in self.targets:
if target is not None:
result.append(target.get_parameter(index))
return result |
<SYSTEM_TASK:>
Sets the docstring of this interface using the docstrings of its embedded
<END_TASK>
<USER_TASK:>
Description:
def find_docstring(self):
"""Sets the docstring of this interface using the docstrings of its embedded
module procedures that it is an interface for.
""" |
#The docstrings for the interface are compiled from the separate docstrings
#of the module procedures it is an interface for. We choose the first of these
#procedures by convention and copy its docstrings over.
#Just use the very first embedded method that isn't None and has a docstring.
if self.first and len(self.docstring) == 0:
self.docstring = self.first.docstring |
<SYSTEM_TASK:>
Returns a home-grown description that includes a summary of the calling interface
<END_TASK>
<USER_TASK:>
Description:
def describe(self):
"""Returns a home-grown description that includes a summary of the calling interface
for all the module procedures embedded in this interface.
""" |
#Interfaces are tricky because we can have an arbitrary number of embedded procedures
#that each have different calling interfaces and return types. We are trying to
#summarize that information in a single interface. Interfaces can't mix executable
#types; they are either all subroutines or all functions.
self.find_docstring()
if not self.subroutine:
#We have a return type to worry about, compile it from all the targets
ret_type = []
for target in self.targets:
if target.returns not in ret_type:
ret_type.append(target.returns)
ret_text = ', '.join(ret_type)
else:
ret_text = ""
#The list of types it accepts is constructed the same way for functions and subroutines.
act_type = []
for target in self.targets:
param = target.ordered_parameters[0]
if param.strtype not in act_type:
act_type.append(param.strtype)
act_text = ', '.join(act_type)
if self.subroutine:
return "SUMMARY: {} | ACCEPTS: {}".format(self.summary, act_text)
else:
return "SUMMARY: {} | RETURNS: {} | ACCEPTS: {}".format(self.summary, ret_text, act_text) |
<SYSTEM_TASK:>
Returns the first module procedure embedded in the interface that has a valid
<END_TASK>
<USER_TASK:>
Description:
def first(self):
"""Returns the first module procedure embedded in the interface that has a valid
instance of a CodeElement.
""" |
if self._first is None:
for target in self.targets:
if target is not None:
self._first = target
break
else:
self._first = False
return self._first |
<SYSTEM_TASK:>
Provides an ordered list of CodeElement instances for each of the embedded
<END_TASK>
<USER_TASK:>
Description:
def targets(self):
"""Provides an ordered list of CodeElement instances for each of the embedded
module procedures in the generic interface.
""" |
if self._targets is None:
self._targets = {}
for key in self.procedures:
element = self.module.parent.get_executable(key)
if element is not None:
self._targets[key] = element
else:
self._targets[key] = None
msg.warn("unable to locate module procedure {}".format(key) +
" in interface {}".format(self.name))
return [self._targets[key] for key in self.procedures] |
<SYSTEM_TASK:>
Returns a list of other modules that this module and its members and executables
<END_TASK>
<USER_TASK:>
Description:
def search_dependencies(self):
"""Returns a list of other modules that this module and its members and executables
depend on in order to run correctly. This differs from the self.dependencies attribute
that just hase explicit module names from the 'use' clauses.
""" |
result = [self.module.name]
#First we look at the explicit use references from this module and all
#its dependencies until the chain terminates.
stack = self.needs
while len(stack) > 0:
module = stack.pop()
if module in result:
continue
self.parent.load_dependency(module, True, True, False)
if module in self.parent.modules:
for dep in self.parent.modules[module].needs:
modname = dep.split(".")[0]
if modname not in result:
result.append(modname)
if modname not in stack:
stack.append(modname)
#Add any incidentals from the automatic construction of code. These can be from
#executables that use special precision types without importing them or from
#derived types. Same applies to the local members of this module.
for ekey, anexec in list(self.executables.items()):
for dep in anexec.search_dependencies():
if dep is not None and dep not in result:
result.append(dep)
for member in list(self.members.values()):
dep = member.dependency()
if dep is not None and dep not in result:
result.append(dep)
return result |
<SYSTEM_TASK:>
Returns the file path to this module taking the pre-processing into account.
<END_TASK>
<USER_TASK:>
Description:
def compile_path(self):
"""Returns the file path to this module taking the pre-processing into account.
If the module requires pre-processing, the extension is reported as F90; otherwise,
the regular self.filepath is returned.
""" |
if not self.precompile:
return self.filepath
else:
if self._compile_path is None:
segs = self.filepath.split('.')
segs.pop()
segs.append("F90")
self._compile_path = '.'.join(segs)
return self._compile_path |
<SYSTEM_TASK:>
Sets all members, types and executables in this module as public as
<END_TASK>
<USER_TASK:>
Description:
def all_to_public(self):
"""Sets all members, types and executables in this module as public as
long as it doesn't already have the 'private' modifier.
""" |
if "private" not in self.modifiers:
def public_collection(attribute):
for key in self.collection(attribute):
if key not in self.publics:
self.publics[key.lower()] = 1
public_collection("members")
public_collection("types")
public_collection("executables") |
<SYSTEM_TASK:>
Uses the specified line parser to parse the given statement.
<END_TASK>
<USER_TASK:>
Description:
def rt_update(self, statement, linenum, mode, modulep, lineparser):
"""Uses the specified line parser to parse the given statement.
:arg statement: a string of lines that are part of a single statement.
:arg linenum: the line number of the first line in the statement relative to
the entire module contents.
:arg mode: either 'insert', 'replace' or 'delete'
:arg modulep: an instance of ModuleParser for handling the changes
to the instance of the module.
:arg lineparser: a line parser instance for dealing with new instances
of types or executables that are add using only a signature.
""" |
#Most of the module is body, since that includes everything inside
#of the module ... end module keywords. Since docstrings are handled
#at a higher level by line parser, we only need to deal with the body
#Changes of module name are so rare that we aren't going to bother with them.
section = self.find_section(self.module.charindex(linenum, 1))
if section == "body":
modulep.rt_update(statement, self, mode, linenum, lineparser) |
<SYSTEM_TASK:>
Checks if the specified symbol is the name of one of the methods
<END_TASK>
<USER_TASK:>
Description:
def get_dependency_element(self, symbol):
"""Checks if the specified symbol is the name of one of the methods
that this module depends on. If it is, search for the actual code
element and return it.""" |
for depend in self.dependencies:
if "." in depend:
#We know the module name and the executable name, easy
if depend.split(".")[1] == symbol.lower():
found = self.parent.get_executable(depend)
break
else:
#We only have the name of an executable or interface, we have to search
#the whole module for the element.
fullname = "{}.{}".format(depend, symbol)
if self.parent.get_executable(fullname) is not None:
found = self.parent.get_executable(fullname)
break
if self.parent.get_interface(fullname) is not None:
found = self.parent.get_interface(fullname)
break
else:
return None
return found |
<SYSTEM_TASK:>
Finds all possible symbol completions of the given symbol that belong
<END_TASK>
<USER_TASK:>
Description:
def completions(self, symbol, attribute, recursive = False):
"""Finds all possible symbol completions of the given symbol that belong
to this module and its dependencies.
:arg symbol: the code symbol that needs to be completed.
:arg attribute: one of ['dependencies', 'publics', 'members',
'types', 'executables'] for specifying which collections to search.
:arg result: the possible completions collected so far in the search.
""" |
possible = []
for ekey in self.collection(attribute):
if symbol in ekey:
possible.append(ekey)
#Try this out on all the dependencies as well to find all the possible
#completions.
if recursive:
for depkey in self.dependencies:
#Completions need to be fast. If the module for the parent isn't already
#loaded, we just ignore the completions it might have.
if depkey in self.parent.modules:
possible.extend(self.parent.modules[depkey].completions(symbol, attribute))
return possible |
<SYSTEM_TASK:>
Returns a unique list of module names that this module depends on.
<END_TASK>
<USER_TASK:>
Description:
def needs(self):
"""Returns a unique list of module names that this module depends on.""" |
result = []
for dep in self.dependencies:
module = dep.split(".")[0].lower()
if module not in result:
result.append(module)
return result |
<SYSTEM_TASK:>
Filters the executables in the dictionary by their type.
<END_TASK>
<USER_TASK:>
Description:
def _filter_execs(self, isSubroutine):
"""Filters the executables in the dictionary by their type.""" |
result = {}
for key in self.executables:
if (isinstance(self.executables[key], Subroutine) and isSubroutine) or \
(isinstance(self.executables[key], Function) and not isSubroutine):
result[key] = self.executables[key]
return result |
<SYSTEM_TASK:>
Checks the module for documentation and best-practice warnings.
<END_TASK>
<USER_TASK:>
Description:
def warn(self, collection):
"""Checks the module for documentation and best-practice warnings.""" |
super(CodeElement, self).warn(collection)
if not "implicit none" in self.modifiers:
collection.append("WARNING: implicit none not set in {}".format(self.name)) |
<SYSTEM_TASK:>
Returns the collection corresponding the attribute name.
<END_TASK>
<USER_TASK:>
Description:
def collection(self, attribute):
"""Returns the collection corresponding the attribute name.""" |
return {
"dependencies": self.dependencies,
"publics": self.publics,
"members": self.members,
"types": self.types,
"executables": self.executables,
"interfaces": self.interfaces
}[attribute] |
<SYSTEM_TASK:>
Updates the refstring that represents the original string that
<END_TASK>
<USER_TASK:>
Description:
def update_refstring(self, string):
"""Updates the refstring that represents the original string that
the module was parsed from. Also updates any properties or attributes
that are derived from the refstring.""" |
self.refstring = string
self._lines = []
self._contains_index = None
self.changed = True
#The only other references that become out of date are the contains
#and preamble attributes which are determined by the parsers.
#Assuming we did everything right with the rt update, we should be
#able to just use the new contains index to update those.
icontains = self.contains_index
ichar = self.charindex(icontains, 0)
self.preamble = string[:ichar]
self.contains = string[ichar + 9:] |
<SYSTEM_TASK:>
Updates all the element instances that are children of this module
<END_TASK>
<USER_TASK:>
Description:
def update_elements(self, line, column, charcount, docdelta=0):
"""Updates all the element instances that are children of this module
to have new start and end charindex values based on an operation that
was performed on the module source code.
:arg line: the line number of the *start* of the operation.
:arg column: the column number of the start of the operation.
:arg charcount: the total character length change from the operation.
:arg docdelta: the character length of changes made to types/execs
that are children of the module whose docstrings external to their
definitions were changed.
""" |
target = self.charindex(line, column) + charcount
#We are looking for all the instances whose *start* attribute lies
#after this target. Then we update them all by that amount.
#However, we need to be careful because of docdelta. If an elements
#docstring contains the target, we don't want to update it.
if line < self.contains_index:
for t in self.types:
if self._update_char_check(self.types[t], target, docdelta):
self._element_charfix(self.types[t], charcount)
for m in self.members:
if self.members[m].start > target:
self.members[m].start += charcount
self.members[m].end += charcount
self._contains_index = None
else:
for iexec in self.executables:
if self._update_char_check(self.executables[iexec], target, docdelta):
self._element_charfix(self.executables[iexec], charcount) |
<SYSTEM_TASK:>
Checks whether the specified element should have its character indices
<END_TASK>
<USER_TASK:>
Description:
def _update_char_check(self, element, target, docdelta):
"""Checks whether the specified element should have its character indices
updated as part of real-time updating.""" |
if docdelta != 0:
if (element.docstart <= target and
element.docend >= target - docdelta):
return True
else:
return element.absstart > target
else:
return element.absstart > target |
<SYSTEM_TASK:>
Updates the start and end attributes by charcount for the element.
<END_TASK>
<USER_TASK:>
Description:
def _element_charfix(self, element, charcount):
"""Updates the start and end attributes by charcount for the element.""" |
element.start += charcount
element.docstart += charcount
element.end += charcount
element.docend += charcount |
<SYSTEM_TASK:>
Gets the instance of the element who owns the specified line
<END_TASK>
<USER_TASK:>
Description:
def get_element(self, line, column):
"""Gets the instance of the element who owns the specified line
and column.""" |
ichar = self.charindex(line, column)
icontains = self.contains_index
result = None
if line < icontains:
#We only need to search through the types and members.
maxstart = 0
tempresult = None
for t in self.types:
if ichar >= self.types[t].absstart:
if self.types[t].absstart > maxstart:
maxstart = self.types[t].absstart
tempresult = self.types[t]
#This takes the possibility of an incomplete type into account
if (tempresult is not None and (ichar <= tempresult.end or
tempresult.incomplete)):
result = tempresult
if not result:
#Members only span a single line usually and don't get added
#without an end token.
for m in self.members:
if (ichar >= self.members[m].start and
ichar <= self.members[m].end):
result = self.members[m]
break
else:
#We only need to search through the executables
tempresult = None
maxstart = 0
for iexec in self.executables:
if (ichar >= self.executables[iexec].absstart):
if self.executables[iexec].absstart > maxstart:
maxstart = self.executables[iexec].absstart
tempresult = self.executables[iexec]
if tempresult is not None and (ichar <= tempresult.end or
tempresult.incomplete):
result = tempresult
if result is None:
#We must be in the text of the module, return the module
return self
else:
return result |
<SYSTEM_TASK:>
Updates the elements in the module 'result' that have character indices
<END_TASK>
<USER_TASK:>
Description:
def update_embedded(self, attribute):
"""Updates the elements in the module 'result' that have character indices
that are a subset of another element. These correspond to cases where the
type or subroutine is declared within another subroutine.
:attr attribute: the name of the collection to update over.
""" |
#The parser doesn't handle embeddings deeper than two levels.
coll = self.collection(attribute)
keys = list(coll.keys())
for key in keys:
element = coll[key]
new_parent = self.find_embedded_parent(element)
if new_parent is not None:
#Update the parent of the embedded element, add it to the collection
#of the parent element and then delete it from the module's collection.
element.parent = new_parent
if attribute == "types":
new_parent.types[key] = element
else:
new_parent.executables[key] = element
del coll[key] |
<SYSTEM_TASK:>
Gets the absolute character index of the line and column
<END_TASK>
<USER_TASK:>
Description:
def charindex(self, line, column):
"""Gets the absolute character index of the line and column
in the continuous string.""" |
#Make sure that we have chars and lines to work from if this
#gets called before linenum() does.
if len(self._lines) == 0:
self.linenum(1)
if line < len(self._chars):
return self._chars[line - 1] + column
else:
return len(self.refstring) |
<SYSTEM_TASK:>
Gets the line number of the character at the specified index.
<END_TASK>
<USER_TASK:>
Description:
def linenum(self, index):
"""Gets the line number of the character at the specified index.
If the result is unknown, -1 is returned.""" |
if len(self._lines) == 0 and self.refstring != "":
self._lines = self.refstring.split("\n")
#Add one for the \n that we split on for each line
self._chars = [ len(x) + 1 for x in self._lines ]
#Remove the last line break since it doesn't exist
self._chars[-1] -= 1
#Now we want to add up the number of characters in each line
#as the lines progress so that it is easy to search for the
#line of a single character index
total = 0
for i in range(len(self._chars)):
total += self._chars[i]
self._chars[i] = total
if len(self._lines) > 0:
#Now, find the first index where the character value is >= index
result = -1
i = 0
while result == -1 and i < len(self._chars):
if index <= self._chars[i]:
result = [ i, self._chars[i] - index]
i += 1
return result
else:
return [ -1, -1 ] |
<SYSTEM_TASK:>
check if input is valid
<END_TASK>
<USER_TASK:>
Description:
def check_valid(self):
""" check if input is valid """ |
for k,input in self.inputs.items():
if k in self.valid_opts:
for param in self.valid_opts[k]:
if param is None or input is None:
return True
elif type(param) is str and '+' in param:
if re.search(r'^'+param,str(input)):
return True
elif type(param) is bool and type(input) is bool:
return True
elif type(param) is list and type(input) is list:
return True
else:
if str(input).lower() == str(param):
return True
raise ValueError("Invalid input for '%s' parameter. Options are: %s" % (k,' '.join(["'%s'," % str(o) for o in self.valid_opts[k]]) ))
else:
raise ValueError("Invalid parameter for '%s'. Params are: %s" % (self.__class__.__name__,', '.join(["'%s'" % p for p in self.valid_opts.keys()]) )) |
<SYSTEM_TASK:>
if policy in default but not input still return
<END_TASK>
<USER_TASK:>
Description:
def update_policy(self,defaultHeaders):
""" if policy in default but not input still return """ |
if self.inputs is not None:
for k,v in defaultHeaders.items():
if k not in self.inputs:
self.inputs[k] = v
return self.inputs
else:
return self.inputs |
<SYSTEM_TASK:>
rewrite update policy so that additional pins are added and not overwritten
<END_TASK>
<USER_TASK:>
Description:
def update_policy(self,defaultHeaders):
""" rewrite update policy so that additional pins are added and not overwritten """ |
if self.inputs is not None:
for k,v in defaultHeaders.items():
if k not in self.inputs:
self.inputs[k] = v
if k == 'pins':
self.inputs[k] = self.inputs[k] + defaultHeaders[k]
return self.inputs
else:
return self.inputs |
<SYSTEM_TASK:>
rewrite return header dict for HPKP
<END_TASK>
<USER_TASK:>
Description:
def create_header(self):
""" rewrite return header dict for HPKP """ |
try:
self.check_valid()
_header_list = []
for k,v in self.inputs.items():
if v is None:
return {self.__class__.__name__.replace('_','-'):None}
elif k == 'value':
_header_list.insert(0,str(v))
elif isinstance(v,bool):
if v is True: _header_list.append(k)
elif type(v) is list:
lambda v: len(v)>0, [_header_list.append(''.join(['pin-%s=%s' % (pink,pinv) for pink, pinv in pin.items()])) for pin in v]
else:
_header_list.append('%s=%s' % (k,str(v)))
return {self.__class__.__name__.replace('_','-'):'; '.join(_header_list)}
except Exception, e:
raise |
<SYSTEM_TASK:>
add items to existing csp policies
<END_TASK>
<USER_TASK:>
Description:
def update_policy(self,cspDefaultHeaders):
""" add items to existing csp policies """ |
try:
self.check_valid(cspDefaultHeaders)
if self.inputs is not None:
for p,l in self.inputs.items():
cspDefaultHeaders[p] = cspDefaultHeaders[p]+ list(set(self.inputs[p]) - set(cspDefaultHeaders[p]))
return cspDefaultHeaders
else:
return self.inputs
except Exception, e:
raise |
<SYSTEM_TASK:>
fresh csp policy
<END_TASK>
<USER_TASK:>
Description:
def rewrite_policy(self,cspDefaultHeaders):
""" fresh csp policy """ |
try:
self.check_valid(cspDefaultHeaders)
if self.inputs is not None:
for p,l in cspDefaultHeaders.items():
if p in self.inputs:
cspDefaultHeaders[p] = self.inputs[p]
else:
cspDefaultHeaders[p] = []
return cspDefaultHeaders
else:
return self.inputs
except Exception, e:
raise |
<SYSTEM_TASK:>
Main entrypoint for all plugins.
<END_TASK>
<USER_TASK:>
Description:
def invoke(self, dirname, filenames=set(), linter_configs=set()):
"""
Main entrypoint for all plugins.
Returns results in the format of:
{'filename': {
'line_number': [
'error1',
'error2'
]
}
}
""" |
retval = defaultdict(lambda: defaultdict(list))
if len(filenames):
extensions = [e.lstrip('.') for e in self.get_file_extensions()]
filenames = [f for f in filenames if f.split('.')[-1] in extensions]
if not filenames:
# There were a specified set of files, but none were the right
# extension. Different from the else-case below.
return {}
to_find = ' -o '.join(['-samefile "%s"' % f for f in filenames])
else:
to_find = ' -o '.join(['-name "*%s"' % ext
for ext in self.get_file_extensions()])
cmd = 'find %s -path "*/%s" | xargs %s' % (
dirname, to_find, self.get_command(
dirname,
linter_configs=linter_configs))
result = self.executor(cmd)
for line in result.split('\n'):
output = self.process_line(dirname, line)
if output is not None:
filename, lineno, messages = output
if filename.startswith(dirname):
filename = filename[len(dirname) + 1:]
retval[filename][lineno].append(messages)
return retval |
<SYSTEM_TASK:>
message is potentially a list of messages to post. This is later
<END_TASK>
<USER_TASK:>
Description:
def clean_already_reported(self, comments, file_name, position,
message):
"""
message is potentially a list of messages to post. This is later
converted into a string.
""" |
for comment in comments:
if ((comment['path'] == file_name and
comment['position'] == position and
comment['user']['login'] == self.requester.username)):
return [m for m in message if m not in comment['body']]
return message |
<SYSTEM_TASK:>
Convert message from list to string for GitHub API.
<END_TASK>
<USER_TASK:>
Description:
def convert_message_to_string(self, message):
"""Convert message from list to string for GitHub API.""" |
final_message = ''
for submessage in message:
final_message += '* {submessage}\n'.format(submessage=submessage)
return final_message |
<SYSTEM_TASK:>
Comments on an issue, not on a particular line.
<END_TASK>
<USER_TASK:>
Description:
def post_comment(self, message):
"""
Comments on an issue, not on a particular line.
""" |
report_url = (
'https://api.github.com/repos/%s/issues/%s/comments'
% (self.repo_name, self.pr_number)
)
result = self.requester.post(report_url, {'body': message})
if result.status_code >= 400:
log.error("Error posting comment to github. %s", result.json())
return result |
<SYSTEM_TASK:>
Handles GET requests and instantiates a blank version of the form.
<END_TASK>
<USER_TASK:>
Description:
def get(self, request, *args, **kwargs):
"""
Handles GET requests and instantiates a blank version of the form.
""" |
form_class = self.get_form_class()
form = self.get_form(form_class)
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form) |
<SYSTEM_TASK:>
That's the trick - we create self.form when django tries to get our queryset.
<END_TASK>
<USER_TASK:>
Description:
def queryset(self, request, queryset):
form = self.get_form(request)
"""
That's the trick - we create self.form when django tries to get our queryset.
This allows to create unbount and bound form in the single place.
""" |
self.form = form
start_date = form.start_date()
end_date = form.end_date()
if form.is_valid() and (start_date or end_date):
args = self.__get_filterargs(
start=start_date,
end=end_date,
)
return queryset.filter(**args) |
<SYSTEM_TASK:>
Clones the given repo and returns the Repository object.
<END_TASK>
<USER_TASK:>
Description:
def clone_repo(self, repo_name, remote_repo, ref):
"""Clones the given repo and returns the Repository object.""" |
self.shallow_clone = False
dirname, repo = self.set_up_clone(repo_name, remote_repo)
if os.path.isdir("%s/.git" % dirname):
log.debug("Updating %s to %s", repo.download_location, dirname)
self.executor(
"cd %s && git checkout master" % dirname)
self.pull(dirname)
else:
log.debug("Cloning %s to %s", repo.download_location, dirname)
self.executor(
"git clone %s %s" % (repo.download_location, dirname))
if remote_repo is not None:
log.debug("Pulling remote branch from %s", remote_repo.url)
self.add_remote(dirname,
remote_repo.name,
remote_repo.url)
self.pull(dirname)
return repo |
<SYSTEM_TASK:>
Returns a Python dictionary representation of the given object, expected to
<END_TASK>
<USER_TASK:>
Description:
def prepare_object(obj, using="default"):
"""
Returns a Python dictionary representation of the given object, expected to
be a Model object with an associated SearchIndex. The optional argument
`using` specifies the backend to use from the Haystack connections list.
""" |
model = obj.__class__
unified_index = connections[using].get_unified_index()
index = unified_index.get_index(model)
prepped_data = index.full_prepare(obj)
final_data = {}
for key, value in prepped_data.items():
final_data[key] = connections[using].get_backend()._from_python(value)
return final_data |
<SYSTEM_TASK:>
Fetches a Django model using the app registry.
<END_TASK>
<USER_TASK:>
Description:
def get_model(app_label, model_name):
"""
Fetches a Django model using the app registry.
This doesn't require that an app with the given app label exists, which
makes it safe to call when the registry is being populated. All other
methods to access models might raise an exception about the registry not
being ready yet.
Raises LookupError if model isn't found.
""" |
try:
from django.apps import apps
from django.core.exceptions import AppRegistryNotReady
except ImportError:
# Django < 1.7
from django.db import models
return models.get_model(app_label, model_name)
try:
return apps.get_model(app_label, model_name)
except AppRegistryNotReady:
if apps.apps_ready and not apps.models_ready:
# If this function is called while `apps.populate()` is
# loading models, ensure that the module that defines the
# target model has been imported and try looking the model up
# in the app registry. This effectively emulates
# `from path.to.app.models import Model` where we use
# `Model = get_model('app', 'Model')` instead.
app_config = apps.get_app_config(app_label)
# `app_config.import_models()` cannot be used here because it
# would interfere with `apps.populate()`.
import_module("%s.%s" % (app_config.name, "models"))
# In order to account for case-insensitivity of model_name,
# look up the model through a private API of the app registry.
return apps.get_registered_model(app_label, model_name)
else:
# This must be a different case (e.g. the model really doesn't
# exist). We just re-raise the exception.
raise |
<SYSTEM_TASK:>
Main entrypoint for the command-line app.
<END_TASK>
<USER_TASK:>
Description:
def main():
"""
Main entrypoint for the command-line app.
""" |
args = app.parse_args(sys.argv[1:])
params = args.__dict__
params.update(**load_config(args.config_file))
if params['debug']:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig()
try:
imhotep = app.gen_imhotep(**params)
except NoGithubCredentials:
log.error("You must specify a GitHub username or password.")
return False
except NoCommitInfo:
log.error("You must specify a commit or PR number")
return False
except UnknownTools as e:
log.error("Didn't find any of the specified linters.")
log.error("Known linters: %s", ', '.join(e.known))
return False
imhotep.invoke() |
<SYSTEM_TASK:>
Returns contents of the given file, which path is supposed relative
<END_TASK>
<USER_TASK:>
Description:
def read_relative_file(filename):
"""Returns contents of the given file, which path is supposed relative
to this module.""" |
with open(join(dirname(abspath(__file__)), filename)) as f:
return f.read() |
<SYSTEM_TASK:>
Returns a diff as a string from the current HEAD to the given commit.
<END_TASK>
<USER_TASK:>
Description:
def diff_commit(self, commit, compare_point=None):
"""
Returns a diff as a string from the current HEAD to the given commit.
""" |
# @@@ This is a security hazard as compare-point is user-passed in
# data. Doesn't matter until we wrap this in a service.
if compare_point is not None:
self.apply_commit(compare_point)
return self.executor("cd %s && git diff %s" % (self.dirname, commit)) |
<SYSTEM_TASK:>
Return value with given key or index.
<END_TASK>
<USER_TASK:>
Description:
def get(self, key=NOT_SET, index=NOT_SET, d=None):
"""Return value with given key or index.
If no value is found, return d (None by default).
""" |
if index is NOT_SET and key is not NOT_SET:
try:
index, value = self._dict[key]
except KeyError:
return d
else:
return value
elif index is not NOT_SET and key is NOT_SET:
try:
key, value = self._list[index]
except IndexError:
return d
else:
return value
else:
raise KEY_EQ_INDEX_ERROR |
<SYSTEM_TASK:>
Remove an element by key.
<END_TASK>
<USER_TASK:>
Description:
def _pop_key(self, key, has_default):
"""Remove an element by key.""" |
try:
index, value = self._dict.pop(key)
except KeyError:
if has_default:
return None, None
else:
raise
key2, value2 = self._list.pop(index)
assert key is key2
assert value is value2
return index, value |
<SYSTEM_TASK:>
Remove an element by index, or last element.
<END_TASK>
<USER_TASK:>
Description:
def _pop_index(self, index, has_default):
"""Remove an element by index, or last element.""" |
try:
if index is NOT_SET:
index = len(self._list) - 1
key, value = self._list.pop()
else:
key, value = self._list.pop(index)
if index < 0:
index += len(self._list) + 1
except IndexError:
if has_default:
return None, None, None
else:
raise
index2, value2 = self._dict.pop(key)
assert index == index2
assert value is value2
return key, index, value |
<SYSTEM_TASK:>
Pop a specific item quickly by swapping it to the end.
<END_TASK>
<USER_TASK:>
Description:
def fast_pop(self, key=NOT_SET, index=NOT_SET):
"""Pop a specific item quickly by swapping it to the end.
Remove value with given key or index (last item by default) fast
by swapping it to the last place first.
Changes order of the remaining items (item that used to be last goes to
the popped location).
Returns tuple of (poped_value, new_moved_index, moved_key, moved_value).
If key is not found raises KeyError or IndexError.
Runs in O(1).
""" |
if index is NOT_SET and key is not NOT_SET:
index, popped_value = self._dict.pop(key)
elif key is NOT_SET:
if index is NOT_SET:
index = len(self._list) - 1
key, popped_value2 = self._list[-1]
else:
key, popped_value2 = self._list[index]
if index < 0:
index += len(self._list)
index2, popped_value = self._dict.pop(key)
assert index == index2
else:
raise KEY_AND_INDEX_ERROR
if key == self._list[-1][0]:
# The item we're removing happens to be the last in the list,
# no swapping needed
_, popped_value2 = self._list.pop()
assert popped_value is popped_value2
return popped_value, len(self._list), key, popped_value
else:
# Swap the last item onto the deleted spot and
# pop the last item from the list
self._list[index] = self._list[-1]
moved_key, moved_value = self._list.pop()
self._dict[moved_key] = (index, moved_value)
return popped_value, index, moved_key, moved_value |
<SYSTEM_TASK:>
Try to get the tags without any authentication, this does work only for
<END_TASK>
<USER_TASK:>
Description:
def get_all_tags_no_auth(image_name, branch=None):
"""
Try to get the tags without any authentication, this does work only for
public images.
GET /v1/repositories/<namespace>/<repository_name>/tags
:param image_name: The docker image name
:param branch: The branch to filter by
:return: A list of Version instances, latest first
""" |
output = []
logging.debug('Getting %s without authentication' % image_name)
spec = '/%s/tags' % image_name
headers = {'Accept': 'application/json',
'Content-Type': 'application/json'}
try:
# This works well for any public images:
response = requests.get(API_URL + spec, headers=headers)
except RequestException, re:
raise DockerTagNamingException('HTTP request exception "%s"' % re)
if response.status_code == 401:
msg = ('Received unexpected status code %s from the registry'
' REST API, the image is private.')
raise AuthException(msg % response.status_code)
if response.status_code != 200:
msg = ('Received unexpected status code %s from the registry'
' REST API, the image might not exist')
raise DockerTagNamingException(msg % response.status_code)
try:
json_data = response.json()
except ValueError:
msg = 'JSON decode failed! Raw data is: "%s". Please report a bug.'
raise DockerTagNamingException(msg % (response.content[:25]).strip())
try:
tag_names = [tag_info['name'] for tag_info in json_data]
except Exception:
msg = ('The JSON data does not contain the expected format!'
' Raw data is: "%s". Please report a bug.')
raise DockerTagNamingException(msg % (response.content[:25]).strip())
for tag_name in tag_names:
try:
version = version_parser(tag_name)
except Exception, e:
msg = 'Ignoring version tag "%s" with incorrect format: "%s"'
logging.debug(msg % (tag_name, e))
continue
if branch is not None:
if version.branch != branch:
continue
output.append(version)
def sort_func(version_a, version_b):
return cmp(version_b.version_number, version_a.version_number)
output.sort(sort_func)
return output |
<SYSTEM_TASK:>
Start publishing MySQL row-based binlog events to blinker signals
<END_TASK>
<USER_TASK:>
Description:
def start_publishing(mysql_settings, **kwargs):
"""Start publishing MySQL row-based binlog events to blinker signals
Args:
mysql_settings (dict): information to connect to mysql via pymysql
**kwargs: The additional kwargs will be passed to
:py:class:`pymysqlreplication.BinLogStreamReader`.
""" |
_logger.info('Start publishing from %s with:\n%s'
% (mysql_settings, kwargs))
kwargs.setdefault('server_id', random.randint(1000000000, 4294967295))
kwargs.setdefault('freeze_schema', True)
# connect to binlog stream
stream = pymysqlreplication.BinLogStreamReader(
mysql_settings,
only_events=[row_event.DeleteRowsEvent,
row_event.UpdateRowsEvent,
row_event.WriteRowsEvent],
**kwargs
)
""":type list[RowsEvent]"""
for event in stream:
# ignore non row events
if not isinstance(event, row_event.RowsEvent):
continue
_logger.debug('Send binlog signal "%s@%s.%s"' % (
event.__class__.__name__,
event.schema,
event.table
))
signals.binlog_signal.send(event, stream=stream)
signals.binlog_position_signal.send((stream.log_file, stream.log_pos)) |
<SYSTEM_TASK:>
Runs an arbitrary HTML string through Tidy.
<END_TASK>
<USER_TASK:>
Description:
def tidyHTML(dirtyHTML):
"""
Runs an arbitrary HTML string through Tidy.
""" |
try:
from tidylib import tidy_document
except ImportError as e:
raise ImportError(("%s\nYou need to install pytidylib.\n" +
"e.g. sudo pip install pytidylib") % e)
options = {
'output-xhtml':1,
#add_xml_decl=1,#option in tidy but not pytidylib
'indent':1,
'tidy-mark':1,
#'char-encoding':'utf8',
'char-encoding':'raw',
}
html, errors = tidy_document(dirtyHTML, options=options)
return html |
<SYSTEM_TASK:>
Generates the cache key for the given string using the content in pattern
<END_TASK>
<USER_TASK:>
Description:
def generate_key(s, pattern="%s.txt"):
"""
Generates the cache key for the given string using the content in pattern
to format the output string
""" |
h = hashlib.sha1()
#h.update(s)
h.update(s.encode('utf-8'))
return pattern % h.hexdigest() |
<SYSTEM_TASK:>
Returns the content of a cache item or the given default
<END_TASK>
<USER_TASK:>
Description:
def cache_get(cache_dir, cache_key, default=None):
"""
Returns the content of a cache item or the given default
""" |
filename = os.path.join(cache_dir, cache_key)
if os.path.isfile(filename):
with open(filename, 'r') as f:
return f.read()
return default |
<SYSTEM_TASK:>
Creates a new cache file in the cache directory
<END_TASK>
<USER_TASK:>
Description:
def cache_set(cache_dir, cache_key, content):
"""
Creates a new cache file in the cache directory
""" |
filename = os.path.join(cache_dir, cache_key)
with open(filename, 'w') as f:
f.write(content) |
<SYSTEM_TASK:>
Returns the cache files mtime or 0 if it does not exists
<END_TASK>
<USER_TASK:>
Description:
def cache_info(cache_dir, cache_key):
"""
Returns the cache files mtime or 0 if it does not exists
""" |
filename = os.path.join(cache_dir, cache_key)
return os.path.getmtime(filename) if os.path.exists(filename) else 0 |
<SYSTEM_TASK:>
Extracts text from a URL.
<END_TASK>
<USER_TASK:>
Description:
def extractFromURL(url,
cache=False,
cacheDir='_cache',
verbose=False,
encoding=None,
filters=None,
userAgent=None,
timeout=5,
blur=5,
ignore_robotstxt=False,
only_mime_types=None,
raw=False):
"""
Extracts text from a URL.
Parameters:
url := string
Remote URL or local filename where HTML will be read.
cache := bool
True=store and retrieve url from cache
False=always retrieve url from the web
cacheDir := str
Directory where cached url contents will be stored.
verbose := bool
True=print logging messages
False=print no output
encoding := string
The encoding of the page contents.
If none given, it will attempt to guess the encoding.
See http://docs.python.org/howto/unicode.html for further info
on Python Unicode and encoding support.
filters := string
Comma-delimited list of filters to apply before parsing.
only_mime_types := list of strings
A list of mime-types to limit parsing to.
If the mime-type of the raw-content retrieved does not match
one of these, a value of None will be returned.
""" |
blur = int(blur)
try:
import chardet
except ImportError as e:
raise ImportError(("%s\nYou need to install chardet.\n" + \
"e.g. sudo pip install chardet") % e)
if only_mime_types and isinstance(only_mime_types, six.text_type):
only_mime_types = only_mime_types.split(',')
# Load url from cache if enabled.
if cache:
if not os.path.isdir(cacheDir):
cache_perms = 488 # 750 in octal, '-rwxr-x---'
os.makedirs(cacheDir, cache_perms)
cache_key = generate_key(url)
cached_content = cache_get(cacheDir, cache_key)
if cached_content:
return cached_content
if not ignore_robotstxt:
if not check_robotstxt(url, cache, cacheDir, userAgent=userAgent):
if verbose: print("Request denied by robots.txt")
return ''
# Otherwise download the url.
if verbose: print('Reading %s...' % url)
html = fetch(
url,
timeout=timeout,
userAgent=userAgent,
only_mime_types=only_mime_types)
if not html:
return ''
# If no encoding guess given, then attempt to determine
# encoding automatically.
if not encoding:
if isinstance(html, unicode):
html = html.encode('utf8', 'replace')
encoding_opinion = chardet.detect(html)
encoding = encoding_opinion['encoding']
if verbose: print('Using encoding %s.' % encoding)
# Save raw contents to cache if enabled.
if verbose: print('Read %i characters.' % len(html))
if cache:
raw_key = generate_key(url, "%s.raw")
cache_set(cacheDir, raw_key, html)
# Apply filters.
if filters:
filter_names = map(str.strip, filters.split(','))
for filter_name in filter_names:
fltr = get_filter(filter_name)
html = fltr(html)
# Clean up HTML.
html = tidyHTML(html)
if verbose: print('Extracted %i characters.' % len(html))
# Convert to Unicode.
if not html:
return ''
html = unicode(html, encoding=encoding, errors='replace')
if raw:
return html
# Extract text from HTML.
res = extractFromHTML(html, blur=blur)
assert isinstance(res, unicode)
# Save extracted text to cache if enabled.
res = res.encode(encoding, 'ignore')
if cache:
cache_set(cacheDir, cache_key, res)
return res |
<SYSTEM_TASK:>
Create a shallow copy of self.
<END_TASK>
<USER_TASK:>
Description:
def copy(self):
"""Create a shallow copy of self.
This runs in O(len(self.num_unique_elements()))
""" |
out = self._from_iterable(None)
out._dict = self._dict.copy()
out._size = self._size
return out |
<SYSTEM_TASK:>
List the n most common elements and their counts.
<END_TASK>
<USER_TASK:>
Description:
def nlargest(self, n=None):
"""List the n most common elements and their counts.
List is from the most
common to the least. If n is None, the list all element counts.
Run time should be O(m log m) where m is len(self)
Args:
n (int): The number of elements to return
""" |
if n is None:
return sorted(self.counts(), key=itemgetter(1), reverse=True)
else:
return heapq.nlargest(n, self.counts(), key=itemgetter(1)) |
<SYSTEM_TASK:>
Create a bag from a dict of elem->count.
<END_TASK>
<USER_TASK:>
Description:
def from_mapping(cls, mapping):
"""Create a bag from a dict of elem->count.
Each key in the dict is added if the value is > 0.
Raises:
ValueError: If any count is < 0.
""" |
out = cls()
for elem, count in mapping.items():
out._set_count(elem, count)
return out |
<SYSTEM_TASK:>
Check that every element in self has a count <= in other.
<END_TASK>
<USER_TASK:>
Description:
def is_subset(self, other):
"""Check that every element in self has a count <= in other.
Args:
other (Set)
""" |
if isinstance(other, _basebag):
for elem, count in self.counts():
if not count <= other.count(elem):
return False
else:
for elem in self:
if self.count(elem) > 1 or elem not in other:
return False
return True |
<SYSTEM_TASK:>
Add all of the elements of other to self.
<END_TASK>
<USER_TASK:>
Description:
def _iadd(self, other):
"""Add all of the elements of other to self.
if isinstance(it, _basebag):
This runs in O(it.num_unique_elements())
else:
This runs in O(len(it))
""" |
if isinstance(other, _basebag):
for elem, count in other.counts():
self._increment_count(elem, count)
else:
for elem in other:
self._increment_count(elem, 1)
return self |
<SYSTEM_TASK:>
Set multiplicity of each element to the minimum of the two collections.
<END_TASK>
<USER_TASK:>
Description:
def _iand(self, other):
"""Set multiplicity of each element to the minimum of the two collections.
if isinstance(other, _basebag):
This runs in O(other.num_unique_elements())
else:
This runs in O(len(other))
""" |
# TODO do we have to create a bag from the other first?
if not isinstance(other, _basebag):
other = self._from_iterable(other)
for elem, old_count in set(self.counts()):
other_count = other.count(elem)
new_count = min(other_count, old_count)
self._set_count(elem, new_count)
return self |
<SYSTEM_TASK:>
Set multiplicity of each element to the maximum of the two collections.
<END_TASK>
<USER_TASK:>
Description:
def _ior(self, other):
"""Set multiplicity of each element to the maximum of the two collections.
if isinstance(other, _basebag):
This runs in O(other.num_unique_elements())
else:
This runs in O(len(other))
""" |
# TODO do we have to create a bag from the other first?
if not isinstance(other, _basebag):
other = self._from_iterable(other)
for elem, other_count in other.counts():
old_count = self.count(elem)
new_count = max(other_count, old_count)
self._set_count(elem, new_count)
return self |
<SYSTEM_TASK:>
Set self to the symmetric difference between the sets.
<END_TASK>
<USER_TASK:>
Description:
def _ixor(self, other):
"""Set self to the symmetric difference between the sets.
if isinstance(other, _basebag):
This runs in O(other.num_unique_elements())
else:
This runs in O(len(other))
""" |
if isinstance(other, _basebag):
for elem, other_count in other.counts():
count = abs(self.count(elem) - other_count)
self._set_count(elem, count)
else:
# Let a = self.count(elem) and b = other.count(elem)
# if a >= b then elem is removed from self b times leaving a - b
# if a < b then elem is removed from self a times then added (b - a)
# times leaving a - a + (b - a) = b - a
for elem in other:
try:
self._increment_count(elem, -1)
except ValueError:
self._increment_count(elem, 1)
return self |
<SYSTEM_TASK:>
Discard the elements of other from self.
<END_TASK>
<USER_TASK:>
Description:
def _isub(self, other):
"""Discard the elements of other from self.
if isinstance(it, _basebag):
This runs in O(it.num_unique_elements())
else:
This runs in O(len(it))
""" |
if isinstance(other, _basebag):
for elem, other_count in other.counts():
try:
self._increment_count(elem, -other_count)
except ValueError:
self._set_count(elem, 0)
else:
for elem in other:
try:
self._increment_count(elem, -1)
except ValueError:
pass
return self |
<SYSTEM_TASK:>
Remove all of the elems from other.
<END_TASK>
<USER_TASK:>
Description:
def remove_all(self, other):
"""Remove all of the elems from other.
Raises a ValueError if the multiplicity of any elem in other is greater
than in self.
""" |
if not self.is_superset(other):
raise ValueError('Passed collection is not a subset of this bag')
self.discard_all(other) |
<SYSTEM_TASK:>
Run ``git ls-files`` in the top-level project directory. Arguments go
<END_TASK>
<USER_TASK:>
Description:
def git_ls_files(*cmd_args):
"""Run ``git ls-files`` in the top-level project directory. Arguments go
directly to execution call.
:return: set of file names
:rtype: :class:`set`
""" |
cmd = ['git', 'ls-files']
cmd.extend(cmd_args)
return set(subprocess.check_output(cmd).splitlines()) |
<SYSTEM_TASK:>
Login v2ex, otherwise we can't complete the mission.
<END_TASK>
<USER_TASK:>
Description:
def login(self):
"""Login v2ex, otherwise we can't complete the mission.""" |
response = self.session.get(self.signin_url, verify=False)
user_param, password_param = self._get_hashed_params(response.text)
login_data = {
user_param: self.config['username'],
password_param: self.config['password'],
'once': self._get_once(response.text),
'next': '/'
}
headers = {'Referer': 'https://www.v2ex.com/signin'}
self.session.post(self.signin_url, headers=headers, data=login_data) |
<SYSTEM_TASK:>
Get once which will be used when you login.
<END_TASK>
<USER_TASK:>
Description:
def _get_once(self, page_text):
"""Get once which will be used when you login.""" |
soup = BeautifulSoup(page_text, 'html.parser')
once = soup.find('input', attrs={'name': 'once'})['value']
return once |
<SYSTEM_TASK:>
Complete daily mission then get the money.
<END_TASK>
<USER_TASK:>
Description:
def get_money(self):
"""Complete daily mission then get the money.""" |
response = self.session.get(self.mission_url, verify=False)
soup = BeautifulSoup(response.text, 'html.parser')
onclick = soup.find('input', class_='super normal button')['onclick']
url = onclick.split('=', 1)[1][2:-2]
if url == '/balance':
return "You have completed the mission today."
else:
headers = {'Referer': 'https://www.v2ex.com/mission/daily'}
data = {'once': url.split('=')[-1]}
self.session.get('https://www.v2ex.com'+url, verify=False,
headers=headers, data=data)
balance = self._get_balance()
return balance |
<SYSTEM_TASK:>
Get to know how much you totally have and how much you get today.
<END_TASK>
<USER_TASK:>
Description:
def _get_balance(self):
"""Get to know how much you totally have and how much you get today.""" |
response = self.session.get(self.balance_url, verify=False)
soup = BeautifulSoup(response.text, 'html.parser')
first_line = soup.select(
"table.data tr:nth-of-type(2)")[0].text.strip().split('\n')
total, today = first_line[-2:]
logging.info('%-26sTotal:%-8s', today, total)
return '\n'.join([u"Today: {0}".format(today),
"Total: {0}".format(total)]) |
<SYSTEM_TASK:>
Get to know how long you have kept signing in.
<END_TASK>
<USER_TASK:>
Description:
def get_last(self):
"""Get to know how long you have kept signing in.""" |
response = self.session.get(self.mission_url, verify=False)
soup = BeautifulSoup(response.text, 'html.parser')
last = soup.select('#Main div')[-1].text
return last |
<SYSTEM_TASK:>
Save current position into file
<END_TASK>
<USER_TASK:>
Description:
def _save_file_and_pos(self):
""" Save current position into file
""" |
if not self._pos_changed:
return
with open(self.pos_storage_filename, 'w+') as f:
_pos = '%s:%s' % (self._log_file, self._log_pos)
_logger.debug('Saving position %s to file %s'
% (_pos, self.pos_storage_filename))
f.write(_pos)
self._pos_changed = False |
<SYSTEM_TASK:>
Read last position from file, store as current position
<END_TASK>
<USER_TASK:>
Description:
def _read_file_and_pos(self):
""" Read last position from file, store as current position
""" |
try:
with open(self.pos_storage_filename, 'r+') as f:
_pos = f.read()
_logger.debug('Got position "%s" from file %s'
% (_pos, self.pos_storage_filename))
if not _pos:
return
log_file, log_pos = _pos.split(':')
try:
log_file = str(log_file)
log_pos = int(log_pos)
except (ValueError, TypeError) as e:
_logger.critical('Can not read position: %s' % e)
sys.exit(13)
self._log_file = log_file
self._log_pos = log_pos
except IOError as e:
_logger.error(e) |
<SYSTEM_TASK:>
Return the index of value between start and end.
<END_TASK>
<USER_TASK:>
Description:
def index(self, value, start=0, end=None):
"""Return the index of value between start and end.
By default, the entire setlist is searched.
This runs in O(1)
Args:
value: The value to find the index of
start (int): The index to start searching at (defaults to 0)
end (int): The index to stop searching at (defaults to the end of the list)
Returns:
int: The index of the value
Raises:
ValueError: If the value is not in the list or outside of start - end
IndexError: If start or end are out of range
""" |
try:
index = self._dict[value]
except KeyError:
raise ValueError
else:
start = self._fix_neg_index(start)
end = self._fix_end_index(end)
if start <= index and index < end:
return index
else:
raise ValueError |
<SYSTEM_TASK:>
Return the index of a subsequence.
<END_TASK>
<USER_TASK:>
Description:
def sub_index(self, sub, start=0, end=None):
"""Return the index of a subsequence.
This runs in O(len(sub))
Args:
sub (Sequence): An Iterable to search for
Returns:
int: The index of the first element of sub
Raises:
ValueError: If sub isn't a subsequence
TypeError: If sub isn't iterable
IndexError: If start or end are out of range
""" |
start_index = self.index(sub[0], start, end)
end = self._fix_end_index(end)
if start_index + len(sub) > end:
raise ValueError
for i in range(1, len(sub)):
if sub[i] != self[start_index + i]:
raise ValueError
return start_index |
<SYSTEM_TASK:>
Remove and return the item at index.
<END_TASK>
<USER_TASK:>
Description:
def pop(self, index=-1):
"""Remove and return the item at index.""" |
value = self._list.pop(index)
del self._dict[value]
return value |
<SYSTEM_TASK:>
Insert value at index.
<END_TASK>
<USER_TASK:>
Description:
def insert(self, index, value):
"""Insert value at index.
Args:
index (int): Index to insert value at
value: Value to insert
Raises:
ValueError: If value already in self
IndexError: If start or end are out of range
""" |
if value in self:
raise ValueError
index = self._fix_neg_index(index)
self._dict[value] = index
for elem in self._list[index:]:
self._dict[elem] += 1
self._list.insert(index, value) |
<SYSTEM_TASK:>
Remove value from self.
<END_TASK>
<USER_TASK:>
Description:
def remove(self, value):
"""Remove value from self.
Args:
value: Element to remove from self
Raises:
ValueError: if element is already present
""" |
try:
index = self._dict[value]
except KeyError:
raise ValueError('Value "%s" is not present.')
else:
del self[index] |
<SYSTEM_TASK:>
Update self to include only the difference with other.
<END_TASK>
<USER_TASK:>
Description:
def difference_update(self, other):
"""Update self to include only the difference with other.""" |
other = set(other)
indices_to_delete = set()
for i, elem in enumerate(self):
if elem in other:
indices_to_delete.add(i)
if indices_to_delete:
self._delete_values_by_index(indices_to_delete) |
<SYSTEM_TASK:>
Update self to include only the symmetric difference with other.
<END_TASK>
<USER_TASK:>
Description:
def symmetric_difference_update(self, other):
"""Update self to include only the symmetric difference with other.""" |
other = setlist(other)
indices_to_delete = set()
for i, item in enumerate(self):
if item in other:
indices_to_delete.add(i)
for item in other:
self.add(item)
self._delete_values_by_index(indices_to_delete) |
<SYSTEM_TASK:>
Sort this setlist in place.
<END_TASK>
<USER_TASK:>
Description:
def sort(self, *args, **kwargs):
"""Sort this setlist in place.""" |
self._list.sort(*args, **kwargs)
for index, value in enumerate(self._list):
self._dict[value] = index |
<SYSTEM_TASK:>
Swap the values at indices i & j.
<END_TASK>
<USER_TASK:>
Description:
def swap(self, i, j):
"""Swap the values at indices i & j.
.. versionadded:: 1.1
""" |
i = self._fix_neg_index(i)
j = self._fix_neg_index(j)
self._list[i], self._list[j] = self._list[j], self._list[i]
self._dict[self._list[i]] = i
self._dict[self._list[j]] = j |
<SYSTEM_TASK:>
Get updated values from 2 dicts of values
<END_TASK>
<USER_TASK:>
Description:
def _get_updated_values(before_values, after_values):
""" Get updated values from 2 dicts of values
Args:
before_values (dict): values before update
after_values (dict): values after update
Returns:
dict: a diff dict with key is field key, value is tuple of
(before_value, after_value)
""" |
assert before_values.keys() == after_values.keys()
return dict([(k, [before_values[k], after_values[k]])
for k in before_values.keys()
if before_values[k] != after_values[k]]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.