text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Row(self):
""" The class for a row in this list. """ |
if not hasattr(self, '_row_class'):
attrs = {'fields': self.fields, 'list': self, 'opener': self.opener}
for field in self.fields.values():
attrs[field.name] = field.descriptor
self._row_class = type('SharePointListRow', (SharePointListRow,), attrs)
r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append(self, row):
""" Appends a row to the list. Takes a dictionary, returns a row. """ |
if isinstance(row, dict):
row = self.Row(row)
elif isinstance(row, self.Row):
pass
elif isinstance(row, SharePointListRow):
raise TypeError("row must be a dict or an instance of SharePointList.Row, not SharePointListRow")
else:
raise TypeE... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(self, row):
""" Removes the row from the list. """ |
self._rows.remove(row)
self._deleted_rows.add(row) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self):
""" Updates the list with changes. """ |
# Based on the documentation at
# http://msdn.microsoft.com/en-us/library/lists.lists.updatelistitems%28v=office.12%29.aspx
# Note, this ends up un-namespaced. SharePoint doesn't care about
# namespaces on this XML node, and will bork if any of these elements
# have a namespace... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_batch_method(self):
""" Returns a change batch for SharePoint's UpdateListItems operation. """ |
if not self._changed:
return None
batch_method = E.Method(Cmd='Update' if self.id else 'New')
batch_method.append(E.Field(text_type(self.id) if self.id else 'New',
Name='ID'))
for field in self.fields.values():
if field.name i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_to_python(self, xmlrpc=None):
"""
Extracts a value for the field from an XML-RPC response.
""" |
if xmlrpc:
return xmlrpc.get(self.name, self.default)
elif self.default:
return self.default
else:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_outputs(self, input_value):
"""
Generate a set of output values for a given input.
""" |
output_value = self.convert_to_xmlrpc(input_value)
output = {}
for name in self.output_names:
output[name] = output_value
return output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def struct(self):
"""
XML-RPC-friendly representation of the current object state
""" |
data = {}
for var, fmap in self._def.items():
if hasattr(self, var):
data.update(fmap.get_outputs(getattr(self, var)))
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_args(self, client):
"""
Builds final set of XML-RPC method arguments based on
the method's arguments, any default arguments, and their
defined respec... |
default_args = self.default_args(client)
if self.method_args or self.optional_args:
optional_args = getattr(self, 'optional_args', tuple())
args = []
for arg in (self.method_args + optional_args):
if hasattr(self, arg):
ob... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_result(self, raw_result):
"""
Performs actions on the raw result from the XML-RPC response.
If a `results_class` is defined, the response will b... |
if self.results_class and raw_result:
if isinstance(raw_result, dict_type):
return self.results_class(raw_result)
elif isinstance(raw_result, collections.Iterable):
return [self.results_class(result) for result in raw_result]
return raw_re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def parse(self, text):
'''Returns a list of addresses found in text
together with parsed address parts
'''
results = []
if isinstance(text, str):
if six.PY2:
text = unicode(text, 'utf-8')
self.clean_text = self._normalize_string(text)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _parse_address(self, address_string):
'''Parses address into parts'''
match = utils.match(self.rules, address_string, flags=re.VERBOSE | re.U)
if match:
match_as_dict = match.groupdict()
match_as_dict.update({'country_id': self.country})
# combine results
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _get_addresses(self, text):
'''Returns a list of addresses found in text'''
# find addresses
addresses = []
matches = utils.findall(
self.rules,
text,
flags=re.VERBOSE | re.U)
if(matches):
for match in matches:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(some_text, **kwargs):
"""Creates request to AddressParser and returns list of Address objects """ |
ap = parser.AddressParser(**kwargs)
return ap.parse(some_text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setAttribute(values, value):
""" Takes the values of an attribute value list and attempts to append attributes of the proper type, inferred from their Python... |
if isinstance(value, int):
values.add().int32_value = value
elif isinstance(value, float):
values.add().double_value = value
elif isinstance(value, long):
values.add().int64_value = value
elif isinstance(value, str):
values.add().string_value = value
elif isinstance(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deepSetAttr(obj, path, val):
""" Sets a deep attribute on an object by resolving a dot-delimited path. If path does not exist an `AttributeError` will be rai... |
first, _, rest = path.rpartition('.')
return setattr(deepGetAttr(obj, first) if first else obj, rest, val) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convertDatetime(t):
""" Converts the specified datetime object into its appropriate protocol value. This is the number of milliseconds from the epoch. """ |
epoch = datetime.datetime.utcfromtimestamp(0)
delta = t - epoch
millis = delta.total_seconds() * 1000
return int(millis) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getValueFromValue(value):
""" Extract the currently set field from a Value structure """ |
if type(value) != common.AttributeValue:
raise TypeError(
"Expected an AttributeValue, but got {}".format(type(value)))
if value.WhichOneof("value") is None:
raise AttributeError("Nothing set for {}".format(value))
return getattr(value, value.WhichOneof("value")) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def toJson(protoObject, indent=None):
""" Serialises a protobuf object as json """ |
# Using the internal method because this way we can reformat the JSON
js = json_format.MessageToDict(protoObject, False)
return json.dumps(js, indent=indent) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getProtocolClasses(superclass=message.Message):
""" Returns all the protocol classes that are subclasses of the specified superclass. Only 'leaf' classes are... |
# We keep a manual list of the superclasses that we define here
# so we can filter them out when we're getting the protocol
# classes.
superclasses = set([message.Message])
thisModule = sys.modules[__name__]
subclasses = []
for name, class_ in inspect.getmembers(thisModule):
if ((in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def runCommandSplits(splits, silent=False, shell=False):
""" Run a shell command given the command's parsed command line """ |
try:
if silent:
with open(os.devnull, 'w') as devnull:
subprocess.check_call(
splits, stdout=devnull, stderr=devnull, shell=shell)
else:
subprocess.check_call(splits, shell=shell)
except OSError as exception:
if exception.errno... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _createSchemaFiles(self, destPath, schemasPath):
""" Create a hierarchy of proto files in a destination directory, copied from the schemasPath hierarchy """ |
# Create the target directory hierarchy, if neccessary
ga4ghPath = os.path.join(destPath, 'ga4gh')
if not os.path.exists(ga4ghPath):
os.mkdir(ga4ghPath)
ga4ghSchemasPath = os.path.join(ga4ghPath, 'schemas')
if not os.path.exists(ga4ghSchemasPath):
os.mkdi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _doLineReplacements(self, line):
""" Given a line of a proto file, replace the line with one that is appropriate for the hierarchy that we want to compile ""... |
# ga4gh packages
packageString = 'package ga4gh;'
if packageString in line:
return line.replace(
packageString,
'package ga4gh.schemas.ga4gh;')
importString = 'import "ga4gh/'
if importString in line:
return line.replace(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _copySchemaFile(self, src, dst):
""" Copy a proto file to the temporary directory, with appropriate line replacements """ |
with open(src) as srcFile, open(dst, 'w') as dstFile:
srcLines = srcFile.readlines()
for srcLine in srcLines:
toWrite = self._doLineReplacements(srcLine)
dstFile.write(toWrite) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_protodef_to_editable(proto):
""" Protobuf objects can't have arbitrary fields addedd and we need to later on add comments to them, so we instead make... |
class Editable(object):
def __init__(self, prot):
self.kind = type(prot)
self.name = prot.name
self.comment = ""
self.options = dict([(key.name, value) for (key, value) in prot.options.ListFields()])
if isinstance(prot, EnumDescriptorProto):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def haversine(point1, point2, unit='km'):
""" Calculate the great-circle distance between two points on the Earth surface. :input: two 2-tuples, containing the l... |
# mean earth radius - https://en.wikipedia.org/wiki/Earth_radius#Mean_radius
AVG_EARTH_RADIUS_KM = 6371.0088
# Units values taken from http://www.unitconversion.org/unit_converter/length.html
conversions = {'km': 1,
'm': 1000,
'mi': 0.621371192,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
""" Retrieve run folder paths from the command line Ensure only metrics required for summary are loaded Load the run metrics Calculate the summary me... |
logging.basicConfig(level=logging.INFO)
run_metrics = py_interop_run_metrics.run_metrics()
summary = py_interop_summary.run_summary()
valid_to_load = py_interop_run.uchar_vector(py_interop_run.MetricCount, 0)
py_interop_run_metrics.list_summary_metrics_to_load(valid_to_load)
for run_folder_p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def gen_csv(sc, filename, field_list, source, filters):
'''csv SecurityCenterObj, AssetListName, CSVFields, EmailAddress
'''
# First thing we need to do is initialize the csvfile and build the header
# for the file.
datafile = open(filename, 'wb')
csvfile = csv.writer(datafile)
header = []
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def login(self, user, passwd):
'''Logs the user into SecurityCenter and stores the needed token and cookies.'''
resp = self.post('token', json={'username': user, 'password': passwd})
self._token = resp.json()['response']['token'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def download_scans(sc, age=0, unzip=False, path='scans'):
'''Scan Downloader
Here we will attempt to download all of the scans that have completed between
now and AGE days ago.
sc = SecurityCenter5 object
age = how many days back do we want to pull? (default: 0)
unzip = Do we want to uncompress... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def update(sc, filename, asset_id):
'''
Updates a DNS Asset List with the contents of the filename. The assumed
format of the file is 1 entry per line. This function will convert the
file contents into an array of entries and then upload that array into
SecurityCenter.
'''
addresses = []
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def generate_html_report(base_path, asset_id):
'''
Generates the HTML report and dumps it into the specified filename
'''
jenv = Environment(loader=PackageLoader('swchange', 'templates'))
s = Session()
#hosts = s.query(Host).filter_by(asset_id=asset_id).all()
asset = s.query(AssetList).filte... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def gen_csv(sc, filename):
'''csv SecurityCenterObj, EmailAddress
'''
# First thing we need to do is initialize the csvfile and build the header
# for the file.
datafile = open(filename, 'wb')
csvfile = csv.writer(datafile)
csvfile.writerow(['Software Package Name', 'Count'])
debug.wri... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def download(sc, age=0, path='reports', **args):
'''Report Downloader
The report downloader will pull reports down from SecurityCenter
based on the conditions provided to the path provided.
sc = SecurityCenter5 object
age = number of days old the report may be to be included in the
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def post(self, path, **kwargs):
'''Calls the specified path with the POST method'''
resp = self._session.post(self._url(path), **self._builder(**kwargs))
if 'stream' in kwargs:
return resp
else:
return self._resp_error_check(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def import_repo(self, repo_id, fileobj):
'''
Imports a repository package using the repository ID specified.
'''
# Step 1, lets upload the file
filename = self.upload(fileobj).json()['response']['filename']
# Step 2, lets tell SecurityCenter what to do with the file
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _revint(self, version):
'''
Internal function to convert a version string to an integer.
'''
intrev = 0
vsplit = version.split('.')
for c in range(len(vsplit)):
item = int(vsplit[c]) * (10 ** (((len(vsplit) - c - 1) * 2)))
intrev += item
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _revcheck(self, func, version):
'''
Internal function to see if a version is func than what we have
determined to be talking to. This is very useful for newer API calls
to make sure we don't accidentally make a call to something that
doesnt exist.
'''
current... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _build_xrefs(self):
'''
Internal function to populate the xrefs list with the external
references to be used in searching plugins and potentially
other functions as well.
'''
xrefs = set()
plugins = self.plugins()
for plugin in plugins:
fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login(self, user, passwd):
"""login user passwd Performs the login operation for Security Center, storing the token that Security Center has generated for th... |
data = self.raw_query('auth', 'login',
data={'username': user, 'password': passwd})
self._token = data["token"]
self._user = data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def credential_add(self, name, cred_type, **options):
'''
Adds a new credential into SecurityCenter. As credentials can be of
multiple types, we have different options to specify for each type of
credential.
**Global Options (Required)**
:param name: Unique name to be ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def credential_delete_simulate(self, *ids):
"""Show the relationships and dependencies for one or more credentials. :param ids: one or more credential ids """ |
return self.raw_query("credential", "deleteSimulate", data={
"credentials": [{"id": str(id)} for id in ids]
}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def credential_delete(self, *ids):
"""Delete one or more credentials. :param ids: one or more credential ids """ |
return self.raw_query("credential", "delete", data={
"credentials": [{"id": str(id)} for id in ids]
}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plugins(self, plugin_type='all', sort='id', direction='asc', size=1000, offset=0, all=True, loops=0, since=None, **filterset):
"""plugins Returns a list of o... |
plugins = []
# First we need to generate the basic payload that we will be augmenting
# to build the
payload = {
'size': size,
'offset': offset,
'type': plugin_type,
'sortField': sort,
'sortDirection': direction.upper(),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plugin_counts(self):
"""plugin_counts Returns the plugin counts as dictionary with the last updated info if its available. """ |
ret = {
'total': 0,
}
# As ususal, we need data before we can actually do anything ;)
data = self.raw_query('plugin', 'init')
# For backwards compatability purposes, we will be handling this a bit
# differently than I would like. We are going to check to s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ip_info(self, ip, repository_ids=None):
"""ip_info Returns information about the IP specified in the repository ids defined. """ |
if not repository_ids:
repository_ids = []
repos = []
for rid in repository_ids:
repos.append({'id': rid})
return self.raw_query('vuln', 'getIP', data={
'ip': ip, 'repositories': repos}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scan_list(self, start_time=None, end_time=None, **kwargs):
"""List scans stored in Security Center in a given time range. Time is given in UNIX timestamps, a... |
try:
end_time = datetime.utcfromtimestamp(int(end_time))
except TypeError:
if end_time is None:
end_time = datetime.utcnow()
try:
start_time = datetime.utcfromtimestamp(int(start_time))
except TypeError:
if start_time is ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dashboard_import(self, name, fileobj):
"""dashboard_import Dashboard_Name, filename Uploads a dashboard template to the current user's dashboard tabs. UN-DOC... |
data = self._upload(fileobj)
return self.raw_query('dashboard', 'importTab', data={
'filename': data['filename'],
'name': name,
}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def report_import(self, name, filename):
"""report_import Report_Name, filename Uploads a report template to the current user's reports UN-DOCUMENTED CALL: This ... |
data = self._upload(filename)
return self.raw_query('report', 'import', data={
'filename': data['filename'],
'name': name,
}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def asset_create(self, name, items, tag='', description='', atype='static'):
'''asset_create_static name, ips, tags, description
Create a new asset list with the defined information.
UN-DOCUMENTED CALL: This function is not considered stable.
:param name: asset list name (must be uniqu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def asset_create_combo(self, name, combo, tag='', description=''):
'''asset_create_combo name, combination, tag, description
Creates a new combination asset list. Operands can be either asset list
IDs or be a nested combination asset list.
UN-DOCUMENTED CALL: This function is not consi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def risk_rule(self, rule_type, rule_value, port, proto, plugin_id,
repo_ids, comment='', expires='-1', severity=None):
'''accept_risk rule_type, rule_value, port, proto, plugin_id, comment
Creates an accept rick rule based on information provided.
UN-DOCUMENTED CALL: This func... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def group_add(self, name, restrict, repos, lces=[], assets=[], queries=[],
policies=[], dashboards=[], credentials=[], description=''):
'''group_add name, restrict, repos
'''
return self.raw_query('group', 'add', data={
'lces': [{'id': i} for i in lces],
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_geo_info(filename, band=1):
''' Gets information from a Raster data set
'''
sourceds = gdal.Open(filename, GA_ReadOnly)
ndv = sourceds.GetRasterBand(band).GetNoDataValue()
xsize = sourceds.RasterXSize
ysize = sourceds.RasterYSize
geot = sourceds.GetGeoTransform()
projection = osr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def create_geotiff(name, Array, driver, ndv, xsize, ysize, geot, projection, datatype, band=1):
'''
Creates new geotiff from array
'''
if isinstance(datatype, np.int) == False:
if datatype.startswith('gdal.GDT_') == False:
datatype = eval('gdal.GDT_'+datatype)
newfilename = name+... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_tiff(file):
""" Load a geotiff raster keeping ndv values using a masked array Usage: data = load_tiff(file) """ |
ndv, xsize, ysize, geot, projection, datatype = get_geo_info(file)
data = gdalnumeric.LoadFile(file)
data = np.ma.masked_array(data, mask=data == ndv, fill_value=ndv)
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_file(filename, **kwargs):
""" Create a GeoRaster object from a file """ |
ndv, xsize, ysize, geot, projection, datatype = get_geo_info(filename, **kwargs)
data = gdalnumeric.LoadFile(filename, **kwargs)
data = np.ma.masked_array(data, mask=data == ndv, fill_value=ndv)
return GeoRaster(data, geot, nodata_value=ndv, projection=projection, datatype=datatype) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(self):
"""Returns copy of itself""" |
return GeoRaster(self.raster.copy(), self.geot, nodata_value=self.nodata_value,
projection=self.projection, datatype=self.datatype) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def clip(self, shp, keep=False, *args, **kwargs):
'''
Clip raster using shape, where shape is either a GeoPandas DataFrame, shapefile,
or some other geometry format used by python-raster-stats
Returns list of GeoRasters or Pandas DataFrame with GeoRasters and additional information
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pysal_Gamma(self, **kwargs):
""" Compute Gamma Index of Spatial Autocorrelation for GeoRaster Usage: geo.pysal_Gamma(permutations = 1000, rook=True, operatio... |
if self.weights is None:
self.raster_weights(**kwargs)
rasterf = self.raster.flatten()
rasterf = rasterf[rasterf.mask==False]
self.Gamma = pysal.Gamma(rasterf, self.weights, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pysal_Join_Counts(self, **kwargs):
""" Compute join count statistics for GeoRaster Usage: geo.pysal_Join_Counts(permutations = 1000, rook=True) arguments pas... |
if self.weights is None:
self.raster_weights(**kwargs)
rasterf = self.raster.flatten()
rasterf = rasterf[rasterf.mask==False]
self.Join_Counts = pysal.Join_Counts(rasterf, self.weights, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pysal_Moran(self, **kwargs):
""" Compute Moran's I measure of global spatial autocorrelation for GeoRaster Usage: geo.pysal_Moran(permutations = 1000, rook=T... |
if self.weights is None:
self.raster_weights(**kwargs)
rasterf = self.raster.flatten()
rasterf = rasterf[rasterf.mask==False]
self.Moran = pysal.Moran(rasterf, self.weights, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pysal_Moran_Local(self, **kwargs):
""" Compute Local Moran's I measure of local spatial autocorrelation for GeoRaster Usage: geo.pysal_Moran_Local(permutatio... |
if self.weights is None:
self.raster_weights(**kwargs)
rasterf = self.raster.flatten()
rasterf = rasterf[rasterf.mask==False]
self.Moran_Local = pysal.Moran_Local(rasterf, self.weights, **kwargs)
for i in self.Moran_Local.__dict__.keys():
if (isinstance(g... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mcp(self, *args, **kwargs):
""" Setup MCP_Geometric object from skimage for optimal travel time computations """ |
# Create Cost surface to work on
self.mcp_cost = graph.MCP_Geometric(self.raster, *args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def notify(self, method, params=None):
"""Send a JSON RPC notification to the client. Args: method (str):
The method name of the notification to send params (an... |
log.debug('Sending notification: %s %s', method, params)
message = {
'jsonrpc': JSONRPC_VERSION,
'method': method,
}
if params is not None:
message['params'] = params
self._consumer(message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request(self, method, params=None):
"""Send a JSON RPC request to the client. Args: method (str):
The method name of the message to send params (any):
The ... |
msg_id = self._id_generator()
log.debug('Sending request with id %s: %s %s', msg_id, method, params)
message = {
'jsonrpc': JSONRPC_VERSION,
'id': msg_id,
'method': method,
}
if params is not None:
message['params'] = params
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _cancel_callback(self, request_id):
"""Construct a cancellation callback for the given request ID.""" |
def callback(future):
if future.cancelled():
self.notify(CANCEL_METHOD, {'id': request_id})
future.set_exception(JsonRpcRequestCancelled())
return callback |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def consume(self, message):
"""Consume a JSON RPC message from the client. Args: message (dict):
The JSON RPC message sent by the client """ |
if 'jsonrpc' not in message or message['jsonrpc'] != JSONRPC_VERSION:
log.warn("Unknown message type %s", message)
return
if 'id' not in message:
log.debug("Handling notification from client %s", message)
self._handle_notification(message['method'], mess... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_notification(self, method, params):
"""Handle a notification from the client.""" |
if method == CANCEL_METHOD:
self._handle_cancel_notification(params['id'])
return
try:
handler = self._dispatcher[method]
except KeyError:
log.warn("Ignoring notification for unknown method %s", method)
return
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _notification_callback(method, params):
"""Construct a notification callback for the given request ID.""" |
def callback(future):
try:
future.result()
log.debug("Successfully handled async notification %s %s", method, params)
except Exception: # pylint: disable=broad-except
log.exception("Failed to handle async notification %s %s", method, para... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_cancel_notification(self, msg_id):
"""Handle a cancel notification from the client.""" |
request_future = self._client_request_futures.pop(msg_id, None)
if not request_future:
log.warn("Received cancel notification for unknown message id %s", msg_id)
return
# Will only work if the request hasn't started executing
if request_future.cancel():
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_request(self, msg_id, method, params):
"""Handle a request from the client.""" |
try:
handler = self._dispatcher[method]
except KeyError:
raise JsonRpcMethodNotFound.of(method)
handler_result = handler(params)
if callable(handler_result):
log.debug("Executing async request handler %s", handler_result)
request_future ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _request_callback(self, request_id):
"""Construct a request callback for the given request ID.""" |
def callback(future):
# Remove the future from the client requests map
self._client_request_futures.pop(request_id, None)
if future.cancelled():
future.set_exception(JsonRpcRequestCancelled())
message = {
'jsonrpc': JSONRPC_VERSI... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_response(self, msg_id, result=None, error=None):
"""Handle a response from the client.""" |
request_future = self._server_request_futures.pop(msg_id, None)
if not request_future:
log.warn("Received response to unknown message id %s", msg_id)
return
if error is not None:
log.debug("Received error response to message %s: %s", msg_id, error)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def listen(self, message_consumer):
"""Blocking call to listen for messages on the rfile. Args: message_consumer (fn):
function that is passed each message as i... |
while not self._rfile.closed:
request_str = self._read_message()
if request_str is None:
break
try:
message_consumer(json.loads(request_str.decode('utf-8')))
except ValueError:
log.exception("Failed to parse JSON ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_message(self):
"""Reads the contents of a message. Returns: body of message if parsable else None """ |
line = self._rfile.readline()
if not line:
return None
content_length = self._content_length(line)
# Blindly consume all header lines
while line and line.strip():
line = self._rfile.readline()
if not line:
return None
# Gr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _content_length(line):
"""Extract the content length from an input line.""" |
if line.startswith(b'Content-Length: '):
_, value = line.split(b'Content-Length: ')
value = value.strip()
try:
return int(value)
except ValueError:
raise ValueError("Invalid Content-Length header: {}".format(value))
return... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hostapi_info(index=None):
"""Return a generator with information about each host API. If index is given, only one dictionary for the given host API is return... |
if index is None:
return (hostapi_info(i) for i in range(_pa.Pa_GetHostApiCount()))
else:
info = _pa.Pa_GetHostApiInfo(index)
if not info:
raise RuntimeError("Invalid host API")
assert info.structVersion == 1
return {'name': ffi.string(info.name).decode(error... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def device_info(index=None):
"""Return a generator with information about each device. If index is given, only one dictionary for the given device is returned. "... |
if index is None:
return (device_info(i) for i in range(_pa.Pa_GetDeviceCount()))
else:
info = _pa.Pa_GetDeviceInfo(index)
if not info:
raise RuntimeError("Invalid device")
assert info.structVersion == 2
if 'DirectSound' in hostapi_info(info.hostApi)['name']... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_stream_parameters(kind, device, channels, dtype, latency, samplerate):
"""Generate PaStreamParameters struct.""" |
if device is None:
if kind == 'input':
device = _pa.Pa_GetDefaultInputDevice()
elif kind == 'output':
device = _pa.Pa_GetDefaultOutputDevice()
info = device_info(device)
if channels is None:
channels = info['max_' + kind + '_channels']
dtype = np.dtype(d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _frombuffer(ptr, frames, channels, dtype):
"""Create NumPy array from a pointer to some memory.""" |
framesize = channels * dtype.itemsize
data = np.frombuffer(ffi.buffer(ptr, frames * framesize), dtype=dtype)
data.shape = -1, channels
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self):
"""Commence audio processing. If successful, the stream is considered active. """ |
err = _pa.Pa_StartStream(self._stream)
if err == _pa.paStreamIsNotStopped:
return
self._handle_error(err) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
"""Terminate audio processing. This waits until all pending audio buffers have been played before it returns. If successful, the stream is consid... |
err = _pa.Pa_StopStream(self._stream)
if err == _pa.paStreamIsStopped:
return
self._handle_error(err) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def abort(self):
"""Terminate audio processing immediately. This does not wait for pending audio buffers. If successful, the stream is considered inactive. """ |
err = _pa.Pa_AbortStream(self._stream)
if err == _pa.paStreamIsStopped:
return
self._handle_error(err) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(self, frames, raw=False):
"""Read samples from an input stream. The function does not return until the required number of frames has been read. This may... |
channels, _ = _split(self.channels)
dtype, _ = _split(self.dtype)
data = ffi.new("signed char[]", channels * dtype.itemsize * frames)
self._handle_error(_pa.Pa_ReadStream(self._stream, data, frames))
if not raw:
data = np.frombuffer(ffi.buffer(data), dtype=dtype)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, data):
"""Write samples to an output stream. As much as one blocksize of audio data will be played without blocking. If more than one blocksize w... |
frames = len(data)
_, channels = _split(self.channels)
_, dtype = _split(self.dtype)
if (not isinstance(data, np.ndarray) or data.dtype != dtype):
data = np.array(data, dtype=dtype)
if len(data.shape) == 1:
# play mono signals on all channels
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_shell(self,cfg_file,*args,**options):
"""Command 'supervisord shell' runs the interactive command shell.""" |
args = ("--interactive",) + args
return supervisorctl.main(("-c",cfg_file) + args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_getconfig(self,cfg_file,*args,**options):
"""Command 'supervisor getconfig' prints merged config to stdout.""" |
if args:
raise CommandError("supervisor getconfig takes no arguments")
print cfg_file.read()
return 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_autoreload(self,cfg_file,*args,**options):
"""Command 'supervisor autoreload' watches for code changes. This command provides a simulation of the Dja... |
if args:
raise CommandError("supervisor autoreload takes no arguments")
live_dirs = self._find_live_code_dirs()
reload_progs = self._get_autoreload_programs(cfg_file)
def autoreloader():
"""
Forks a subprocess to make the restart call.
Ot... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_autoreload_programs(self,cfg_file):
"""Get the set of programs to auto-reload when code changes. Such programs will have autoreload=true in their config... |
cfg = RawConfigParser()
cfg.readfp(cfg_file)
reload_progs = []
for section in cfg.sections():
if section.startswith("program:"):
try:
if cfg.getboolean(section,"autoreload"):
reload_progs.append(section.split(":",1)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_live_code_dirs(self):
"""Find all directories in which we might have live python code. This walks all of the currently-imported modules and adds their ... |
live_dirs = []
for mod in sys.modules.values():
# Get the directory containing that module.
# This is deliberately casting a wide net.
try:
dirnm = os.path.dirname(mod.__file__)
except AttributeError:
continue
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_config(data,ctx):
"""Render the given config data using Django's template system. This function takes a config data string and a dict of context varia... |
djsupervisor_tags.current_context = ctx
data = "{% load djsupervisor_tags %}" + data
t = template.Template(data)
c = template.Context(ctx)
return t.render(c).encode("ascii") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_config_from_options(**options):
"""Get config file fragment reflecting command-line options.""" |
data = []
# Set whether or not to daemonize.
# Unlike supervisord, our default is to stay in the foreground.
data.append("[supervisord]\n")
if options.get("daemonize",False):
data.append("nodaemon=false\n")
else:
data.append("nodaemon=true\n")
if options.get("pidfile",None... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def guess_project_dir():
"""Find the top-level Django project directory. This function guesses the top-level Django project directory based on the current enviro... |
projname = settings.SETTINGS_MODULE.split(".",1)[0]
projmod = import_module(projname)
projdir = os.path.dirname(projmod.__file__)
# For Django 1.3 and earlier, the manage.py file was located
# in the same directory as the settings file.
if os.path.isfile(os.path.join(projdir,"manage.py")):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_if_missing(cfg,section,option,value):
"""If the given option is missing, set to the given value.""" |
try:
cfg.get(section,option)
except NoSectionError:
cfg.add_section(section)
cfg.set(section,option,value)
except NoOptionError:
cfg.set(section,option,value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rerender_options(options):
"""Helper function to re-render command-line options. This assumes that command-line options use the same name as their key in the... |
args = []
for name,value in options.iteritems():
name = name.replace("_","-")
if value is None:
pass
elif isinstance(value,bool):
if value:
args.append("--%s" % (name,))
elif isinstance(value,list):
for item in value:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login(self, email=None, password=None, user=None):
""" Logs the user in and setups the header with the private token :param email: Gitlab user Email :param u... |
if user is not None:
data = {'login': user, 'password': password}
elif email is not None:
data = {'email': email, 'password': password}
else:
raise ValueError('Neither username nor email provided to login')
self.headers = {'connection': 'close'}
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getuser(self, user_id):
""" Get info for a user identified by id :param user_id: id of the user :return: False if not found, a dictionary if found """ |
request = requests.get(
'{0}/{1}'.format(self.users_url, user_id),
headers=self.headers, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)
if request.status_code == 200:
return request.json()
else:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deleteuser(self, user_id):
""" Deletes a user. Available only for administrators. This is an idempotent function, calling this function for a non-existent us... |
deleted = self.delete_user(user_id)
if deleted is False:
return False
else:
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def currentuser(self):
""" Returns the current user parameters. The current user is linked to the secret token :return: a list with the current user properties "... |
request = requests.get(
'{0}/api/v3/user'.format(self.host),
headers=self.headers, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)
return request.json() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.