code stringlengths 70 11.9k | docstring stringlengths 4 7.08k | text stringlengths 128 15k |
|---|---|---|
def validate_content(*objs):
from .main import Collection, Module
validator = {
Collection: cnxml.validate_collxml,
Module: cnxml.validate_cnxml,
}[type(objs[0])]
return validator(*[obj.file for obj in objs]) | Runs the correct validator for given `obj`ects. Assumes all same type | ### Input:
Runs the correct validator for given `obj`ects. Assumes all same type
### Response:
def validate_content(*objs):
from .main import Collection, Module
validator = {
Collection: cnxml.validate_collxml,
Module: cnxml.validate_cnxml,
}[type(objs[0])]
return validator(*[obj.file for obj in objs]) |
def copy(self, dest, src):
doc = fragment = deepcopy(self.document)
for token in Pointer(src):
fragment = token.extract(fragment, bypass_ref=True)
return Target(doc).add(dest, fragment) | Copy element from sequence, member from mapping.
:param dest: the destination
:type dest: Pointer
:param src: the source
:type src: Pointer
:return: resolved document
:rtype: Target | ### Input:
Copy element from sequence, member from mapping.
:param dest: the destination
:type dest: Pointer
:param src: the source
:type src: Pointer
:return: resolved document
:rtype: Target
### Response:
def copy(self, dest, src):
doc = fragment = deepcopy(self.document)
for token in Pointer(src):
fragment = token.extract(fragment, bypass_ref=True)
return Target(doc).add(dest, fragment) |
def setChannel(self, channel, wifiInterfaceId=1, timeout=1):
namespace = Wifi.getServiceType("setChannel") + str(wifiInterfaceId)
uri = self.getControlURL(namespace)
self.execute(uri, namespace, "SetChannel", timeout=timeout, NewChannel=channel) | Set the channel of this Wifi interface
:param int channel: the channel number
:param int wifiInterfaceId: the id of the Wifi interface
:param float timeout: the timeout to wait for the action to be executed | ### Input:
Set the channel of this Wifi interface
:param int channel: the channel number
:param int wifiInterfaceId: the id of the Wifi interface
:param float timeout: the timeout to wait for the action to be executed
### Response:
def setChannel(self, channel, wifiInterfaceId=1, timeout=1):
namespace = Wifi.getServiceType("setChannel") + str(wifiInterfaceId)
uri = self.getControlURL(namespace)
self.execute(uri, namespace, "SetChannel", timeout=timeout, NewChannel=channel) |
def send_position_setpoint(self, x, y, z, yaw):
pk = CRTPPacket()
pk.port = CRTPPort.COMMANDER_GENERIC
pk.data = struct.pack(, TYPE_POSITION,
x, y, z, yaw)
self._cf.send_packet(pk) | Control mode where the position is sent as absolute x,y,z coordinate in
meter and the yaw is the absolute orientation.
x and y are in m
yaw is in degrees | ### Input:
Control mode where the position is sent as absolute x,y,z coordinate in
meter and the yaw is the absolute orientation.
x and y are in m
yaw is in degrees
### Response:
def send_position_setpoint(self, x, y, z, yaw):
pk = CRTPPacket()
pk.port = CRTPPort.COMMANDER_GENERIC
pk.data = struct.pack(, TYPE_POSITION,
x, y, z, yaw)
self._cf.send_packet(pk) |
def trigger_actions(self, source, actions):
ret = []
for action in actions:
if isinstance(action, EventListener):
self.log("Registering event listener %r on %r", action, self)
action.once = True
if source.type == CardType.SPELL:
listener = source.controller
else:
listener = source
listener._events.append(action)
else:
ret.append(action.trigger(source))
return ret | Performs a list of `actions` from `source`.
This should seldom be called directly - use `queue_actions` instead. | ### Input:
Performs a list of `actions` from `source`.
This should seldom be called directly - use `queue_actions` instead.
### Response:
def trigger_actions(self, source, actions):
ret = []
for action in actions:
if isinstance(action, EventListener):
self.log("Registering event listener %r on %r", action, self)
action.once = True
if source.type == CardType.SPELL:
listener = source.controller
else:
listener = source
listener._events.append(action)
else:
ret.append(action.trigger(source))
return ret |
def matrix(self, band=1, mask_nan=True):
mat = self.__data[band - 1]
if mat is None:
mat = self.raster.GetRasterBand(band).ReadAsArray()
if mask_nan:
if isinstance(self.nodata, list):
nodata = self.nodata[band - 1]
else:
nodata = self.nodata
try:
mat[mat == nodata] = np.nan
except ValueError:
mat = mat.astype()
mat[mat == nodata] = np.nan
return mat | read a raster band (subset) into a numpy ndarray
Parameters
----------
band: int
the band to read the matrix from; 1-based indexing
mask_nan: bool
convert nodata values to :obj:`numpy.nan`? As :obj:`numpy.nan` requires at least float values, any integer array is cast
to float32.
Returns
-------
numpy.ndarray
the matrix (subset) of the selected band | ### Input:
read a raster band (subset) into a numpy ndarray
Parameters
----------
band: int
the band to read the matrix from; 1-based indexing
mask_nan: bool
convert nodata values to :obj:`numpy.nan`? As :obj:`numpy.nan` requires at least float values, any integer array is cast
to float32.
Returns
-------
numpy.ndarray
the matrix (subset) of the selected band
### Response:
def matrix(self, band=1, mask_nan=True):
mat = self.__data[band - 1]
if mat is None:
mat = self.raster.GetRasterBand(band).ReadAsArray()
if mask_nan:
if isinstance(self.nodata, list):
nodata = self.nodata[band - 1]
else:
nodata = self.nodata
try:
mat[mat == nodata] = np.nan
except ValueError:
mat = mat.astype()
mat[mat == nodata] = np.nan
return mat |
def run3(data, ipyclient, force):
start = time.time()
raws, longbar, cutters, matchdict = prechecks2(data, force)
kbd = 0
try:
progressbar(len(ready), sum(ready), printstr, spacer=spacer)
time.sleep(0.1)
if async.ready():
print("")
break
if async.successful():
statdicts = async.get()
else:
raise IPyradWarningExit(async.get())
perfile, fsamplehits, fbarhits, fmisses, fdbars = statdicts
make_stats(data, perfile, fsamplehits, fbarhits, fmisses, fdbars)
except KeyboardInterrupt:
print("\n ...interrupted, just a second while we ensure proper cleanup")
kbd = 1
finally:
tmpdir = os.path.join(data.paramsdict["project_dir"], "tmp-chunks-"+data.name)
if os.path.exists(tmpdir):
shutil.rmtree(tmpdir)
tmpfiles = glob.glob(os.path.join(data.dirs.fastqs, "tmp_*_R*.fastq"))
tmpfiles += glob.glob(os.path.join(data.dirs.fastqs, "tmp_*.p"))
for tmpf in tmpfiles:
if os.path.exists(tmpf):
os.remove(tmpf)
if kbd:
raise | One input file (or pair) is run on two processors, one for reading
and decompressing the data, and the other for demuxing it. | ### Input:
One input file (or pair) is run on two processors, one for reading
and decompressing the data, and the other for demuxing it.
### Response:
def run3(data, ipyclient, force):
start = time.time()
raws, longbar, cutters, matchdict = prechecks2(data, force)
kbd = 0
try:
progressbar(len(ready), sum(ready), printstr, spacer=spacer)
time.sleep(0.1)
if async.ready():
print("")
break
if async.successful():
statdicts = async.get()
else:
raise IPyradWarningExit(async.get())
perfile, fsamplehits, fbarhits, fmisses, fdbars = statdicts
make_stats(data, perfile, fsamplehits, fbarhits, fmisses, fdbars)
except KeyboardInterrupt:
print("\n ...interrupted, just a second while we ensure proper cleanup")
kbd = 1
finally:
tmpdir = os.path.join(data.paramsdict["project_dir"], "tmp-chunks-"+data.name)
if os.path.exists(tmpdir):
shutil.rmtree(tmpdir)
tmpfiles = glob.glob(os.path.join(data.dirs.fastqs, "tmp_*_R*.fastq"))
tmpfiles += glob.glob(os.path.join(data.dirs.fastqs, "tmp_*.p"))
for tmpf in tmpfiles:
if os.path.exists(tmpf):
os.remove(tmpf)
if kbd:
raise |
def init_app(self, app):
self.app = app
if not hasattr(app, ):
app.extensions = {}
app.extensions[] = self
self.reload() | Initialize this Flask extension for given app. | ### Input:
Initialize this Flask extension for given app.
### Response:
def init_app(self, app):
self.app = app
if not hasattr(app, ):
app.extensions = {}
app.extensions[] = self
self.reload() |
def form_valid(self, form):
valid = True
name = form.cleaned_data.get().name
user = self.request.user
form.save(user=user, service_name=name)
sa = ServicesActivated.objects.get(name=name)
if sa.auth_required and sa.self_hosted:
from django_th.services import default_provider
default_provider.load_services()
service_provider = default_provider.get_service(name)
result = service_provider.check(self.request, user)
if result is not True:
form.add_error(, result)
messages.error(self.request, result)
return redirect(, pk=self.kwargs.get(self.pk_url_kwarg))
if valid:
messages.success(self.request, _() % name.split()[1])
return HttpResponseRedirect(reverse()) | save the data
:param form:
:return: | ### Input:
save the data
:param form:
:return:
### Response:
def form_valid(self, form):
valid = True
name = form.cleaned_data.get().name
user = self.request.user
form.save(user=user, service_name=name)
sa = ServicesActivated.objects.get(name=name)
if sa.auth_required and sa.self_hosted:
from django_th.services import default_provider
default_provider.load_services()
service_provider = default_provider.get_service(name)
result = service_provider.check(self.request, user)
if result is not True:
form.add_error(, result)
messages.error(self.request, result)
return redirect(, pk=self.kwargs.get(self.pk_url_kwarg))
if valid:
messages.success(self.request, _() % name.split()[1])
return HttpResponseRedirect(reverse()) |
def get_isp(self, ip):
rec = self.get_all(ip)
return rec and rec.isp | Get isp | ### Input:
Get isp
### Response:
def get_isp(self, ip):
rec = self.get_all(ip)
return rec and rec.isp |
def get_cameras_signal_strength(self):
signal_strength = {}
if not self.camera_properties:
return None
for camera in self.camera_properties:
serialnum = camera.get()
cam_strength = camera.get()
signal_strength[serialnum] = cam_strength
return signal_strength | Return a list of signal strength of all cameras. | ### Input:
Return a list of signal strength of all cameras.
### Response:
def get_cameras_signal_strength(self):
signal_strength = {}
if not self.camera_properties:
return None
for camera in self.camera_properties:
serialnum = camera.get()
cam_strength = camera.get()
signal_strength[serialnum] = cam_strength
return signal_strength |
def post(self, path, data=None, **kwargs):
if data:
return (yield from self._compute.post("/projects/{}/{}/nodes/{}{}".format(self._project.id, self._node_type, self._id, path), data=data, **kwargs))
else:
return (yield from self._compute.post("/projects/{}/{}/nodes/{}{}".format(self._project.id, self._node_type, self._id, path), **kwargs)) | HTTP post on the node | ### Input:
HTTP post on the node
### Response:
def post(self, path, data=None, **kwargs):
if data:
return (yield from self._compute.post("/projects/{}/{}/nodes/{}{}".format(self._project.id, self._node_type, self._id, path), data=data, **kwargs))
else:
return (yield from self._compute.post("/projects/{}/{}/nodes/{}{}".format(self._project.id, self._node_type, self._id, path), **kwargs)) |
def recent_post(self, author=None, daysback=0, flag=0):
if not author:
author = self.mainaccount
for num_of_retries in range(default.max_retry):
try:
self.blog = self.steem_instance().get_blog(author, 0, 30)
except Exception as e:
self.util.retry(
+
+ .format(author),
e, num_of_retries, default.wait_time)
self.s = None
else:
i = 0
for p in self.blog:
if p[][] == author:
self.blognumber = i
ageinminutes = self.util.minutes_back(p[][])
ageindays = (ageinminutes / 60) / 24
if (int(ageindays) == daysback):
if flag == 1 and ageinminutes < 15:
return None
else:
return self.util.identifier(
p[][],
p[][])
else:
return None
i += 1 | Returns the most recent post from the account
given. If the days back is greater than zero
then the most recent post is returned for that
day. For instance if daysback is set to 2
then it will be the most recent post from 2 days
ago (48 hours). | ### Input:
Returns the most recent post from the account
given. If the days back is greater than zero
then the most recent post is returned for that
day. For instance if daysback is set to 2
then it will be the most recent post from 2 days
ago (48 hours).
### Response:
def recent_post(self, author=None, daysback=0, flag=0):
if not author:
author = self.mainaccount
for num_of_retries in range(default.max_retry):
try:
self.blog = self.steem_instance().get_blog(author, 0, 30)
except Exception as e:
self.util.retry(
+
+ .format(author),
e, num_of_retries, default.wait_time)
self.s = None
else:
i = 0
for p in self.blog:
if p[][] == author:
self.blognumber = i
ageinminutes = self.util.minutes_back(p[][])
ageindays = (ageinminutes / 60) / 24
if (int(ageindays) == daysback):
if flag == 1 and ageinminutes < 15:
return None
else:
return self.util.identifier(
p[][],
p[][])
else:
return None
i += 1 |
def _render(self):
return list(self._parent)[self._start:self._stop:self._step] | Return the actual list from the stored start/stop/step. | ### Input:
Return the actual list from the stored start/stop/step.
### Response:
def _render(self):
return list(self._parent)[self._start:self._stop:self._step] |
def write_packet(self, payload):
data = pack_int24(len(payload)) + int2byte(self._next_seq_id) + payload
self._write_bytes(data)
self._next_seq_id = (self._next_seq_id + 1) % 256 | Writes an entire "mysql packet" in its entirety to the network
addings its length and sequence number. | ### Input:
Writes an entire "mysql packet" in its entirety to the network
addings its length and sequence number.
### Response:
def write_packet(self, payload):
data = pack_int24(len(payload)) + int2byte(self._next_seq_id) + payload
self._write_bytes(data)
self._next_seq_id = (self._next_seq_id + 1) % 256 |
def get_postmortem_exclusion_list(cls, bits = None):
if bits is None:
bits = cls.bits
elif bits not in (32, 64):
raise NotImplementedError("Unknown architecture (%r bits)" % bits)
if bits == 32 and cls.bits == 64:
keyname =
else:
keyname =
try:
key = cls.registry[keyname]
except KeyError:
return []
return [name for (name, enabled) in key.items() if enabled] | Returns the exclusion list for the postmortem debugger.
@see: L{get_postmortem_debugger}
@type bits: int
@param bits: Set to C{32} for the 32 bits debugger, or C{64} for the
64 bits debugger. Set to {None} for the default (L{System.bits}).
@rtype: list( str )
@return: List of excluded application filenames.
@raise WindowsError:
Raises an exception on error. | ### Input:
Returns the exclusion list for the postmortem debugger.
@see: L{get_postmortem_debugger}
@type bits: int
@param bits: Set to C{32} for the 32 bits debugger, or C{64} for the
64 bits debugger. Set to {None} for the default (L{System.bits}).
@rtype: list( str )
@return: List of excluded application filenames.
@raise WindowsError:
Raises an exception on error.
### Response:
def get_postmortem_exclusion_list(cls, bits = None):
if bits is None:
bits = cls.bits
elif bits not in (32, 64):
raise NotImplementedError("Unknown architecture (%r bits)" % bits)
if bits == 32 and cls.bits == 64:
keyname =
else:
keyname =
try:
key = cls.registry[keyname]
except KeyError:
return []
return [name for (name, enabled) in key.items() if enabled] |
def process_alias_create_namespace(namespace):
namespace = filter_alias_create_namespace(namespace)
_validate_alias_name(namespace.alias_name)
_validate_alias_command(namespace.alias_command)
_validate_alias_command_level(namespace.alias_name, namespace.alias_command)
_validate_pos_args_syntax(namespace.alias_name, namespace.alias_command) | Validate input arguments when the user invokes 'az alias create'.
Args:
namespace: argparse namespace object. | ### Input:
Validate input arguments when the user invokes 'az alias create'.
Args:
namespace: argparse namespace object.
### Response:
def process_alias_create_namespace(namespace):
namespace = filter_alias_create_namespace(namespace)
_validate_alias_name(namespace.alias_name)
_validate_alias_command(namespace.alias_command)
_validate_alias_command_level(namespace.alias_name, namespace.alias_command)
_validate_pos_args_syntax(namespace.alias_name, namespace.alias_command) |
def handleEvent(self, eventObj):
if eventObj.type not in (MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN) or not self._visible:
return []
retVal = []
hasExited = False
if not self.mouseOverButton and self._rect.collidepoint(eventObj.pos):
self.mouseOverButton = True
self.mouseEnter(eventObj)
retVal.append()
elif self.mouseOverButton and not self._rect.collidepoint(eventObj.pos):
self.mouseOverButton = False
hasExited = True
if self._rect.collidepoint(eventObj.pos):
if eventObj.type == MOUSEMOTION:
self.mouseMove(eventObj)
retVal.append()
elif eventObj.type == MOUSEBUTTONDOWN:
self.buttonDown = True
self.lastMouseDownOverButton = True
self.mouseDown(eventObj)
retVal.append()
else:
if eventObj.type in (MOUSEBUTTONUP, MOUSEBUTTONDOWN):
return retVal | All MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN event objects
created by Pygame should be passed to this method. handleEvent() will
detect if the event is relevant to this button and change its state.
There are two ways that your code can respond to button-events. One is
to inherit the PygButton class and override the mouse*() methods. The
other is to have the caller of handleEvent() check the return value
for the strings 'enter', 'move', 'down', 'up', 'click', or 'exit'.
Note that mouseEnter() is always called before mouseMove(), and
mouseMove() is always called before mouseExit(). Also, mouseUp() is
always called before mouseClick().
buttonDown is always True when mouseDown() is called, and always False
when mouseUp() or mouseClick() is called. lastMouseDownOverButton is
always False when mouseUp() or mouseClick() is called. | ### Input:
All MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN event objects
created by Pygame should be passed to this method. handleEvent() will
detect if the event is relevant to this button and change its state.
There are two ways that your code can respond to button-events. One is
to inherit the PygButton class and override the mouse*() methods. The
other is to have the caller of handleEvent() check the return value
for the strings 'enter', 'move', 'down', 'up', 'click', or 'exit'.
Note that mouseEnter() is always called before mouseMove(), and
mouseMove() is always called before mouseExit(). Also, mouseUp() is
always called before mouseClick().
buttonDown is always True when mouseDown() is called, and always False
when mouseUp() or mouseClick() is called. lastMouseDownOverButton is
always False when mouseUp() or mouseClick() is called.
### Response:
def handleEvent(self, eventObj):
if eventObj.type not in (MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN) or not self._visible:
return []
retVal = []
hasExited = False
if not self.mouseOverButton and self._rect.collidepoint(eventObj.pos):
self.mouseOverButton = True
self.mouseEnter(eventObj)
retVal.append()
elif self.mouseOverButton and not self._rect.collidepoint(eventObj.pos):
self.mouseOverButton = False
hasExited = True
if self._rect.collidepoint(eventObj.pos):
if eventObj.type == MOUSEMOTION:
self.mouseMove(eventObj)
retVal.append()
elif eventObj.type == MOUSEBUTTONDOWN:
self.buttonDown = True
self.lastMouseDownOverButton = True
self.mouseDown(eventObj)
retVal.append()
else:
if eventObj.type in (MOUSEBUTTONUP, MOUSEBUTTONDOWN):
return retVal |
def doAction(self, w, action):
U = self.upperCase1
return eval(self.actionList[action], locals()) | Perform the proper action | ### Input:
Perform the proper action
### Response:
def doAction(self, w, action):
U = self.upperCase1
return eval(self.actionList[action], locals()) |
def then_the_return_value_for_is(context, key, value):
assert key in context.apiRequest.data
assert str(context.apiRequest.data[key]) == str(value) | :type key: str
:type value: str
:type context: behave.runner.Context | ### Input:
:type key: str
:type value: str
:type context: behave.runner.Context
### Response:
def then_the_return_value_for_is(context, key, value):
assert key in context.apiRequest.data
assert str(context.apiRequest.data[key]) == str(value) |
def hash(value):
if not value:
return
elif len(value) == 32:
type =
elif len(value) == 40:
type =
elif len(value) == 64:
type =
else:
return None
return {: type, : value} | Detect an hash type | ### Input:
Detect an hash type
### Response:
def hash(value):
if not value:
return
elif len(value) == 32:
type =
elif len(value) == 40:
type =
elif len(value) == 64:
type =
else:
return None
return {: type, : value} |
def make_parser(self, ctx):
parser = OptionParser(ctx)
parser.allow_interspersed_args = ctx.allow_interspersed_args
parser.ignore_unknown_options = ctx.ignore_unknown_options
for param in self.get_params(ctx):
param.add_to_parser(parser, ctx)
return parser | Creates the underlying option parser for this command. | ### Input:
Creates the underlying option parser for this command.
### Response:
def make_parser(self, ctx):
parser = OptionParser(ctx)
parser.allow_interspersed_args = ctx.allow_interspersed_args
parser.ignore_unknown_options = ctx.ignore_unknown_options
for param in self.get_params(ctx):
param.add_to_parser(parser, ctx)
return parser |
async def get_content_count(self, source: str):
params = {"uri": source, "type": None, "target": "all", "view": "flat"}
return ContentInfo.make(
**await self.services["avContent"]["getContentCount"](params)
) | Return file listing for source. | ### Input:
Return file listing for source.
### Response:
async def get_content_count(self, source: str):
params = {"uri": source, "type": None, "target": "all", "view": "flat"}
return ContentInfo.make(
**await self.services["avContent"]["getContentCount"](params)
) |
def count_unread_messages_between(self, um_to_user, um_from_user):
unread_total = self.filter(message__sender=um_from_user,
user=um_to_user,
read_at__isnull=True,
deleted_at__isnull=True).count()
return unread_total | Returns the amount of unread messages between two users
:param um_to_user:
A Django :class:`User` for who the messages are for.
:param um_from_user:
A Django :class:`User` from whom the messages originate from.
:return:
An integer with the amount of unread messages. | ### Input:
Returns the amount of unread messages between two users
:param um_to_user:
A Django :class:`User` for who the messages are for.
:param um_from_user:
A Django :class:`User` from whom the messages originate from.
:return:
An integer with the amount of unread messages.
### Response:
def count_unread_messages_between(self, um_to_user, um_from_user):
unread_total = self.filter(message__sender=um_from_user,
user=um_to_user,
read_at__isnull=True,
deleted_at__isnull=True).count()
return unread_total |
def find_dimension_by_name(self, dim_name):
for dim in self.dimensions:
if is_equal_strings_ignore_case(dim.name, dim_name):
return dim
return None | the method searching dimension with a given name | ### Input:
the method searching dimension with a given name
### Response:
def find_dimension_by_name(self, dim_name):
for dim in self.dimensions:
if is_equal_strings_ignore_case(dim.name, dim_name):
return dim
return None |
def request_ride(
self,
ride_type=None,
start_latitude=None,
start_longitude=None,
start_address=None,
end_latitude=None,
end_longitude=None,
end_address=None,
primetime_confirmation_token=None,
):
args = {
: ride_type,
: {
: start_latitude,
: start_longitude,
: start_address,
},
: {
: end_latitude,
: end_longitude,
: end_address,
},
: primetime_confirmation_token,
}
return self._api_call(, , args=args) | Request a ride on behalf of an Lyft user.
Parameters
ride_type (str)
Name of the type of ride you're requesting.
E.g., lyft, lyft_plus
start_latitude (float)
Latitude component of a start location.
start_longitude (float)
Longitude component of a start location.
start_address (str)
Optional pickup address.
end_latitude (float)
Optional latitude component of a end location.
Destination would be NULL in this case.
end_longitude (float)
Optional longitude component of a end location.
Destination would be NULL in this case.
end_address (str)
Optional destination address.
primetime_confirmation_token (str)
Optional string containing the Prime Time confirmation token
to book rides having Prime Time Pricing.
Returns
(Response)
A Response object containing the ride request ID and other
details about the requested ride.. | ### Input:
Request a ride on behalf of an Lyft user.
Parameters
ride_type (str)
Name of the type of ride you're requesting.
E.g., lyft, lyft_plus
start_latitude (float)
Latitude component of a start location.
start_longitude (float)
Longitude component of a start location.
start_address (str)
Optional pickup address.
end_latitude (float)
Optional latitude component of a end location.
Destination would be NULL in this case.
end_longitude (float)
Optional longitude component of a end location.
Destination would be NULL in this case.
end_address (str)
Optional destination address.
primetime_confirmation_token (str)
Optional string containing the Prime Time confirmation token
to book rides having Prime Time Pricing.
Returns
(Response)
A Response object containing the ride request ID and other
details about the requested ride..
### Response:
def request_ride(
self,
ride_type=None,
start_latitude=None,
start_longitude=None,
start_address=None,
end_latitude=None,
end_longitude=None,
end_address=None,
primetime_confirmation_token=None,
):
args = {
: ride_type,
: {
: start_latitude,
: start_longitude,
: start_address,
},
: {
: end_latitude,
: end_longitude,
: end_address,
},
: primetime_confirmation_token,
}
return self._api_call(, , args=args) |
def action_setattr():
def action_setattr(value, context, **_params):
setattr(context["action"], context["key"], value)
return _attr()
return action_setattr | Creates a setter that will set the action attribute with context's key
for name to the current value. | ### Input:
Creates a setter that will set the action attribute with context's key
for name to the current value.
### Response:
def action_setattr():
def action_setattr(value, context, **_params):
setattr(context["action"], context["key"], value)
return _attr()
return action_setattr |
def _preprocess_data_for_tabular_explain(self, df, categories):
df = df.copy()
for col in list(df.columns):
if col not in (self._categorical_columns + self._numeric_columns):
del df[col]
for col_name, col_categories in zip(self._categorical_columns, categories):
df[col_name] = df[col_name].apply(
lambda x: col_categories.index(str(x)) if str(x) in col_categories
else len(col_categories) - 1)
for numeric_col in self._numeric_columns:
df[numeric_col] = df[numeric_col].apply(lambda x: float(x))
return df.as_matrix(self._categorical_columns + self._numeric_columns) | Get preprocessed training set in numpy array, and categorical names from raw training data.
LIME tabular explainer requires a training set to know the distribution of numeric and
categorical values. The training set has to be numpy arrays, with all categorical values
converted to indices. It also requires list of names for each category. | ### Input:
Get preprocessed training set in numpy array, and categorical names from raw training data.
LIME tabular explainer requires a training set to know the distribution of numeric and
categorical values. The training set has to be numpy arrays, with all categorical values
converted to indices. It also requires list of names for each category.
### Response:
def _preprocess_data_for_tabular_explain(self, df, categories):
df = df.copy()
for col in list(df.columns):
if col not in (self._categorical_columns + self._numeric_columns):
del df[col]
for col_name, col_categories in zip(self._categorical_columns, categories):
df[col_name] = df[col_name].apply(
lambda x: col_categories.index(str(x)) if str(x) in col_categories
else len(col_categories) - 1)
for numeric_col in self._numeric_columns:
df[numeric_col] = df[numeric_col].apply(lambda x: float(x))
return df.as_matrix(self._categorical_columns + self._numeric_columns) |
def encrypt(privkey, passphrase):
if isinstance(privkey, str):
privkey = PrivateKey(privkey)
else:
privkey = PrivateKey(repr(privkey))
privkeyhex = repr(privkey)
addr = format(privkey.bitcoin.address, "BTC")
a = _bytes(addr)
salt = hashlib.sha256(hashlib.sha256(a).digest()).digest()[0:4]
if SCRYPT_MODULE == "scrypt":
key = scrypt.hash(passphrase, salt, 16384, 8, 8)
elif SCRYPT_MODULE == "pylibscrypt":
key = scrypt.scrypt(bytes(passphrase, "utf-8"), salt, 16384, 8, 8)
else:
raise ValueError("No scrypt module loaded")
(derived_half1, derived_half2) = (key[:32], key[32:])
aes = AES.new(derived_half2, AES.MODE_ECB)
encrypted_half1 = _encrypt_xor(privkeyhex[:32], derived_half1[:16], aes)
encrypted_half2 = _encrypt_xor(privkeyhex[32:], derived_half1[16:], aes)
" flag byte is forced 0xc0 because Graphene only uses compressed keys "
payload = b"\x01" + b"\x42" + b"\xc0" + salt + encrypted_half1 + encrypted_half2
" Checksum "
checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
privatkey = hexlify(payload + checksum).decode("ascii")
return Base58(privatkey) | BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted privkey.
:param privkey: Private key
:type privkey: Base58
:param str passphrase: UTF-8 encoded passphrase for encryption
:return: BIP0038 non-ec-multiply encrypted wif key
:rtype: Base58 | ### Input:
BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted privkey.
:param privkey: Private key
:type privkey: Base58
:param str passphrase: UTF-8 encoded passphrase for encryption
:return: BIP0038 non-ec-multiply encrypted wif key
:rtype: Base58
### Response:
def encrypt(privkey, passphrase):
if isinstance(privkey, str):
privkey = PrivateKey(privkey)
else:
privkey = PrivateKey(repr(privkey))
privkeyhex = repr(privkey)
addr = format(privkey.bitcoin.address, "BTC")
a = _bytes(addr)
salt = hashlib.sha256(hashlib.sha256(a).digest()).digest()[0:4]
if SCRYPT_MODULE == "scrypt":
key = scrypt.hash(passphrase, salt, 16384, 8, 8)
elif SCRYPT_MODULE == "pylibscrypt":
key = scrypt.scrypt(bytes(passphrase, "utf-8"), salt, 16384, 8, 8)
else:
raise ValueError("No scrypt module loaded")
(derived_half1, derived_half2) = (key[:32], key[32:])
aes = AES.new(derived_half2, AES.MODE_ECB)
encrypted_half1 = _encrypt_xor(privkeyhex[:32], derived_half1[:16], aes)
encrypted_half2 = _encrypt_xor(privkeyhex[32:], derived_half1[16:], aes)
" flag byte is forced 0xc0 because Graphene only uses compressed keys "
payload = b"\x01" + b"\x42" + b"\xc0" + salt + encrypted_half1 + encrypted_half2
" Checksum "
checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
privatkey = hexlify(payload + checksum).decode("ascii")
return Base58(privatkey) |
def clearOldCalibrations(self, date=None):
self.coeffs[] = [self.coeffs[][-1]]
self.coeffs[] = [self.coeffs[][-1]]
for light in self.coeffs[]:
self.coeffs[][light] = [
self.coeffs[][light][-1]]
for light in self.coeffs[]:
self.coeffs[][light] = [self.coeffs[][light][-1]] | if not only a specific date than remove all except of the youngest calibration | ### Input:
if not only a specific date than remove all except of the youngest calibration
### Response:
def clearOldCalibrations(self, date=None):
self.coeffs[] = [self.coeffs[][-1]]
self.coeffs[] = [self.coeffs[][-1]]
for light in self.coeffs[]:
self.coeffs[][light] = [
self.coeffs[][light][-1]]
for light in self.coeffs[]:
self.coeffs[][light] = [self.coeffs[][light][-1]] |
def remove_child(self, child):
assert isinstance(child, Term)
self.children.remove(child)
self.doc.remove_term(child) | Remove the term from this term's children. | ### Input:
Remove the term from this term's children.
### Response:
def remove_child(self, child):
assert isinstance(child, Term)
self.children.remove(child)
self.doc.remove_term(child) |
def post_slack_message(message=None, channel=None, username=None, icon_emoji=None):
LOG.debug(, channel, message)
slack = slacker.Slacker(SLACK_TOKEN)
try:
slack.chat.post_message(channel=channel, text=message, username=username, icon_emoji=icon_emoji)
LOG.info(, channel)
except slacker.Error:
LOG.info("error posted message to %s", channel) | Format the message and post to the appropriate slack channel.
Args:
message (str): Message to post to slack
channel (str): Desired channel. Must start with # | ### Input:
Format the message and post to the appropriate slack channel.
Args:
message (str): Message to post to slack
channel (str): Desired channel. Must start with #
### Response:
def post_slack_message(message=None, channel=None, username=None, icon_emoji=None):
LOG.debug(, channel, message)
slack = slacker.Slacker(SLACK_TOKEN)
try:
slack.chat.post_message(channel=channel, text=message, username=username, icon_emoji=icon_emoji)
LOG.info(, channel)
except slacker.Error:
LOG.info("error posted message to %s", channel) |
def honor_stop_request(self, site):
site.refresh()
if (site.stop_requested
and site.stop_requested <= doublethink.utcnow()):
self.logger.info("stop requested for site %s", site.id)
raise brozzler.CrawlStopped
if site.job_id:
job = brozzler.Job.load(self.rr, site.job_id)
if (job and job.stop_requested
and job.stop_requested <= doublethink.utcnow()):
self.logger.info("stop requested for job %s", site.job_id)
raise brozzler.CrawlStopped | Raises brozzler.CrawlStopped if stop has been requested. | ### Input:
Raises brozzler.CrawlStopped if stop has been requested.
### Response:
def honor_stop_request(self, site):
site.refresh()
if (site.stop_requested
and site.stop_requested <= doublethink.utcnow()):
self.logger.info("stop requested for site %s", site.id)
raise brozzler.CrawlStopped
if site.job_id:
job = brozzler.Job.load(self.rr, site.job_id)
if (job and job.stop_requested
and job.stop_requested <= doublethink.utcnow()):
self.logger.info("stop requested for job %s", site.job_id)
raise brozzler.CrawlStopped |
def run_interactive_command(command, env=None, **kwargs):
command_result = _run_command(
command=command,
out_pipe=sys.stdout,
err_pipe=sys.stderr,
stdin=sys.stdin,
env=env,
**kwargs
)
return command_result | Runs a command interactively, reusing the current stdin, stdout and stderr
Args:
command(list of str): args of the command to execute, including the
command itself as command[0] as `['ls', '-l']`
env(dict of str:str): If set, will use the given dict as env for the
subprocess
**kwargs: Any other keyword args passed will be passed to the
:ref:subprocess.Popen call
Returns:
lago.utils.CommandStatus: result of the interactive execution | ### Input:
Runs a command interactively, reusing the current stdin, stdout and stderr
Args:
command(list of str): args of the command to execute, including the
command itself as command[0] as `['ls', '-l']`
env(dict of str:str): If set, will use the given dict as env for the
subprocess
**kwargs: Any other keyword args passed will be passed to the
:ref:subprocess.Popen call
Returns:
lago.utils.CommandStatus: result of the interactive execution
### Response:
def run_interactive_command(command, env=None, **kwargs):
command_result = _run_command(
command=command,
out_pipe=sys.stdout,
err_pipe=sys.stderr,
stdin=sys.stdin,
env=env,
**kwargs
)
return command_result |
def get_polarization_change(self, convert_to_muC_per_cm2=True, all_in_polar=True):
tot = self.get_same_branch_polarization_data(
convert_to_muC_per_cm2=convert_to_muC_per_cm2, all_in_polar=all_in_polar)
return (tot[-1] - tot[0]).reshape((1, 3)) | Get difference between nonpolar and polar same branch polarization. | ### Input:
Get difference between nonpolar and polar same branch polarization.
### Response:
def get_polarization_change(self, convert_to_muC_per_cm2=True, all_in_polar=True):
tot = self.get_same_branch_polarization_data(
convert_to_muC_per_cm2=convert_to_muC_per_cm2, all_in_polar=all_in_polar)
return (tot[-1] - tot[0]).reshape((1, 3)) |
def get(self, cluster, environ, topology, component):
start_time = time.time()
futures = yield access.get_component_exceptions(cluster, environ, topology, component)
result_map = dict(
status=,
executiontime=time.time() - start_time,
result=futures)
self.write(json.dumps(result_map)) | :param cluster:
:param environ:
:param topology:
:param component:
:return: | ### Input:
:param cluster:
:param environ:
:param topology:
:param component:
:return:
### Response:
def get(self, cluster, environ, topology, component):
start_time = time.time()
futures = yield access.get_component_exceptions(cluster, environ, topology, component)
result_map = dict(
status=,
executiontime=time.time() - start_time,
result=futures)
self.write(json.dumps(result_map)) |
def acquire(
self, timeout: Union[float, datetime.timedelta] = None
) -> Awaitable[_ReleasingContextManager]:
return self._block.acquire(timeout) | Attempt to lock. Returns an awaitable.
Returns an awaitable, which raises `tornado.util.TimeoutError` after a
timeout. | ### Input:
Attempt to lock. Returns an awaitable.
Returns an awaitable, which raises `tornado.util.TimeoutError` after a
timeout.
### Response:
def acquire(
self, timeout: Union[float, datetime.timedelta] = None
) -> Awaitable[_ReleasingContextManager]:
return self._block.acquire(timeout) |
def _load_fsstat_data(self, timeout=3):
def stats_thread():
try:
cmd = [, self.get_raw_path(), , str(self.offset // self.disk.block_size)]
fstype = {
"ntfs": "ntfs", "fat": "fat", "ext": "ext", "iso": "iso9660", "hfs+": "hfs",
"ufs": "ufs", "swap": "swap", "exfat": "exfat",
}.get(self.fstype, None)
if fstype:
cmd.extend(["-f", fstype])
logger.debug(.format(.join(cmd)))
stats_thread.process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for line in iter(stats_thread.process.stdout.readline, b):
line = line.decode()
logger.debug(.format(line))
if line.startswith("File System Type:"):
self.info[] = line[line.index() + 2:].strip()
elif line.startswith("Last Mount Point:") or line.startswith("Last mounted on:"):
self.info[] = line[line.index() + 2:].strip().replace("//", "/")
elif line.startswith("Volume Name:") and not self.info.get():
self.info[] = line[line.index() + 2:].strip()
elif line.startswith("Version:"):
self.info[] = line[line.index() + 2:].strip()
elif line.startswith("Source OS:"):
self.info[] = line[line.index() + 2:].strip()
elif in line or in line:
try:
stats_thread.process.terminate()
logger.debug("Terminated fsstat at cylinder/block group information.")
except Exception:
pass
break
if self.info.get() and self.info.get():
self.info[] = "{0} ({1})".format(self.info[], self.info[])
elif self.info.get() and not self.info.get():
self.info[] = self.info[]
elif not self.info.get() and self.info.get() and \
self.info[].startswith("/"):
if self.info[].endswith("1"):
self.info[] = self.info[][:-1]
else:
self.info[] = self.info[]
except Exception:
logger.exception("Error while obtaining stats.")
stats_thread.process = None
thread = threading.Thread(target=stats_thread)
thread.start()
thread.join(timeout)
if thread.is_alive():
try:
stats_thread.process.terminate()
except Exception:
pass
thread.join()
logger.debug("Killed fsstat after {0}s".format(timeout)) | Using :command:`fsstat`, adds some additional information of the volume to the Volume. | ### Input:
Using :command:`fsstat`, adds some additional information of the volume to the Volume.
### Response:
def _load_fsstat_data(self, timeout=3):
def stats_thread():
try:
cmd = [, self.get_raw_path(), , str(self.offset // self.disk.block_size)]
fstype = {
"ntfs": "ntfs", "fat": "fat", "ext": "ext", "iso": "iso9660", "hfs+": "hfs",
"ufs": "ufs", "swap": "swap", "exfat": "exfat",
}.get(self.fstype, None)
if fstype:
cmd.extend(["-f", fstype])
logger.debug(.format(.join(cmd)))
stats_thread.process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for line in iter(stats_thread.process.stdout.readline, b):
line = line.decode()
logger.debug(.format(line))
if line.startswith("File System Type:"):
self.info[] = line[line.index() + 2:].strip()
elif line.startswith("Last Mount Point:") or line.startswith("Last mounted on:"):
self.info[] = line[line.index() + 2:].strip().replace("//", "/")
elif line.startswith("Volume Name:") and not self.info.get():
self.info[] = line[line.index() + 2:].strip()
elif line.startswith("Version:"):
self.info[] = line[line.index() + 2:].strip()
elif line.startswith("Source OS:"):
self.info[] = line[line.index() + 2:].strip()
elif in line or in line:
try:
stats_thread.process.terminate()
logger.debug("Terminated fsstat at cylinder/block group information.")
except Exception:
pass
break
if self.info.get() and self.info.get():
self.info[] = "{0} ({1})".format(self.info[], self.info[])
elif self.info.get() and not self.info.get():
self.info[] = self.info[]
elif not self.info.get() and self.info.get() and \
self.info[].startswith("/"):
if self.info[].endswith("1"):
self.info[] = self.info[][:-1]
else:
self.info[] = self.info[]
except Exception:
logger.exception("Error while obtaining stats.")
stats_thread.process = None
thread = threading.Thread(target=stats_thread)
thread.start()
thread.join(timeout)
if thread.is_alive():
try:
stats_thread.process.terminate()
except Exception:
pass
thread.join()
logger.debug("Killed fsstat after {0}s".format(timeout)) |
def clean_up(self):
self.action_buffer = []
self.sources = {}
self.doc_to_get = {}
self.doc_to_update = [] | Do clean-up before returning buffer | ### Input:
Do clean-up before returning buffer
### Response:
def clean_up(self):
self.action_buffer = []
self.sources = {}
self.doc_to_get = {}
self.doc_to_update = [] |
def write_bytes(self, addr, buf):
assert self._device is not None,
self._select_device(addr)
self._device.write(buf) | Write many bytes to the specified device. buf is a bytearray | ### Input:
Write many bytes to the specified device. buf is a bytearray
### Response:
def write_bytes(self, addr, buf):
assert self._device is not None,
self._select_device(addr)
self._device.write(buf) |
def explicitLogout(self, session):
guard.SessionWrapper.explicitLogout(self, session)
self.removeSessionWithKey(session.uid) | Handle a user-requested logout.
Here we override guard's behaviour for the logout action to delete the
persistent session. In this case the user has explicitly requested a
logout, so the persistent session must be deleted to require the user
to log in on the next request.
@type session: L{nevow.guard.GuardSession}
@param session: The session of the user logging out. | ### Input:
Handle a user-requested logout.
Here we override guard's behaviour for the logout action to delete the
persistent session. In this case the user has explicitly requested a
logout, so the persistent session must be deleted to require the user
to log in on the next request.
@type session: L{nevow.guard.GuardSession}
@param session: The session of the user logging out.
### Response:
def explicitLogout(self, session):
guard.SessionWrapper.explicitLogout(self, session)
self.removeSessionWithKey(session.uid) |
def setUnacknowledgedPreKeyMessage(self, preKeyId, signedPreKeyId, baseKey):
self.sessionStructure.pendingPreKey.signedPreKeyId = signedPreKeyId
self.sessionStructure.pendingPreKey.baseKey = baseKey.serialize()
if preKeyId is not None:
self.sessionStructure.pendingPreKey.preKeyId = preKeyId | :type preKeyId: int
:type signedPreKeyId: int
:type baseKey: ECPublicKey | ### Input:
:type preKeyId: int
:type signedPreKeyId: int
:type baseKey: ECPublicKey
### Response:
def setUnacknowledgedPreKeyMessage(self, preKeyId, signedPreKeyId, baseKey):
self.sessionStructure.pendingPreKey.signedPreKeyId = signedPreKeyId
self.sessionStructure.pendingPreKey.baseKey = baseKey.serialize()
if preKeyId is not None:
self.sessionStructure.pendingPreKey.preKeyId = preKeyId |
def matchCollapsedState( self ):
collapsed = not self.isChecked()
if self._inverted:
collapsed = not collapsed
if ( not self.isCollapsible() or not collapsed ):
for child in self.children():
if ( not isinstance(child, QWidget) ):
continue
child.show()
self.setMaximumHeight(MAX_INT)
self.adjustSize()
if ( self.parent() ):
self.parent().adjustSize()
else:
self.setMaximumHeight(self.collapsedHeight())
for child in self.children():
if ( not isinstance(child, QWidget) ):
continue
child.hide() | Matches the collapsed state for this groupbox. | ### Input:
Matches the collapsed state for this groupbox.
### Response:
def matchCollapsedState( self ):
collapsed = not self.isChecked()
if self._inverted:
collapsed = not collapsed
if ( not self.isCollapsible() or not collapsed ):
for child in self.children():
if ( not isinstance(child, QWidget) ):
continue
child.show()
self.setMaximumHeight(MAX_INT)
self.adjustSize()
if ( self.parent() ):
self.parent().adjustSize()
else:
self.setMaximumHeight(self.collapsedHeight())
for child in self.children():
if ( not isinstance(child, QWidget) ):
continue
child.hide() |
def get_documents(self, subtypes=None, refresh=False):
search = ScopusSearch(.format(self.identifier), refresh)
if subtypes:
return [p for p in search.results if p.subtype in subtypes]
else:
return search.results | Return list of author's publications using ScopusSearch, which
fit a specified set of document subtypes. | ### Input:
Return list of author's publications using ScopusSearch, which
fit a specified set of document subtypes.
### Response:
def get_documents(self, subtypes=None, refresh=False):
search = ScopusSearch(.format(self.identifier), refresh)
if subtypes:
return [p for p in search.results if p.subtype in subtypes]
else:
return search.results |
def clear(self):
collection = self.ds.connection(COLLECTION_MANAGED_PROCESS)
return collection.delete_many(filter={}) | removes all documents in this collection | ### Input:
removes all documents in this collection
### Response:
def clear(self):
collection = self.ds.connection(COLLECTION_MANAGED_PROCESS)
return collection.delete_many(filter={}) |
def validate_age(name: str, tolerance: float, from_timestamp: float, to_timestamp: float) -> None:
age = to_timestamp - from_timestamp
assert age <= tolerance, f | Check if age is valid (within tolerance) | ### Input:
Check if age is valid (within tolerance)
### Response:
def validate_age(name: str, tolerance: float, from_timestamp: float, to_timestamp: float) -> None:
age = to_timestamp - from_timestamp
assert age <= tolerance, f |
def funcFindPrf(idxPrc,
aryFuncChnk,
aryPrfTc,
aryMdls,
queOut):
varNumVoxChnk = aryFuncChnk.shape[0]
varNumVol = aryFuncChnk.shape[1]
vecBstXpos = np.zeros(varNumVoxChnk)
vecBstYpos = np.zeros(varNumVoxChnk)
vecBstSd = np.zeros(varNumVoxChnk)
vecBstRes = np.add(np.zeros(varNumVoxChnk),
100000.0)
aryFuncChnk = aryFuncChnk.T
vecConst = np.ones((varNumVol), dtype=np.float32)
aryFuncChnk = aryFuncChnk.astype(np.float32)
aryPrfTc = aryPrfTc.astype(np.float32)
varNumMdls = len(aryMdls)
if idxPrc == 0:
varStsStpSze = 20
vecStatPrf = np.linspace(0,
varNumMdls,
num=(varStsStpSze+1),
endpoint=True)
vecStatPrf = np.ceil(vecStatPrf)
vecStatPrf = vecStatPrf.astype(int)
vecStatPrc = np.linspace(0,
100,
num=(varStsStpSze+1),
endpoint=True)
vecStatPrc = np.ceil(vecStatPrc)
vecStatPrc = vecStatPrc.astype(int)
varCntSts01 = 0
varCntSts02 = 0
for idxMdls in range(0, varNumMdls):
if idxPrc == 0:
if varCntSts02 == vecStatPrf[varCntSts01]:
strStsMsg = ( +
str(vecStatPrc[varCntSts01]) +
+
str(vecStatPrf[varCntSts01]) +
+
str(varNumMdls))
print(strStsMsg)
if varCntSts01 < varStsStpSze:
varCntSts01 = varCntSts01 + int(1)
vecMdlTc = aryPrfTc[idxMdls, :].flatten()
aryDsgn = np.vstack([vecMdlTc,
vecConst]).T
vecTmpRes = np.linalg.lstsq(aryDsgn, aryFuncChnk)[1]
vecLgcTmpRes = np.less(vecTmpRes, vecBstRes)
vecBstXpos[vecLgcTmpRes] = aryMdls[idxMdls][0]
vecBstYpos[vecLgcTmpRes] = aryMdls[idxMdls][1]
vecBstSd[vecLgcTmpRes] = aryMdls[idxMdls][2]
vecBstRes[vecLgcTmpRes] = vecTmpRes[vecLgcTmpRes]
if idxPrc == 0:
varCntSts02 = varCntSts02 + 1
vecFuncMean = np.mean(aryFuncChnk, axis=0)
vecFuncDev = np.subtract(aryFuncChnk, vecFuncMean[None, :])
vecSsTot = np.sum(np.power(vecFuncDev,
2.0),
axis=0)
vecBstR2 = np.subtract(1.0,
np.divide(vecBstRes,
vecSsTot))
lstOut = [idxPrc,
vecBstXpos,
vecBstYpos,
vecBstSd,
vecBstR2]
queOut.put(lstOut) | Function for finding best pRF model for voxel time course.
This function should be used if there is only one predictor. | ### Input:
Function for finding best pRF model for voxel time course.
This function should be used if there is only one predictor.
### Response:
def funcFindPrf(idxPrc,
aryFuncChnk,
aryPrfTc,
aryMdls,
queOut):
varNumVoxChnk = aryFuncChnk.shape[0]
varNumVol = aryFuncChnk.shape[1]
vecBstXpos = np.zeros(varNumVoxChnk)
vecBstYpos = np.zeros(varNumVoxChnk)
vecBstSd = np.zeros(varNumVoxChnk)
vecBstRes = np.add(np.zeros(varNumVoxChnk),
100000.0)
aryFuncChnk = aryFuncChnk.T
vecConst = np.ones((varNumVol), dtype=np.float32)
aryFuncChnk = aryFuncChnk.astype(np.float32)
aryPrfTc = aryPrfTc.astype(np.float32)
varNumMdls = len(aryMdls)
if idxPrc == 0:
varStsStpSze = 20
vecStatPrf = np.linspace(0,
varNumMdls,
num=(varStsStpSze+1),
endpoint=True)
vecStatPrf = np.ceil(vecStatPrf)
vecStatPrf = vecStatPrf.astype(int)
vecStatPrc = np.linspace(0,
100,
num=(varStsStpSze+1),
endpoint=True)
vecStatPrc = np.ceil(vecStatPrc)
vecStatPrc = vecStatPrc.astype(int)
varCntSts01 = 0
varCntSts02 = 0
for idxMdls in range(0, varNumMdls):
if idxPrc == 0:
if varCntSts02 == vecStatPrf[varCntSts01]:
strStsMsg = ( +
str(vecStatPrc[varCntSts01]) +
+
str(vecStatPrf[varCntSts01]) +
+
str(varNumMdls))
print(strStsMsg)
if varCntSts01 < varStsStpSze:
varCntSts01 = varCntSts01 + int(1)
vecMdlTc = aryPrfTc[idxMdls, :].flatten()
aryDsgn = np.vstack([vecMdlTc,
vecConst]).T
vecTmpRes = np.linalg.lstsq(aryDsgn, aryFuncChnk)[1]
vecLgcTmpRes = np.less(vecTmpRes, vecBstRes)
vecBstXpos[vecLgcTmpRes] = aryMdls[idxMdls][0]
vecBstYpos[vecLgcTmpRes] = aryMdls[idxMdls][1]
vecBstSd[vecLgcTmpRes] = aryMdls[idxMdls][2]
vecBstRes[vecLgcTmpRes] = vecTmpRes[vecLgcTmpRes]
if idxPrc == 0:
varCntSts02 = varCntSts02 + 1
vecFuncMean = np.mean(aryFuncChnk, axis=0)
vecFuncDev = np.subtract(aryFuncChnk, vecFuncMean[None, :])
vecSsTot = np.sum(np.power(vecFuncDev,
2.0),
axis=0)
vecBstR2 = np.subtract(1.0,
np.divide(vecBstRes,
vecSsTot))
lstOut = [idxPrc,
vecBstXpos,
vecBstYpos,
vecBstSd,
vecBstR2]
queOut.put(lstOut) |
def get_host(self, name, default=NoHostError):
if name in self.hosts:
return self.hosts[name]
if default is NoHostError:
raise NoHostError(.format(name))
return default | Get a single host by name. | ### Input:
Get a single host by name.
### Response:
def get_host(self, name, default=NoHostError):
if name in self.hosts:
return self.hosts[name]
if default is NoHostError:
raise NoHostError(.format(name))
return default |
def ancestry(self, context):
log.debug("get ancestry %s", context)
if context is None:
return
ancestors.pop() | Return the ancestry of the context (that is, all of the
packages and modules containing the context), in order of
descent with the outermost ancestor last.
This method is a generator. | ### Input:
Return the ancestry of the context (that is, all of the
packages and modules containing the context), in order of
descent with the outermost ancestor last.
This method is a generator.
### Response:
def ancestry(self, context):
log.debug("get ancestry %s", context)
if context is None:
return
ancestors.pop() |
def get_t_statistics(self):
t used, since this information is taken
directly from the corpus categories.
Returns
-------
catncat']].sum(axis=1) == 0
pvals = stats.t.sf(np.abs(tt), degs_of_freedom)
tt[only_in_neutral_mask] = 0
pvals[only_in_neutral_mask] = 0
return tt, pvals | In this case, parameters a and b aren't used, since this information is taken
directly from the corpus categories.
Returns
------- | ### Input:
In this case, parameters a and b aren't used, since this information is taken
directly from the corpus categories.
Returns
-------
### Response:
def get_t_statistics(self):
t used, since this information is taken
directly from the corpus categories.
Returns
-------
catncat']].sum(axis=1) == 0
pvals = stats.t.sf(np.abs(tt), degs_of_freedom)
tt[only_in_neutral_mask] = 0
pvals[only_in_neutral_mask] = 0
return tt, pvals |
def parse_shutitfile_args(args_str):
ret = []
if args_str == :
return ret
if args_str[0] == and args_str[-1] == :
ret = eval(args_str)
assert isinstance(ret, list)
else:
ret = args_str.split()
nv_pairs = True
for item in ret:
if item.find() < 0:
nv_pairs = False
if nv_pairs:
d = {}
for item in ret:
item_nv = item.split()
d.update({item_nv[0]:item_nv[1]})
ret = d
return ret | Parse shutitfile args (eg in the line 'RUN some args', the passed-in args_str would be 'some args').
If the string is bounded by square brackets, then it's treated in the form: ['arg1','arg2'], and the returned list looks the same.
If the string composed entirely of name-value pairs (eg RUN a=b c=d) then it's returned as a dict (eg {'a':'b','c':'d'}).
If what's passed-in is of the form: "COMMAND ['a=b','c=d']" then a dict is also returned.'
Also eg: ["asd and space=value","asd 2=asdgasdg"] | ### Input:
Parse shutitfile args (eg in the line 'RUN some args', the passed-in args_str would be 'some args').
If the string is bounded by square brackets, then it's treated in the form: ['arg1','arg2'], and the returned list looks the same.
If the string composed entirely of name-value pairs (eg RUN a=b c=d) then it's returned as a dict (eg {'a':'b','c':'d'}).
If what's passed-in is of the form: "COMMAND ['a=b','c=d']" then a dict is also returned.'
Also eg: ["asd and space=value","asd 2=asdgasdg"]
### Response:
def parse_shutitfile_args(args_str):
ret = []
if args_str == :
return ret
if args_str[0] == and args_str[-1] == :
ret = eval(args_str)
assert isinstance(ret, list)
else:
ret = args_str.split()
nv_pairs = True
for item in ret:
if item.find() < 0:
nv_pairs = False
if nv_pairs:
d = {}
for item in ret:
item_nv = item.split()
d.update({item_nv[0]:item_nv[1]})
ret = d
return ret |
def _invoke_xz(self, xz_input_file):
cmd = [self._xz_binary_path, , , , , xz_input_file]
try:
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=sys.stderr)
except OSError as e:
raise self.XZArchiverError(
"Error invoking xz with command {} for input file {}: {}"
.format(cmd, xz_input_file, e),
e)
yield process.stdout
rc = process.wait()
if rc != 0:
raise self.XZArchiverError(
"Error decompressing xz input with command {} for input file {}. Exit code was: {}. "
.format(cmd, xz_input_file, rc)) | Run the xz command and yield a file object for its stdout.
This allows streaming the decompressed tar archive directly into a tar decompression stream,
which is significantly faster in practice than making a temporary file. | ### Input:
Run the xz command and yield a file object for its stdout.
This allows streaming the decompressed tar archive directly into a tar decompression stream,
which is significantly faster in practice than making a temporary file.
### Response:
def _invoke_xz(self, xz_input_file):
cmd = [self._xz_binary_path, , , , , xz_input_file]
try:
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=sys.stderr)
except OSError as e:
raise self.XZArchiverError(
"Error invoking xz with command {} for input file {}: {}"
.format(cmd, xz_input_file, e),
e)
yield process.stdout
rc = process.wait()
if rc != 0:
raise self.XZArchiverError(
"Error decompressing xz input with command {} for input file {}. Exit code was: {}. "
.format(cmd, xz_input_file, rc)) |
def get_conn(self):
conn = self.get_connection(self.vertica_conn_id)
conn_config = {
"user": conn.login,
"password": conn.password or ,
"database": conn.schema,
"host": conn.host or
}
if not conn.port:
conn_config["port"] = 5433
else:
conn_config["port"] = int(conn.port)
conn = connect(**conn_config)
return conn | Returns verticaql connection object | ### Input:
Returns verticaql connection object
### Response:
def get_conn(self):
conn = self.get_connection(self.vertica_conn_id)
conn_config = {
"user": conn.login,
"password": conn.password or ,
"database": conn.schema,
"host": conn.host or
}
if not conn.port:
conn_config["port"] = 5433
else:
conn_config["port"] = int(conn.port)
conn = connect(**conn_config)
return conn |
def backend(self):
"Internal property that returns the Node script running harness"
if self._backend is None:
with io.open(path.join(path.abspath(path.dirname(__file__)), "runner.js")) as runner_file:
runner_source = runner_file.read()
self._backend = execjs.ExternalRuntime(name="Node.js (V8)",
command=["node"],
runner_source=runner_source)
return self._backend | Internal property that returns the Node script running harness | ### Input:
Internal property that returns the Node script running harness
### Response:
def backend(self):
"Internal property that returns the Node script running harness"
if self._backend is None:
with io.open(path.join(path.abspath(path.dirname(__file__)), "runner.js")) as runner_file:
runner_source = runner_file.read()
self._backend = execjs.ExternalRuntime(name="Node.js (V8)",
command=["node"],
runner_source=runner_source)
return self._backend |
def _get_recursive_dependancies(self, dependencies_map, sourcepath,
recursive=True):
collected = set([])
collected.update(dependencies_map.get(sourcepath, []))
sequence = collected.copy()
walkthrough = []
if recursive:
while True:
if not sequence:
break
item = sequence.pop()
walkthrough.append(item)
current_item_dependancies = dependencies_map.get(item, [])
for dependency in current_item_dependancies:
if dependency in walkthrough:
continue
else:
collected.add(dependency)
sequence.add(dependency)
raise CircularImport(msg.format(current_item_dependancies))
if not sequence:
break
return collected | Return all dependencies of a source, recursively searching through its
dependencies.
This is a common method used by ``children`` and ``parents`` methods.
Args:
dependencies_map (dict): Internal buffer (internal buffers
``_CHILDREN_MAP`` or ``_PARENTS_MAP``) to use for searching.
sourcepath (str): Source file path to start searching for
dependencies.
Keyword Arguments:
recursive (bool): Switch to enable recursive finding (if True).
Default to True.
Raises:
CircularImport: If circular error is detected from a source.
Returns:
set: List of dependencies paths. | ### Input:
Return all dependencies of a source, recursively searching through its
dependencies.
This is a common method used by ``children`` and ``parents`` methods.
Args:
dependencies_map (dict): Internal buffer (internal buffers
``_CHILDREN_MAP`` or ``_PARENTS_MAP``) to use for searching.
sourcepath (str): Source file path to start searching for
dependencies.
Keyword Arguments:
recursive (bool): Switch to enable recursive finding (if True).
Default to True.
Raises:
CircularImport: If circular error is detected from a source.
Returns:
set: List of dependencies paths.
### Response:
def _get_recursive_dependancies(self, dependencies_map, sourcepath,
recursive=True):
collected = set([])
collected.update(dependencies_map.get(sourcepath, []))
sequence = collected.copy()
walkthrough = []
if recursive:
while True:
if not sequence:
break
item = sequence.pop()
walkthrough.append(item)
current_item_dependancies = dependencies_map.get(item, [])
for dependency in current_item_dependancies:
if dependency in walkthrough:
continue
else:
collected.add(dependency)
sequence.add(dependency)
raise CircularImport(msg.format(current_item_dependancies))
if not sequence:
break
return collected |
def load_pdb(pdb, path=True, pdb_id=, ignore_end=False):
pdb_p = PdbParser(pdb, path=path, pdb_id=pdb_id, ignore_end=ignore_end)
return pdb_p.make_ampal() | Converts a PDB file into an AMPAL object.
Parameters
----------
pdb : str
Either a path to a PDB file or a string containing PDB
format structural data.
path : bool, optional
If `true`, flags `pdb` as a path and not a PDB string.
pdb_id : str, optional
Identifier for the `Assembly`.
ignore_end : bool, optional
If `false`, parsing of the file will stop when an "END"
record is encountered.
Returns
-------
ampal : ampal.Assembly or ampal.AmpalContainer
AMPAL object that contains the structural information from
the PDB file provided. If the PDB file has a single state
then an `Assembly` will be returned, otherwise an
`AmpalContainer` will be returned. | ### Input:
Converts a PDB file into an AMPAL object.
Parameters
----------
pdb : str
Either a path to a PDB file or a string containing PDB
format structural data.
path : bool, optional
If `true`, flags `pdb` as a path and not a PDB string.
pdb_id : str, optional
Identifier for the `Assembly`.
ignore_end : bool, optional
If `false`, parsing of the file will stop when an "END"
record is encountered.
Returns
-------
ampal : ampal.Assembly or ampal.AmpalContainer
AMPAL object that contains the structural information from
the PDB file provided. If the PDB file has a single state
then an `Assembly` will be returned, otherwise an
`AmpalContainer` will be returned.
### Response:
def load_pdb(pdb, path=True, pdb_id=, ignore_end=False):
pdb_p = PdbParser(pdb, path=path, pdb_id=pdb_id, ignore_end=ignore_end)
return pdb_p.make_ampal() |
def prop_power(self, propulsion_eff=0.7, sea_margin=0.2):
PP = (1 + sea_margin) * self.resistance() * self.speed/propulsion_eff
return PP | Total propulsion power of the ship.
:param propulsion_eff: Shaft efficiency of the ship
:param sea_margin: Sea margin take account of interaction between ship and the sea, e.g. wave
:return: Watts shaft propulsion power of the ship | ### Input:
Total propulsion power of the ship.
:param propulsion_eff: Shaft efficiency of the ship
:param sea_margin: Sea margin take account of interaction between ship and the sea, e.g. wave
:return: Watts shaft propulsion power of the ship
### Response:
def prop_power(self, propulsion_eff=0.7, sea_margin=0.2):
PP = (1 + sea_margin) * self.resistance() * self.speed/propulsion_eff
return PP |
def seq_2_DbDevExportInfos(seq, vec=None):
if vec is None:
if isinstance(seq, DbDevExportInfos):
return seq
vec = DbDevExportInfos()
if not isinstance(vec, DbDevExportInfos):
raise TypeError()
for e in seq:
vec.append(e)
return vec | Converts a python sequence<DbDevExportInfo> object to a :class:`tango.DbDevExportInfos`
:param seq: the sequence of DbDevExportInfo
:type seq: sequence<DbDevExportInfo>
:param vec: (optional, default is None) an :class:`tango.DbDevExportInfos`
to be filled. If None is given, a new :class:`tango.DbDevExportInfos`
is created
:return: a :class:`tango.DbDevExportInfos` filled with the same contents as seq
:rtype: :class:`tango.DbDevExportInfos` | ### Input:
Converts a python sequence<DbDevExportInfo> object to a :class:`tango.DbDevExportInfos`
:param seq: the sequence of DbDevExportInfo
:type seq: sequence<DbDevExportInfo>
:param vec: (optional, default is None) an :class:`tango.DbDevExportInfos`
to be filled. If None is given, a new :class:`tango.DbDevExportInfos`
is created
:return: a :class:`tango.DbDevExportInfos` filled with the same contents as seq
:rtype: :class:`tango.DbDevExportInfos`
### Response:
def seq_2_DbDevExportInfos(seq, vec=None):
if vec is None:
if isinstance(seq, DbDevExportInfos):
return seq
vec = DbDevExportInfos()
if not isinstance(vec, DbDevExportInfos):
raise TypeError()
for e in seq:
vec.append(e)
return vec |
def set_custom_interpreters_list(self, value):
custom_list = self.get_option()
if value not in custom_list and value != get_python_executable():
custom_list.append(value)
self.set_option(, custom_list) | Update the list of interpreters used and the current one. | ### Input:
Update the list of interpreters used and the current one.
### Response:
def set_custom_interpreters_list(self, value):
custom_list = self.get_option()
if value not in custom_list and value != get_python_executable():
custom_list.append(value)
self.set_option(, custom_list) |
def scaled_imu3_send(self, time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, force_mavlink1=False):
return self.send(self.scaled_imu3_encode(time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag), force_mavlink1=force_mavlink1) | The RAW IMU readings for 3rd 9DOF sensor setup. This message should
contain the scaled values to the described units
time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t)
xacc : X acceleration (mg) (int16_t)
yacc : Y acceleration (mg) (int16_t)
zacc : Z acceleration (mg) (int16_t)
xgyro : Angular speed around X axis (millirad /sec) (int16_t)
ygyro : Angular speed around Y axis (millirad /sec) (int16_t)
zgyro : Angular speed around Z axis (millirad /sec) (int16_t)
xmag : X Magnetic field (milli tesla) (int16_t)
ymag : Y Magnetic field (milli tesla) (int16_t)
zmag : Z Magnetic field (milli tesla) (int16_t) | ### Input:
The RAW IMU readings for 3rd 9DOF sensor setup. This message should
contain the scaled values to the described units
time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t)
xacc : X acceleration (mg) (int16_t)
yacc : Y acceleration (mg) (int16_t)
zacc : Z acceleration (mg) (int16_t)
xgyro : Angular speed around X axis (millirad /sec) (int16_t)
ygyro : Angular speed around Y axis (millirad /sec) (int16_t)
zgyro : Angular speed around Z axis (millirad /sec) (int16_t)
xmag : X Magnetic field (milli tesla) (int16_t)
ymag : Y Magnetic field (milli tesla) (int16_t)
zmag : Z Magnetic field (milli tesla) (int16_t)
### Response:
def scaled_imu3_send(self, time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, force_mavlink1=False):
return self.send(self.scaled_imu3_encode(time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag), force_mavlink1=force_mavlink1) |
def _add_column(self, p_view, p_pos=None):
def execute_silent(p_cmd, p_todo_id=None):
self._execute_handler(p_cmd, p_todo_id, lambda _: None)
todolist = TodoListWidget(p_view, p_view.data[], self.keymap)
urwid.connect_signal(todolist, ,
execute_silent)
urwid.connect_signal(todolist, , self._execute_handler)
urwid.connect_signal(todolist, , self._repeat_last_cmd)
urwid.connect_signal(todolist, , self.mainloop.screen.clear)
urwid.connect_signal(todolist, , self._set_alarm)
urwid.connect_signal(todolist, , self._remove_alarm)
urwid.connect_signal(todolist, , self._column_action_handler)
urwid.connect_signal(todolist, , self._print_keystate)
urwid.connect_signal(todolist, ,
self._process_mark_toggle)
options = self.columns.options(
width_type=,
width_amount=config().column_width(),
box_widget=True
)
item = (todolist, options)
if p_pos == None:
p_pos = len(self.columns.contents)
self.columns.contents.insert(p_pos, item)
self.columns.focus_position = p_pos
self._blur_commandline() | Given an UIView, adds a new column widget with the todos in that view.
When no position is given, it is added to the end, otherwise inserted
before that position. | ### Input:
Given an UIView, adds a new column widget with the todos in that view.
When no position is given, it is added to the end, otherwise inserted
before that position.
### Response:
def _add_column(self, p_view, p_pos=None):
def execute_silent(p_cmd, p_todo_id=None):
self._execute_handler(p_cmd, p_todo_id, lambda _: None)
todolist = TodoListWidget(p_view, p_view.data[], self.keymap)
urwid.connect_signal(todolist, ,
execute_silent)
urwid.connect_signal(todolist, , self._execute_handler)
urwid.connect_signal(todolist, , self._repeat_last_cmd)
urwid.connect_signal(todolist, , self.mainloop.screen.clear)
urwid.connect_signal(todolist, , self._set_alarm)
urwid.connect_signal(todolist, , self._remove_alarm)
urwid.connect_signal(todolist, , self._column_action_handler)
urwid.connect_signal(todolist, , self._print_keystate)
urwid.connect_signal(todolist, ,
self._process_mark_toggle)
options = self.columns.options(
width_type=,
width_amount=config().column_width(),
box_widget=True
)
item = (todolist, options)
if p_pos == None:
p_pos = len(self.columns.contents)
self.columns.contents.insert(p_pos, item)
self.columns.focus_position = p_pos
self._blur_commandline() |
def BytesIO(*args, **kwargs):
raw = sync_io.BytesIO(*args, **kwargs)
return AsyncBytesIOWrapper(raw) | BytesIO constructor shim for the async wrapper. | ### Input:
BytesIO constructor shim for the async wrapper.
### Response:
def BytesIO(*args, **kwargs):
raw = sync_io.BytesIO(*args, **kwargs)
return AsyncBytesIOWrapper(raw) |
def json(self):
if self.meta_type == :
ret = []
for dat in self._list:
if not isinstance(dat, composite):
ret.append(dat)
else:
ret.append(dat.json())
return ret
elif self.meta_type == :
ret = {}
for key in self._dict:
if not isinstance(self._dict[key], composite):
ret[key] = self._dict[key]
else:
ret[key] = self._dict[key].json()
return ret | Return JSON representation of object. | ### Input:
Return JSON representation of object.
### Response:
def json(self):
if self.meta_type == :
ret = []
for dat in self._list:
if not isinstance(dat, composite):
ret.append(dat)
else:
ret.append(dat.json())
return ret
elif self.meta_type == :
ret = {}
for key in self._dict:
if not isinstance(self._dict[key], composite):
ret[key] = self._dict[key]
else:
ret[key] = self._dict[key].json()
return ret |
def encode(data, version=0, level=QR_ECLEVEL_L, hint=QR_MODE_8,
case_sensitive=True):
if isinstance(data, unicode):
data = data.encode()
elif not isinstance(data, basestring):
raise ValueError()
version = int(version)
if level not in levels:
raise ValueError()
if hint not in hints:
raise ValueError()
if case_sensitive:
version, size, data = _encode(data, version, level, hint, True)
else:
version, size, data = _encode(data, version, level, hint, False)
im = Image.frombytes(, (size, size), data)
return (version, size, im) | Creates a QR-Code from string data.
Args:
data: string: The data to encode in a QR-code. If a unicode string is
supplied, it will be encoded in UTF-8.
version: int: The minimum version to use. If set to 0, the library picks
the smallest version that the data fits in.
level: int: Error correction level. Defaults to 'L'.
hint: int: The type of data to encode. Either QR_MODE_8 or QR_MODE_KANJI.
case_sensitive: bool: Should string data be encoded case-preserving?
Returns:
A (version, size, image) tuple, where image is a size*size PIL image of
the QR-code. | ### Input:
Creates a QR-Code from string data.
Args:
data: string: The data to encode in a QR-code. If a unicode string is
supplied, it will be encoded in UTF-8.
version: int: The minimum version to use. If set to 0, the library picks
the smallest version that the data fits in.
level: int: Error correction level. Defaults to 'L'.
hint: int: The type of data to encode. Either QR_MODE_8 or QR_MODE_KANJI.
case_sensitive: bool: Should string data be encoded case-preserving?
Returns:
A (version, size, image) tuple, where image is a size*size PIL image of
the QR-code.
### Response:
def encode(data, version=0, level=QR_ECLEVEL_L, hint=QR_MODE_8,
case_sensitive=True):
if isinstance(data, unicode):
data = data.encode()
elif not isinstance(data, basestring):
raise ValueError()
version = int(version)
if level not in levels:
raise ValueError()
if hint not in hints:
raise ValueError()
if case_sensitive:
version, size, data = _encode(data, version, level, hint, True)
else:
version, size, data = _encode(data, version, level, hint, False)
im = Image.frombytes(, (size, size), data)
return (version, size, im) |
def serialtoflat(self, raw, width=None):
if self.bitdepth == 8:
return raw
if self.bitdepth == 16:
raw = bytearray_to_bytes(raw)
return array(,
struct.unpack( % (len(raw) // 2), raw))
assert self.bitdepth < 8
if width is None:
width = self.width
spb = 8 // self.bitdepth
out = newBarray()
mask = 2**self.bitdepth - 1
shifts = [self.bitdepth * it for it in range(spb - 1, -1, -1)]
l = width
for o in raw:
out.extend([(mask&(o>>s)) for s in shifts][:l])
l -= spb
if l <= 0:
l = width
return out | Convert serial (byte stream) pixel data to flat row flat pixel. | ### Input:
Convert serial (byte stream) pixel data to flat row flat pixel.
### Response:
def serialtoflat(self, raw, width=None):
if self.bitdepth == 8:
return raw
if self.bitdepth == 16:
raw = bytearray_to_bytes(raw)
return array(,
struct.unpack( % (len(raw) // 2), raw))
assert self.bitdepth < 8
if width is None:
width = self.width
spb = 8 // self.bitdepth
out = newBarray()
mask = 2**self.bitdepth - 1
shifts = [self.bitdepth * it for it in range(spb - 1, -1, -1)]
l = width
for o in raw:
out.extend([(mask&(o>>s)) for s in shifts][:l])
l -= spb
if l <= 0:
l = width
return out |
def per_callback_query_chat_id(types=):
def f(msg):
if (flavor(msg) == and in msg
and (types == or msg[][][] in types)):
return msg[][][]
else:
return None
return f | :param types:
``all`` or a list of chat types (``private``, ``group``, ``channel``)
:return:
a seeder function that returns a callback query's originating chat id
if the chat type is in ``types``. | ### Input:
:param types:
``all`` or a list of chat types (``private``, ``group``, ``channel``)
:return:
a seeder function that returns a callback query's originating chat id
if the chat type is in ``types``.
### Response:
def per_callback_query_chat_id(types=):
def f(msg):
if (flavor(msg) == and in msg
and (types == or msg[][][] in types)):
return msg[][][]
else:
return None
return f |
def schema_completer(prefix):
from c7n import schema
load_resources()
components = prefix.split()
if components[0] in provider.clouds.keys():
cloud_provider = components.pop(0)
provider_resources = provider.resources(cloud_provider)
else:
cloud_provider =
provider_resources = provider.resources()
components[0] = "aws.%s" % components[0]
if len(components) == 1:
choices = [r for r in provider.resources().keys()
if r.startswith(components[0])]
if len(choices) == 1:
choices += [.format(choices[0], )]
return choices
if components[0] not in provider_resources.keys():
return []
if len(components) == 2:
choices = [.format(components[0], x)
for x in (, ) if x.startswith(components[1])]
if len(choices) == 1:
choices += [.format(choices[0], )]
return choices
elif len(components) == 3:
resource_mapping = schema.resource_vocabulary(cloud_provider)
return [.format(components[0], components[1], x)
for x in resource_mapping[components[0]][components[1]]]
return [] | For tab-completion via argcomplete, return completion options.
For the given prefix so far, return the possible options. Note that
filtering via startswith happens after this list is returned. | ### Input:
For tab-completion via argcomplete, return completion options.
For the given prefix so far, return the possible options. Note that
filtering via startswith happens after this list is returned.
### Response:
def schema_completer(prefix):
from c7n import schema
load_resources()
components = prefix.split()
if components[0] in provider.clouds.keys():
cloud_provider = components.pop(0)
provider_resources = provider.resources(cloud_provider)
else:
cloud_provider =
provider_resources = provider.resources()
components[0] = "aws.%s" % components[0]
if len(components) == 1:
choices = [r for r in provider.resources().keys()
if r.startswith(components[0])]
if len(choices) == 1:
choices += [.format(choices[0], )]
return choices
if components[0] not in provider_resources.keys():
return []
if len(components) == 2:
choices = [.format(components[0], x)
for x in (, ) if x.startswith(components[1])]
if len(choices) == 1:
choices += [.format(choices[0], )]
return choices
elif len(components) == 3:
resource_mapping = schema.resource_vocabulary(cloud_provider)
return [.format(components[0], components[1], x)
for x in resource_mapping[components[0]][components[1]]]
return [] |
def _get_or_create_hostfile():
hfn = __get_hosts_filename()
if hfn is None:
hfn =
if not os.path.exists(hfn):
with salt.utils.files.fopen(hfn, ):
pass
return hfn | Wrapper of __get_hosts_filename but create host file if it
does not exist. | ### Input:
Wrapper of __get_hosts_filename but create host file if it
does not exist.
### Response:
def _get_or_create_hostfile():
hfn = __get_hosts_filename()
if hfn is None:
hfn =
if not os.path.exists(hfn):
with salt.utils.files.fopen(hfn, ):
pass
return hfn |
def _fill_scope_refs(name, scope):
symbol = scope.resolve(name)
if symbol is None:
return
orig_scope = symbol.scope
scope.refs[name] = orig_scope
while scope is not orig_scope:
scope = scope.get_enclosing_scope()
scope.refs[name] = orig_scope | Put referenced name in 'ref' dictionary of a scope.
Walks up the scope tree and adds the name to 'ref' of every scope
up in the tree until a scope that defines referenced name is reached. | ### Input:
Put referenced name in 'ref' dictionary of a scope.
Walks up the scope tree and adds the name to 'ref' of every scope
up in the tree until a scope that defines referenced name is reached.
### Response:
def _fill_scope_refs(name, scope):
symbol = scope.resolve(name)
if symbol is None:
return
orig_scope = symbol.scope
scope.refs[name] = orig_scope
while scope is not orig_scope:
scope = scope.get_enclosing_scope()
scope.refs[name] = orig_scope |
def get_actions(actions):
new_actions = []
if actions:
for action in actions:
action_obj = get_action(action)
if action_obj:
new_actions.append(action_obj)
return new_actions | Get actions. | ### Input:
Get actions.
### Response:
def get_actions(actions):
new_actions = []
if actions:
for action in actions:
action_obj = get_action(action)
if action_obj:
new_actions.append(action_obj)
return new_actions |
def add_entity(self, name, lines, reload_cache=False):
Entity.verify_name(name)
self.entities.add(Entity.wrap_name(name), lines, reload_cache)
self.padaos.add_entity(name, lines)
self.must_train = True | Adds an entity that matches the given lines.
Example:
self.add_intent('weather', ['will it rain on {weekday}?'])
self.add_entity('{weekday}', ['monday', 'tuesday', 'wednesday']) # ...
Args:
name (str): The name of the entity
lines (list<str>): Lines of example extracted entities
reload_cache (bool): Whether to refresh all of cache | ### Input:
Adds an entity that matches the given lines.
Example:
self.add_intent('weather', ['will it rain on {weekday}?'])
self.add_entity('{weekday}', ['monday', 'tuesday', 'wednesday']) # ...
Args:
name (str): The name of the entity
lines (list<str>): Lines of example extracted entities
reload_cache (bool): Whether to refresh all of cache
### Response:
def add_entity(self, name, lines, reload_cache=False):
Entity.verify_name(name)
self.entities.add(Entity.wrap_name(name), lines, reload_cache)
self.padaos.add_entity(name, lines)
self.must_train = True |
def autodiscover(self, url):
headers, response = fetch_url(url)
if headers[].split()[0] in (, ):
provider_data = json.loads(response)
return self.store_providers(provider_data) | Load up StoredProviders from url if it is an oembed scheme | ### Input:
Load up StoredProviders from url if it is an oembed scheme
### Response:
def autodiscover(self, url):
headers, response = fetch_url(url)
if headers[].split()[0] in (, ):
provider_data = json.loads(response)
return self.store_providers(provider_data) |
def tn_mean(tasmin, freq=):
r
arr = tasmin.resample(time=freq) if freq else tasmin
return arr.mean(dim=, keep_attrs=True) | r"""Mean minimum temperature.
Mean of daily minimum temperature.
Parameters
----------
tasmin : xarray.DataArray
Minimum daily temperature [℃] or [K]
freq : str, optional
Resampling frequency
Returns
-------
xarray.DataArray
Mean of daily minimum temperature.
Notes
-----
Let :math:`TN_{ij}` be the minimum temperature at day :math:`i` of period :math:`j`. Then mean
values in period :math:`j` are given by:
.. math::
TN_{ij} = \frac{ \sum_{i=1}^{I} TN_{ij} }{I} | ### Input:
r"""Mean minimum temperature.
Mean of daily minimum temperature.
Parameters
----------
tasmin : xarray.DataArray
Minimum daily temperature [℃] or [K]
freq : str, optional
Resampling frequency
Returns
-------
xarray.DataArray
Mean of daily minimum temperature.
Notes
-----
Let :math:`TN_{ij}` be the minimum temperature at day :math:`i` of period :math:`j`. Then mean
values in period :math:`j` are given by:
.. math::
TN_{ij} = \frac{ \sum_{i=1}^{I} TN_{ij} }{I}
### Response:
def tn_mean(tasmin, freq=):
r
arr = tasmin.resample(time=freq) if freq else tasmin
return arr.mean(dim=, keep_attrs=True) |
def download(url):
file_name = os.path.split(url)[1]
file = urlopen(url)
with open(file_name, ) as f:
f.write(file.read())
print("文件下载成功:%s " % file_name) | 输入文件url,下载该文件 | ### Input:
输入文件url,下载该文件
### Response:
def download(url):
file_name = os.path.split(url)[1]
file = urlopen(url)
with open(file_name, ) as f:
f.write(file.read())
print("文件下载成功:%s " % file_name) |
def convertToFree(stream, length_limit=True):
linestack = []
for line in stream:
convline = FortranLine(line, length_limit)
if convline.is_regular:
if convline.isContinuation and linestack:
linestack[0].continueLine()
for l in linestack:
yield str(l)
linestack = []
linestack.append(convline)
for l in linestack:
yield str(l) | Convert stream from fixed source form to free source form. | ### Input:
Convert stream from fixed source form to free source form.
### Response:
def convertToFree(stream, length_limit=True):
linestack = []
for line in stream:
convline = FortranLine(line, length_limit)
if convline.is_regular:
if convline.isContinuation and linestack:
linestack[0].continueLine()
for l in linestack:
yield str(l)
linestack = []
linestack.append(convline)
for l in linestack:
yield str(l) |
def get_or_build_user(self, username, ldap_user):
model = self.get_user_model()
if self.settings.USER_QUERY_FIELD:
query_field = self.settings.USER_QUERY_FIELD
query_value = ldap_user.attrs[self.settings.USER_ATTR_MAP[query_field]][0]
lookup = query_field
else:
query_field = model.USERNAME_FIELD
query_value = username.lower()
lookup = "{}__iexact".format(query_field)
try:
user = model.objects.get(**{lookup: query_value})
except model.DoesNotExist:
user = model(**{query_field: query_value})
built = True
else:
built = False
return (user, built) | This must return a (User, built) 2-tuple for the given LDAP user.
username is the Django-friendly username of the user. ldap_user.dn is
the user's DN and ldap_user.attrs contains all of their LDAP
attributes.
The returned User object may be an unsaved model instance. | ### Input:
This must return a (User, built) 2-tuple for the given LDAP user.
username is the Django-friendly username of the user. ldap_user.dn is
the user's DN and ldap_user.attrs contains all of their LDAP
attributes.
The returned User object may be an unsaved model instance.
### Response:
def get_or_build_user(self, username, ldap_user):
model = self.get_user_model()
if self.settings.USER_QUERY_FIELD:
query_field = self.settings.USER_QUERY_FIELD
query_value = ldap_user.attrs[self.settings.USER_ATTR_MAP[query_field]][0]
lookup = query_field
else:
query_field = model.USERNAME_FIELD
query_value = username.lower()
lookup = "{}__iexact".format(query_field)
try:
user = model.objects.get(**{lookup: query_value})
except model.DoesNotExist:
user = model(**{query_field: query_value})
built = True
else:
built = False
return (user, built) |
def rgb_to_yiq(rgb):
r, g, b = rgb[0] / 255, rgb[1] / 255, rgb[2] / 255
y = (0.299 * r) + (0.587 * g) + (0.114 * b)
i = (0.596 * r) - (0.275 * g) - (0.321 * b)
q = (0.212 * r) - (0.528 * g) + (0.311 * b)
return round(y, 3), round(i, 3), round(q, 3) | Convert an RGB color representation to a YIQ color representation.
(r, g, b) :: r -> [0, 255]
g -> [0, 255]
b -> [0, 255]
:param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.
:return: YIQ representation of the input RGB value.
:rtype: tuple | ### Input:
Convert an RGB color representation to a YIQ color representation.
(r, g, b) :: r -> [0, 255]
g -> [0, 255]
b -> [0, 255]
:param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.
:return: YIQ representation of the input RGB value.
:rtype: tuple
### Response:
def rgb_to_yiq(rgb):
r, g, b = rgb[0] / 255, rgb[1] / 255, rgb[2] / 255
y = (0.299 * r) + (0.587 * g) + (0.114 * b)
i = (0.596 * r) - (0.275 * g) - (0.321 * b)
q = (0.212 * r) - (0.528 * g) + (0.311 * b)
return round(y, 3), round(i, 3), round(q, 3) |
def _get_download_table_ids(self):
all_table_names = []
logger.info()
tables = self.service.tables()
request = tables.list(projectId=self._PROJECT_ID,
datasetId=self._DATASET_ID)
while request is not None:
response = request.execute()
if not in response:
response[] = []
for table in response[]:
if table[] != :
logger.debug(,
table[][],
table[])
continue
if not self._table_re.match(table[][]):
logger.debug(,
table[][])
continue
all_table_names.append(table[][])
request = tables.list_next(previous_request=request,
previous_response=response)
return sorted(all_table_names) | Get a list of PyPI downloads table (sharded per day) IDs.
:return: list of table names (strings)
:rtype: ``list`` | ### Input:
Get a list of PyPI downloads table (sharded per day) IDs.
:return: list of table names (strings)
:rtype: ``list``
### Response:
def _get_download_table_ids(self):
all_table_names = []
logger.info()
tables = self.service.tables()
request = tables.list(projectId=self._PROJECT_ID,
datasetId=self._DATASET_ID)
while request is not None:
response = request.execute()
if not in response:
response[] = []
for table in response[]:
if table[] != :
logger.debug(,
table[][],
table[])
continue
if not self._table_re.match(table[][]):
logger.debug(,
table[][])
continue
all_table_names.append(table[][])
request = tables.list_next(previous_request=request,
previous_response=response)
return sorted(all_table_names) |
def add_header_info(data_api, struct_inflator):
struct_inflator.set_header_info(data_api.r_free,
data_api.r_work,
data_api.resolution,
data_api.title,
data_api.deposition_date,
data_api.release_date,
data_api.experimental_methods) | Add ancilliary header information to the structure.
:param data_api the interface to the decoded data
:param struct_inflator the interface to put the data into the client object | ### Input:
Add ancilliary header information to the structure.
:param data_api the interface to the decoded data
:param struct_inflator the interface to put the data into the client object
### Response:
def add_header_info(data_api, struct_inflator):
struct_inflator.set_header_info(data_api.r_free,
data_api.r_work,
data_api.resolution,
data_api.title,
data_api.deposition_date,
data_api.release_date,
data_api.experimental_methods) |
def publish(self, topic=None, msg=None, modname=None,
pre_fire_hook=None, **kw):
topic = topic or
msg = msg or dict()
modname = modname or guess_calling_module(default="fedmsg")
topic = .join([modname, topic])
if topic[:len(self.c[])] != self.c[]:
topic = .join([
self.c[],
self.c[],
topic,
])
if isinstance(topic, six.text_type):
topic = to_bytes(topic, encoding=, nonstring="passthru")
year = datetime.datetime.now().year
self._i += 1
msg = dict(
topic=topic.decode(),
msg=msg,
timestamp=int(time.time()),
msg_id=str(year) + + str(uuid.uuid4()),
i=self._i,
username=getpass.getuser(),
)
if self.c.get(, False):
if not self.c.get("crypto_backend") == "gpg":
if in self.c:
cert_index = "%s.%s" % (self.c[],
self.hostname)
else:
cert_index = self.c[]
if cert_index == :
cert_index = "shell.%s" % self.hostname
self.c[] = self.c[][cert_index]
else:
if not in self.c:
self.c[] = self.c[][self.hostname]
if self.c.get(, False):
msg = fedmsg.crypto.sign(msg, **self.c)
store = self.c.get(, None)
if store:
msg = store.add(msg)
if pre_fire_hook:
pre_fire_hook(msg)
if self.c.get(, True):
self.publisher.send_multipart(
[topic, fedmsg.encoding.dumps(msg).encode()],
flags=zmq.NOBLOCK,
)
else:
jsonify=False,
) | Send a message over the publishing zeromq socket.
>>> import fedmsg
>>> fedmsg.publish(topic='testing', modname='test', msg={
... 'test': "Hello World",
... })
The above snippet will send the message ``'{test: "Hello World"}'``
over the ``<topic_prefix>.dev.test.testing`` topic. The fully qualified
topic of a message is constructed out of the following pieces:
<:ref:`conf-topic-prefix`>.<:ref:`conf-environment`>.<``modname``>.<``topic``>
This function (and other API functions) do a little bit more
heavy lifting than they let on. If the "zeromq context" is not yet
initialized, :func:`fedmsg.init` is called to construct it and
store it as :data:`fedmsg.__local.__context` before anything else is
done.
**An example from Fedora Tagger -- SQLAlchemy encoding**
Here's an example from
`fedora-tagger <https://github.com/fedora-infra/fedora-tagger>`_ that
sends the information about a new tag over
``org.fedoraproject.{dev,stg,prod}.fedoratagger.tag.update``::
>>> import fedmsg
>>> fedmsg.publish(topic='tag.update', msg={
... 'user': user,
... 'tag': tag,
... })
Note that the `tag` and `user` objects are SQLAlchemy objects defined
by tagger. They both have ``.__json__()`` methods which
:func:`fedmsg.publish` uses to encode both objects as stringified
JSON for you. Under the hood, specifically, ``.publish`` uses
:mod:`fedmsg.encoding` to do this.
``fedmsg`` has also guessed the module name (``modname``) of it's
caller and inserted it into the topic for you. The code from which
we stole the above snippet lives in
``fedoratagger.controllers.root``. ``fedmsg`` figured that out and
stripped it down to just ``fedoratagger`` for the final topic of
``org.fedoraproject.{dev,stg,prod}.fedoratagger.tag.update``.
**Shell Usage**
You could also use the ``fedmsg-logger`` from a shell script like so::
$ echo "Hello, world." | fedmsg-logger --topic testing
$ echo '{"foo": "bar"}' | fedmsg-logger --json-input
:param topic: The message topic suffix. This suffix is joined to the
configured topic prefix (e.g. ``org.fedoraproject``), environment
(e.g. ``prod``, ``dev``, etc.), and modname.
:type topic: unicode
:param msg: A message to publish. This message will be JSON-encoded
prior to being sent, so the object must be composed of JSON-
serializable data types. Please note that if this is already a
string JSON serialization will be applied to that string.
:type msg: dict
:param modname: The module name that is publishing the message. If this
is omitted, ``fedmsg`` will try to guess the name of the module
that called it and use that to produce an intelligent topic.
Specifying ``modname`` explicitly overrides this behavior.
:type modname: unicode
:param pre_fire_hook: A callable that will be called with a single
argument -- the dict of the constructed message -- just before it
is handed off to ZeroMQ for publication.
:type pre_fire_hook: function | ### Input:
Send a message over the publishing zeromq socket.
>>> import fedmsg
>>> fedmsg.publish(topic='testing', modname='test', msg={
... 'test': "Hello World",
... })
The above snippet will send the message ``'{test: "Hello World"}'``
over the ``<topic_prefix>.dev.test.testing`` topic. The fully qualified
topic of a message is constructed out of the following pieces:
<:ref:`conf-topic-prefix`>.<:ref:`conf-environment`>.<``modname``>.<``topic``>
This function (and other API functions) do a little bit more
heavy lifting than they let on. If the "zeromq context" is not yet
initialized, :func:`fedmsg.init` is called to construct it and
store it as :data:`fedmsg.__local.__context` before anything else is
done.
**An example from Fedora Tagger -- SQLAlchemy encoding**
Here's an example from
`fedora-tagger <https://github.com/fedora-infra/fedora-tagger>`_ that
sends the information about a new tag over
``org.fedoraproject.{dev,stg,prod}.fedoratagger.tag.update``::
>>> import fedmsg
>>> fedmsg.publish(topic='tag.update', msg={
... 'user': user,
... 'tag': tag,
... })
Note that the `tag` and `user` objects are SQLAlchemy objects defined
by tagger. They both have ``.__json__()`` methods which
:func:`fedmsg.publish` uses to encode both objects as stringified
JSON for you. Under the hood, specifically, ``.publish`` uses
:mod:`fedmsg.encoding` to do this.
``fedmsg`` has also guessed the module name (``modname``) of it's
caller and inserted it into the topic for you. The code from which
we stole the above snippet lives in
``fedoratagger.controllers.root``. ``fedmsg`` figured that out and
stripped it down to just ``fedoratagger`` for the final topic of
``org.fedoraproject.{dev,stg,prod}.fedoratagger.tag.update``.
**Shell Usage**
You could also use the ``fedmsg-logger`` from a shell script like so::
$ echo "Hello, world." | fedmsg-logger --topic testing
$ echo '{"foo": "bar"}' | fedmsg-logger --json-input
:param topic: The message topic suffix. This suffix is joined to the
configured topic prefix (e.g. ``org.fedoraproject``), environment
(e.g. ``prod``, ``dev``, etc.), and modname.
:type topic: unicode
:param msg: A message to publish. This message will be JSON-encoded
prior to being sent, so the object must be composed of JSON-
serializable data types. Please note that if this is already a
string JSON serialization will be applied to that string.
:type msg: dict
:param modname: The module name that is publishing the message. If this
is omitted, ``fedmsg`` will try to guess the name of the module
that called it and use that to produce an intelligent topic.
Specifying ``modname`` explicitly overrides this behavior.
:type modname: unicode
:param pre_fire_hook: A callable that will be called with a single
argument -- the dict of the constructed message -- just before it
is handed off to ZeroMQ for publication.
:type pre_fire_hook: function
### Response:
def publish(self, topic=None, msg=None, modname=None,
pre_fire_hook=None, **kw):
topic = topic or
msg = msg or dict()
modname = modname or guess_calling_module(default="fedmsg")
topic = .join([modname, topic])
if topic[:len(self.c[])] != self.c[]:
topic = .join([
self.c[],
self.c[],
topic,
])
if isinstance(topic, six.text_type):
topic = to_bytes(topic, encoding=, nonstring="passthru")
year = datetime.datetime.now().year
self._i += 1
msg = dict(
topic=topic.decode(),
msg=msg,
timestamp=int(time.time()),
msg_id=str(year) + + str(uuid.uuid4()),
i=self._i,
username=getpass.getuser(),
)
if self.c.get(, False):
if not self.c.get("crypto_backend") == "gpg":
if in self.c:
cert_index = "%s.%s" % (self.c[],
self.hostname)
else:
cert_index = self.c[]
if cert_index == :
cert_index = "shell.%s" % self.hostname
self.c[] = self.c[][cert_index]
else:
if not in self.c:
self.c[] = self.c[][self.hostname]
if self.c.get(, False):
msg = fedmsg.crypto.sign(msg, **self.c)
store = self.c.get(, None)
if store:
msg = store.add(msg)
if pre_fire_hook:
pre_fire_hook(msg)
if self.c.get(, True):
self.publisher.send_multipart(
[topic, fedmsg.encoding.dumps(msg).encode()],
flags=zmq.NOBLOCK,
)
else:
jsonify=False,
) |
def has_descriptor(self, descriptor):
for p in self.descriptors:
if p in descriptor:
return True
return False | Return ``True`` if the character has the given descriptor.
:param IPADescriptor descriptor: the descriptor to be checked against
:rtype: bool | ### Input:
Return ``True`` if the character has the given descriptor.
:param IPADescriptor descriptor: the descriptor to be checked against
:rtype: bool
### Response:
def has_descriptor(self, descriptor):
for p in self.descriptors:
if p in descriptor:
return True
return False |
def read_mac(self):
words = [self.read_efuse(2), self.read_efuse(1)]
bitstring = struct.pack(">II", *words)
bitstring = bitstring[2:8]
try:
return tuple(ord(b) for b in bitstring)
except TypeError:
return tuple(bitstring) | Read MAC from EFUSE region | ### Input:
Read MAC from EFUSE region
### Response:
def read_mac(self):
words = [self.read_efuse(2), self.read_efuse(1)]
bitstring = struct.pack(">II", *words)
bitstring = bitstring[2:8]
try:
return tuple(ord(b) for b in bitstring)
except TypeError:
return tuple(bitstring) |
def verify_initdict(initdict: InitDict) -> None:
if (not isinstance(initdict, dict) or
ARGS_LABEL not in initdict or
KWARGS_LABEL not in initdict):
raise ValueError("Not an InitDict dictionary") | Ensures that its parameter is a proper ``InitDict``, or raises
``ValueError``. | ### Input:
Ensures that its parameter is a proper ``InitDict``, or raises
``ValueError``.
### Response:
def verify_initdict(initdict: InitDict) -> None:
if (not isinstance(initdict, dict) or
ARGS_LABEL not in initdict or
KWARGS_LABEL not in initdict):
raise ValueError("Not an InitDict dictionary") |
def append_rows(self, indexes, values, new_cols=True):
for column in values:
if len(values[column]) > len(indexes):
raise ValueError( % column)
combined_index = self._index + indexes
if len(set(combined_index)) != len(combined_index):
raise IndexError()
if new_cols:
for col in values:
if col not in self._columns:
self._add_column(col)
self._index.extend(indexes)
for c, col in enumerate(self._columns):
self._data[c].extend(values.get(col, [None] * len(indexes)))
self._pad_data() | Appends rows of values to the end of the data. If there are new columns in the values and new_cols is True
they will be added. Be very careful with this function as for sort DataFrames it will not enforce sort order.
Use this only for speed when needed, be careful.
:param indexes: list of indexes
:param values: dictionary of values where the key is the column name and the value is a list
:param new_cols: if True add new columns in values, if False ignore
:return: nothing | ### Input:
Appends rows of values to the end of the data. If there are new columns in the values and new_cols is True
they will be added. Be very careful with this function as for sort DataFrames it will not enforce sort order.
Use this only for speed when needed, be careful.
:param indexes: list of indexes
:param values: dictionary of values where the key is the column name and the value is a list
:param new_cols: if True add new columns in values, if False ignore
:return: nothing
### Response:
def append_rows(self, indexes, values, new_cols=True):
for column in values:
if len(values[column]) > len(indexes):
raise ValueError( % column)
combined_index = self._index + indexes
if len(set(combined_index)) != len(combined_index):
raise IndexError()
if new_cols:
for col in values:
if col not in self._columns:
self._add_column(col)
self._index.extend(indexes)
for c, col in enumerate(self._columns):
self._data[c].extend(values.get(col, [None] * len(indexes)))
self._pad_data() |
def visit_table(self, layout):
table_content = self.get_table_content(layout)
cols_width = [0] * len(table_content[0])
for row in table_content:
for index, col in enumerate(row):
cols_width[index] = max(cols_width[index], len(col))
self.default_table(layout, table_content, cols_width)
self.writeln() | display a table as text | ### Input:
display a table as text
### Response:
def visit_table(self, layout):
table_content = self.get_table_content(layout)
cols_width = [0] * len(table_content[0])
for row in table_content:
for index, col in enumerate(row):
cols_width[index] = max(cols_width[index], len(col))
self.default_table(layout, table_content, cols_width)
self.writeln() |
def __field_to_parameter_type_and_format(self, field):
variant = field.variant
if variant == messages.Variant.MESSAGE:
raise TypeError()
return CUSTOM_VARIANT_MAP.get(variant) or (variant.name.lower(), None) | Converts the field variant type into a tuple describing the parameter.
Args:
field: An instance of a subclass of messages.Field.
Returns:
A tuple with the type and format of the field, respectively.
Raises:
TypeError: if the field variant is a message variant. | ### Input:
Converts the field variant type into a tuple describing the parameter.
Args:
field: An instance of a subclass of messages.Field.
Returns:
A tuple with the type and format of the field, respectively.
Raises:
TypeError: if the field variant is a message variant.
### Response:
def __field_to_parameter_type_and_format(self, field):
variant = field.variant
if variant == messages.Variant.MESSAGE:
raise TypeError()
return CUSTOM_VARIANT_MAP.get(variant) or (variant.name.lower(), None) |
def multi_find(*patterns, **kwargs):
out = {}
for pattern in set(patterns):
search_result = find(pattern,
best=kwargs.get(, True),
display=kwargs.get(, _DEFAULT_DISPLAY))
out[pattern] = search_result
if not kwargs.get(, _DEFAULT_DISPLAY):
return out | Execute multiple search tasks.
This function is based on the `find` function.
Depending on the search items, some information might overlap.
Optional arguments:
best: ``True``
Return only the best match with the interfaces IP networks
when the saerching pattern is a valid IP Address or Network.
display: ``True``
Display on the screen or return structured object? Default: `True` (return on the CLI).
CLI Example:
.. code-block:: bash
$ sudo salt-run net.multi_find Ethernet1/49 xe-0/1/2
Output Example:
.. code-block:: text
Pattern "Ethernet1/49" found in one of the following LLDP details
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Device | Interface | Parent Interface | Remote Chassis ID | Remote Port Description | Remote Port ID | Remote System Description | Remote System Name |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| edge01.oua04 | xe-0/1/2 | ae1 | DE:AD:BE:EF:DE:AD | Ethernet1/49 | | Cisco NX-OS(tm) n6000, Software (n6000-uk9) | edge07.oua04.dummy.net |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Details for interface xe-0/1/2
-----------------------------------------------------------------------------------------------------------------------
| Device | Interface | Interface Description | IP Addresses | Enabled | UP | MAC Address | Speed [Mbps] |
-----------------------------------------------------------------------------------------------------------------------
| edge01.oua04 | xe-0/1/2 | ae1 sw01.oua04 | | True | True | BE:EF:DE:AD:BE:EF | 10000 |
-----------------------------------------------------------------------------------------------------------------------
LLDP Neighbors for interface xe-0/1/2
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Device | Interface | Parent Interface | Remote Chassis ID | Remote Port Description | Remote Port ID | Remote System Description | Remote System Name |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| edge01.oua04 | xe-0/1/2 | ae1 | DE:AD:BE:EF:DE:AD | Ethernet1/49 | | Cisco NX-OS(tm) n6000, Software (n6000-uk9) | edge07.oua04.dummy.net |
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ### Input:
Execute multiple search tasks.
This function is based on the `find` function.
Depending on the search items, some information might overlap.
Optional arguments:
best: ``True``
Return only the best match with the interfaces IP networks
when the saerching pattern is a valid IP Address or Network.
display: ``True``
Display on the screen or return structured object? Default: `True` (return on the CLI).
CLI Example:
.. code-block:: bash
$ sudo salt-run net.multi_find Ethernet1/49 xe-0/1/2
Output Example:
.. code-block:: text
Pattern "Ethernet1/49" found in one of the following LLDP details
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Device | Interface | Parent Interface | Remote Chassis ID | Remote Port Description | Remote Port ID | Remote System Description | Remote System Name |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| edge01.oua04 | xe-0/1/2 | ae1 | DE:AD:BE:EF:DE:AD | Ethernet1/49 | | Cisco NX-OS(tm) n6000, Software (n6000-uk9) | edge07.oua04.dummy.net |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Details for interface xe-0/1/2
-----------------------------------------------------------------------------------------------------------------------
| Device | Interface | Interface Description | IP Addresses | Enabled | UP | MAC Address | Speed [Mbps] |
-----------------------------------------------------------------------------------------------------------------------
| edge01.oua04 | xe-0/1/2 | ae1 sw01.oua04 | | True | True | BE:EF:DE:AD:BE:EF | 10000 |
-----------------------------------------------------------------------------------------------------------------------
LLDP Neighbors for interface xe-0/1/2
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Device | Interface | Parent Interface | Remote Chassis ID | Remote Port Description | Remote Port ID | Remote System Description | Remote System Name |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| edge01.oua04 | xe-0/1/2 | ae1 | DE:AD:BE:EF:DE:AD | Ethernet1/49 | | Cisco NX-OS(tm) n6000, Software (n6000-uk9) | edge07.oua04.dummy.net |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
### Response:
def multi_find(*patterns, **kwargs):
out = {}
for pattern in set(patterns):
search_result = find(pattern,
best=kwargs.get(, True),
display=kwargs.get(, _DEFAULT_DISPLAY))
out[pattern] = search_result
if not kwargs.get(, _DEFAULT_DISPLAY):
return out |
def dict_2_mat(data, fill = True):
if any([type(k) != int for k in list(data.keys())]):
raise RuntimeError("Dictionary cannot be converted to matrix, " +
"not all keys are ints")
base_shape = np.array(list(data.values())[0]).shape
result_shape = list(base_shape)
if fill:
result_shape.insert(0, max(data.keys()) + 1)
else:
result_shape.insert(0, len(list(data.keys())))
result = np.empty(result_shape) + np.nan
for (i, (k, v)) in enumerate(data.items()):
v = np.array(v)
if v.shape != base_shape:
raise RuntimeError("Dictionary cannot be converted to matrix, " +
"not all values have same dimensions")
result[fill and [k][0] or [i][0]] = v
return result | Creates a NumPy array from a dictionary with only integers as keys and
NumPy arrays as values. Dimension 0 of the resulting array is formed from
data.keys(). Missing values in keys can be filled up with np.nan (default)
or ignored.
Parameters
----------
data : dict
a dictionary with integers as keys and array-likes of the same shape
as values
fill : boolean
flag specifying if the resulting matrix will keep a correspondence
between dictionary keys and matrix indices by filling up missing keys
with matrices of NaNs. Defaults to True
Returns
-------
numpy array with one more dimension than the values of the input dict | ### Input:
Creates a NumPy array from a dictionary with only integers as keys and
NumPy arrays as values. Dimension 0 of the resulting array is formed from
data.keys(). Missing values in keys can be filled up with np.nan (default)
or ignored.
Parameters
----------
data : dict
a dictionary with integers as keys and array-likes of the same shape
as values
fill : boolean
flag specifying if the resulting matrix will keep a correspondence
between dictionary keys and matrix indices by filling up missing keys
with matrices of NaNs. Defaults to True
Returns
-------
numpy array with one more dimension than the values of the input dict
### Response:
def dict_2_mat(data, fill = True):
if any([type(k) != int for k in list(data.keys())]):
raise RuntimeError("Dictionary cannot be converted to matrix, " +
"not all keys are ints")
base_shape = np.array(list(data.values())[0]).shape
result_shape = list(base_shape)
if fill:
result_shape.insert(0, max(data.keys()) + 1)
else:
result_shape.insert(0, len(list(data.keys())))
result = np.empty(result_shape) + np.nan
for (i, (k, v)) in enumerate(data.items()):
v = np.array(v)
if v.shape != base_shape:
raise RuntimeError("Dictionary cannot be converted to matrix, " +
"not all values have same dimensions")
result[fill and [k][0] or [i][0]] = v
return result |
def _logger(self):
logger = logging.getLogger(self.NAME)
logger.setLevel(self.LOG_LEVEL)
shandler = logging.StreamHandler(sys.stdout)
fmt =
fmt +=
shandler.setFormatter(logging.Formatter(fmt))
logger.addHandler(shandler)
return logger | Create a logger to be used between processes.
:returns: Logging instance. | ### Input:
Create a logger to be used between processes.
:returns: Logging instance.
### Response:
def _logger(self):
logger = logging.getLogger(self.NAME)
logger.setLevel(self.LOG_LEVEL)
shandler = logging.StreamHandler(sys.stdout)
fmt =
fmt +=
shandler.setFormatter(logging.Formatter(fmt))
logger.addHandler(shandler)
return logger |
def clusters(self):
if self._clusters is not None:
self.__init()
Cs = []
for c in self._clusters:
url = self._url + "/%s" % c[]
Cs.append(Cluster(url=url,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port,
initialize=True))
self._clusters = Cs
return self._clusters | returns the cluster object for each server | ### Input:
returns the cluster object for each server
### Response:
def clusters(self):
if self._clusters is not None:
self.__init()
Cs = []
for c in self._clusters:
url = self._url + "/%s" % c[]
Cs.append(Cluster(url=url,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port,
initialize=True))
self._clusters = Cs
return self._clusters |
def _transform(self, X):
X = self._matrix_adjust(X)
X = check_array(X, accept_sparse=, force_all_finite=False,
dtype=int)
if X.min() < 0:
raise ValueError("X needs to contain only non-negative integers.")
n_samples, n_features = X.shape
indices = self.feature_indices_
if n_features != indices.shape[0] - 1:
raise ValueError("X has different shape than during fitting."
" Expected %d, got %d."
% (indices.shape[0] - 1, n_features))
if self.minimum_fraction is not None:
for column in range(X.shape[1]):
if sparse.issparse(X):
indptr_start = X.indptr[column]
indptr_end = X.indptr[column + 1]
unique = np.unique(X.data[indptr_start:indptr_end])
else:
unique = np.unique(X[:, column])
for unique_value in unique:
if unique_value not in self.do_not_replace_by_other_[column]:
if sparse.issparse(X):
indptr_start = X.indptr[column]
indptr_end = X.indptr[column + 1]
X.data[indptr_start:indptr_end][
X.data[indptr_start:indptr_end] ==
unique_value] = SPARSE_ENCODINGS[]
else:
X[:, column][X[:, column] == unique_value] = SPARSE_ENCODINGS[]
if sparse.issparse(X):
n_values_check = X.max(axis=0).toarray().flatten() + 1
else:
n_values_check = np.max(X, axis=0) + 1
if (n_values_check > self.n_values_).any():
for i, n_value_check in enumerate(n_values_check):
if (n_value_check - 1) >= self.n_values_[i]:
if sparse.issparse(X):
indptr_start = X.indptr[i]
indptr_end = X.indptr[i+1]
X.data[indptr_start:indptr_end][X.data[indptr_start:indptr_end] >= self.n_values_[i]] = 0
else:
X[:, i][X[:, i] >= self.n_values_[i]] = 0
if sparse.issparse(X):
row_indices = X.indices
column_indices = []
for i in range(len(X.indptr) - 1):
nbr = X.indptr[i + 1] - X.indptr[i]
column_indices_ = [indices[i]] * nbr
column_indices_ += X.data[X.indptr[i]:X.indptr[i + 1]]
column_indices.extend(column_indices_)
data = np.ones(X.data.size)
else:
column_indices = (X + indices[:-1]).ravel()
row_indices = np.repeat(np.arange(n_samples, dtype=np.int32),
n_features)
data = np.ones(n_samples * n_features)
out = sparse.coo_matrix((data, (row_indices, column_indices)),
shape=(n_samples, indices[-1]),
dtype=self.dtype).tocsc()
out = out[:, self.active_features_]
return out.tocsr() if self.sparse else out.toarray() | Asssume X contains only categorical features.
Parameters
----------
X : array-like or sparse matrix, shape=(n_samples, n_features)
Dense array or sparse matrix. | ### Input:
Asssume X contains only categorical features.
Parameters
----------
X : array-like or sparse matrix, shape=(n_samples, n_features)
Dense array or sparse matrix.
### Response:
def _transform(self, X):
X = self._matrix_adjust(X)
X = check_array(X, accept_sparse=, force_all_finite=False,
dtype=int)
if X.min() < 0:
raise ValueError("X needs to contain only non-negative integers.")
n_samples, n_features = X.shape
indices = self.feature_indices_
if n_features != indices.shape[0] - 1:
raise ValueError("X has different shape than during fitting."
" Expected %d, got %d."
% (indices.shape[0] - 1, n_features))
if self.minimum_fraction is not None:
for column in range(X.shape[1]):
if sparse.issparse(X):
indptr_start = X.indptr[column]
indptr_end = X.indptr[column + 1]
unique = np.unique(X.data[indptr_start:indptr_end])
else:
unique = np.unique(X[:, column])
for unique_value in unique:
if unique_value not in self.do_not_replace_by_other_[column]:
if sparse.issparse(X):
indptr_start = X.indptr[column]
indptr_end = X.indptr[column + 1]
X.data[indptr_start:indptr_end][
X.data[indptr_start:indptr_end] ==
unique_value] = SPARSE_ENCODINGS[]
else:
X[:, column][X[:, column] == unique_value] = SPARSE_ENCODINGS[]
if sparse.issparse(X):
n_values_check = X.max(axis=0).toarray().flatten() + 1
else:
n_values_check = np.max(X, axis=0) + 1
if (n_values_check > self.n_values_).any():
for i, n_value_check in enumerate(n_values_check):
if (n_value_check - 1) >= self.n_values_[i]:
if sparse.issparse(X):
indptr_start = X.indptr[i]
indptr_end = X.indptr[i+1]
X.data[indptr_start:indptr_end][X.data[indptr_start:indptr_end] >= self.n_values_[i]] = 0
else:
X[:, i][X[:, i] >= self.n_values_[i]] = 0
if sparse.issparse(X):
row_indices = X.indices
column_indices = []
for i in range(len(X.indptr) - 1):
nbr = X.indptr[i + 1] - X.indptr[i]
column_indices_ = [indices[i]] * nbr
column_indices_ += X.data[X.indptr[i]:X.indptr[i + 1]]
column_indices.extend(column_indices_)
data = np.ones(X.data.size)
else:
column_indices = (X + indices[:-1]).ravel()
row_indices = np.repeat(np.arange(n_samples, dtype=np.int32),
n_features)
data = np.ones(n_samples * n_features)
out = sparse.coo_matrix((data, (row_indices, column_indices)),
shape=(n_samples, indices[-1]),
dtype=self.dtype).tocsc()
out = out[:, self.active_features_]
return out.tocsr() if self.sparse else out.toarray() |
def _set_lsp_frr_bandwidth(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=lsp_frr_bandwidth.lsp_frr_bandwidth, is_container=, presence=False, yang_name="lsp-frr-bandwidth", rest_name="bandwidth", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u: {u: u, u: u}}, namespace=, defining_module=, yang_type=, is_config=True)
except (TypeError, ValueError):
raise ValueError({
: ,
: "container",
: ,
})
self.__lsp_frr_bandwidth = t
if hasattr(self, ):
self._set() | Setter method for lsp_frr_bandwidth, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/lsp_frr/lsp_frr_bandwidth (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_lsp_frr_bandwidth is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_lsp_frr_bandwidth() directly. | ### Input:
Setter method for lsp_frr_bandwidth, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/lsp_frr/lsp_frr_bandwidth (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_lsp_frr_bandwidth is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_lsp_frr_bandwidth() directly.
### Response:
def _set_lsp_frr_bandwidth(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=lsp_frr_bandwidth.lsp_frr_bandwidth, is_container=, presence=False, yang_name="lsp-frr-bandwidth", rest_name="bandwidth", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u: {u: u, u: u}}, namespace=, defining_module=, yang_type=, is_config=True)
except (TypeError, ValueError):
raise ValueError({
: ,
: "container",
: ,
})
self.__lsp_frr_bandwidth = t
if hasattr(self, ):
self._set() |
def add_peer_to_group(self, group_jid, peer_jid):
log.info("[+] Requesting to add user {} into the group {}".format(peer_jid, group_jid))
return self._send_xmpp_element(group_adminship.AddToGroupRequest(group_jid, peer_jid)) | Adds someone to a group
:param group_jid: The JID of the group into which to add a user
:param peer_jid: The JID of the user to add | ### Input:
Adds someone to a group
:param group_jid: The JID of the group into which to add a user
:param peer_jid: The JID of the user to add
### Response:
def add_peer_to_group(self, group_jid, peer_jid):
log.info("[+] Requesting to add user {} into the group {}".format(peer_jid, group_jid))
return self._send_xmpp_element(group_adminship.AddToGroupRequest(group_jid, peer_jid)) |
def build_image_from_git(self, url, image, git_path=None, git_commit=None,
copy_dockerfile_to=None,
stream=False, use_cache=False):
logger.info("building image from git repo specified as URL ",
image, git_path, url)
logger.info("will copy Dockerfile to ", copy_dockerfile_to)
temp_dir = tempfile.mkdtemp()
response = None
try:
clone_git_repo(url, temp_dir, git_commit)
build_file_path, build_file_dir = figure_out_build_file(temp_dir, git_path)
if copy_dockerfile_to:
shutil.copyfile(build_file_path, copy_dockerfile_to)
response = self.build_image_from_path(build_file_dir, image, use_cache=use_cache)
finally:
try:
shutil.rmtree(temp_dir)
except (IOError, OSError) as ex:
logger.warning("Failed to remove dir : %r", temp_dir, ex)
logger.info("build finished")
return response | build image from provided url and tag it
this operation is asynchronous and you should consume returned generator in order to wait
for build to finish
:param url: str
:param image: ImageName, name of the resulting image
:param git_path: str, path to dockerfile within gitrepo
:param copy_dockerfile_to: str, copy dockerfile to provided path
:param stream: bool, True returns generator, False returns str
:param use_cache: bool, True if you want to use cache
:return: generator | ### Input:
build image from provided url and tag it
this operation is asynchronous and you should consume returned generator in order to wait
for build to finish
:param url: str
:param image: ImageName, name of the resulting image
:param git_path: str, path to dockerfile within gitrepo
:param copy_dockerfile_to: str, copy dockerfile to provided path
:param stream: bool, True returns generator, False returns str
:param use_cache: bool, True if you want to use cache
:return: generator
### Response:
def build_image_from_git(self, url, image, git_path=None, git_commit=None,
copy_dockerfile_to=None,
stream=False, use_cache=False):
logger.info("building image from git repo specified as URL ",
image, git_path, url)
logger.info("will copy Dockerfile to ", copy_dockerfile_to)
temp_dir = tempfile.mkdtemp()
response = None
try:
clone_git_repo(url, temp_dir, git_commit)
build_file_path, build_file_dir = figure_out_build_file(temp_dir, git_path)
if copy_dockerfile_to:
shutil.copyfile(build_file_path, copy_dockerfile_to)
response = self.build_image_from_path(build_file_dir, image, use_cache=use_cache)
finally:
try:
shutil.rmtree(temp_dir)
except (IOError, OSError) as ex:
logger.warning("Failed to remove dir : %r", temp_dir, ex)
logger.info("build finished")
return response |
def extinction_query(lon, lat,
coordtype=,
sizedeg=5.0,
forcefetch=False,
cachedir=,
verbose=True,
timeout=10.0,
jitter=5.0):
equatorialgalacticequatorialgalacticre interested in the extinction only.
forcefetch : bool
If this is True, the query will be retried even if cached results for
it exist.
cachedir : str
This points to the directory where results will be downloaded.
verbose : bool
If True, will indicate progress and warn of any issues.
timeout : float
This sets the amount of time in seconds to wait for the service to
respond to our request.
jitter : float
This is used to control the scale of the random wait in seconds before
starting the query. Useful in parallelized situations.
Returns
-------
dict
A dict of the following form is returned::
{:{dict of extinction A_v values for several mag systems},
: array containing the full extinction table,
: the path to the full extinction table file on disk,
: or ,
: string repr of the request made to 2MASS DUST}
equatorial%.3f %.3f Equ J2000galactic%.3f %.3f galunknown coordinate type: %slocstrregSize%.3f~%s - %.1f%s.txtcachere forcefetching, do the query
if forcefetch or (not os.path.exists(cachefname)):
time.sleep(random.randint(1,jitter))
provenance =
try:
if verbose:
LOGINFO(
%
(lon, lat, coordtype, sizedeg))
req = requests.get(DUST_URL, dustparams, timeout=timeout)
req.raise_for_status()
resp = req.text
tableurl = DUST_REGEX.search(resp)
if tableurl:
tableurl = tableurl.group(0)
req2 = requests.get(tableurl, timeout=timeout)
with open(cachefname,) as outfd:
outfd.write(req2.content)
tablefname = cachefname
else:
LOGERROR(
% (coordtype,
lon,lat,sizedeg))
LOGERROR( % resp)
return None
except requests.exceptions.Timeout as e:
LOGERROR(
% (coordtype,
lon,lat,sizedeg))
return None
except Exception as e:
LOGEXCEPTION(
% (coordtype,
lon,lat,sizedeg))
return None
else:
if verbose:
LOGINFO(
%
(lon, lat, coordtype, sizedeg))
tablefname = cachefname
extinction_table = Table.read(tablefname, format=)
filters = np.array(extinction_table[])
a_sf11_byfilter = np.array(extinction_table[])
a_sfd98_byfilter = np.array(extinction_table[])
extdict = {:{x:{:y, :z} for
x,y,z in zip(filters,a_sf11_byfilter,a_sfd98_byfilter)},
:np.array(extinction_table),
:os.path.abspath(cachefname),
:provenance,
: % (coordtype,
lon,lat,
sizedeg)}
return extdict | This queries the 2MASS DUST service to find the extinction parameters
for the given `lon`, `lat`.
Parameters
----------
lon,lat: float
These are decimal right ascension and declination if `coordtype =
'equatorial'`. These are are decimal Galactic longitude and latitude if
`coordtype = 'galactic'`.
coordtype : {'equatorial','galactic'}
Sets the type of coordinates passed in as `lon`, `lat`.
sizedeg : float
This is the width of the image returned by the DUST service. This can
usually be left as-is if you're interested in the extinction only.
forcefetch : bool
If this is True, the query will be retried even if cached results for
it exist.
cachedir : str
This points to the directory where results will be downloaded.
verbose : bool
If True, will indicate progress and warn of any issues.
timeout : float
This sets the amount of time in seconds to wait for the service to
respond to our request.
jitter : float
This is used to control the scale of the random wait in seconds before
starting the query. Useful in parallelized situations.
Returns
-------
dict
A dict of the following form is returned::
{'Amag':{dict of extinction A_v values for several mag systems},
'table': array containing the full extinction table,
'tablefile': the path to the full extinction table file on disk,
'provenance': 'cached' or 'new download',
'request': string repr of the request made to 2MASS DUST} | ### Input:
This queries the 2MASS DUST service to find the extinction parameters
for the given `lon`, `lat`.
Parameters
----------
lon,lat: float
These are decimal right ascension and declination if `coordtype =
'equatorial'`. These are are decimal Galactic longitude and latitude if
`coordtype = 'galactic'`.
coordtype : {'equatorial','galactic'}
Sets the type of coordinates passed in as `lon`, `lat`.
sizedeg : float
This is the width of the image returned by the DUST service. This can
usually be left as-is if you're interested in the extinction only.
forcefetch : bool
If this is True, the query will be retried even if cached results for
it exist.
cachedir : str
This points to the directory where results will be downloaded.
verbose : bool
If True, will indicate progress and warn of any issues.
timeout : float
This sets the amount of time in seconds to wait for the service to
respond to our request.
jitter : float
This is used to control the scale of the random wait in seconds before
starting the query. Useful in parallelized situations.
Returns
-------
dict
A dict of the following form is returned::
{'Amag':{dict of extinction A_v values for several mag systems},
'table': array containing the full extinction table,
'tablefile': the path to the full extinction table file on disk,
'provenance': 'cached' or 'new download',
'request': string repr of the request made to 2MASS DUST}
### Response:
def extinction_query(lon, lat,
coordtype=,
sizedeg=5.0,
forcefetch=False,
cachedir=,
verbose=True,
timeout=10.0,
jitter=5.0):
equatorialgalacticequatorialgalacticre interested in the extinction only.
forcefetch : bool
If this is True, the query will be retried even if cached results for
it exist.
cachedir : str
This points to the directory where results will be downloaded.
verbose : bool
If True, will indicate progress and warn of any issues.
timeout : float
This sets the amount of time in seconds to wait for the service to
respond to our request.
jitter : float
This is used to control the scale of the random wait in seconds before
starting the query. Useful in parallelized situations.
Returns
-------
dict
A dict of the following form is returned::
{:{dict of extinction A_v values for several mag systems},
: array containing the full extinction table,
: the path to the full extinction table file on disk,
: or ,
: string repr of the request made to 2MASS DUST}
equatorial%.3f %.3f Equ J2000galactic%.3f %.3f galunknown coordinate type: %slocstrregSize%.3f~%s - %.1f%s.txtcachere forcefetching, do the query
if forcefetch or (not os.path.exists(cachefname)):
time.sleep(random.randint(1,jitter))
provenance =
try:
if verbose:
LOGINFO(
%
(lon, lat, coordtype, sizedeg))
req = requests.get(DUST_URL, dustparams, timeout=timeout)
req.raise_for_status()
resp = req.text
tableurl = DUST_REGEX.search(resp)
if tableurl:
tableurl = tableurl.group(0)
req2 = requests.get(tableurl, timeout=timeout)
with open(cachefname,) as outfd:
outfd.write(req2.content)
tablefname = cachefname
else:
LOGERROR(
% (coordtype,
lon,lat,sizedeg))
LOGERROR( % resp)
return None
except requests.exceptions.Timeout as e:
LOGERROR(
% (coordtype,
lon,lat,sizedeg))
return None
except Exception as e:
LOGEXCEPTION(
% (coordtype,
lon,lat,sizedeg))
return None
else:
if verbose:
LOGINFO(
%
(lon, lat, coordtype, sizedeg))
tablefname = cachefname
extinction_table = Table.read(tablefname, format=)
filters = np.array(extinction_table[])
a_sf11_byfilter = np.array(extinction_table[])
a_sfd98_byfilter = np.array(extinction_table[])
extdict = {:{x:{:y, :z} for
x,y,z in zip(filters,a_sf11_byfilter,a_sfd98_byfilter)},
:np.array(extinction_table),
:os.path.abspath(cachefname),
:provenance,
: % (coordtype,
lon,lat,
sizedeg)}
return extdict |
def deserialize(cls, target_class, array):
session_server = target_class.__new__(target_class)
session_server.__dict__ = {
cls._ATTRIBUTE_ID: converter.deserialize(
core.Id,
array[cls._INDEX_ID][cls._FIELD_ID]
),
cls._ATTRIBUTE_TOKEN: converter.deserialize(
core.SessionToken,
array[cls._INDEX_TOKEN][cls._FIELD_TOKEN]
),
cls._ATTRIBUTE_USER_COMPANY: None,
cls._ATTRIBUTE_USER_PERSON: None,
}
user_dict_wrapped = array[cls._INDEX_USER]
if cls._FIELD_USER_COMPANY in user_dict_wrapped:
session_server.__dict__[cls._ATTRIBUTE_USER_COMPANY] = \
converter.deserialize(
endpoint.UserCompany,
user_dict_wrapped[cls._FIELD_USER_COMPANY]
)
elif cls._FIELD_USER_PERSON in user_dict_wrapped:
session_server.__dict__[cls._ATTRIBUTE_USER_PERSON] = \
converter.deserialize(
endpoint.UserPerson,
user_dict_wrapped[cls._FIELD_USER_PERSON]
)
elif cls._FIELD_USER_API_KEY in user_dict_wrapped:
session_server.__dict__[cls._ATTRIBUTE_USER_API_KEY] = \
converter.deserialize(
endpoint.UserApiKey,
user_dict_wrapped[cls._FIELD_USER_API_KEY]
)
else:
raise BunqException(cls._ERROR_COULD_NOT_DETERMINE_USER)
return session_server | :type target_class: core.SessionServer|type
:type array: list
:rtype: core.SessionServer | ### Input:
:type target_class: core.SessionServer|type
:type array: list
:rtype: core.SessionServer
### Response:
def deserialize(cls, target_class, array):
session_server = target_class.__new__(target_class)
session_server.__dict__ = {
cls._ATTRIBUTE_ID: converter.deserialize(
core.Id,
array[cls._INDEX_ID][cls._FIELD_ID]
),
cls._ATTRIBUTE_TOKEN: converter.deserialize(
core.SessionToken,
array[cls._INDEX_TOKEN][cls._FIELD_TOKEN]
),
cls._ATTRIBUTE_USER_COMPANY: None,
cls._ATTRIBUTE_USER_PERSON: None,
}
user_dict_wrapped = array[cls._INDEX_USER]
if cls._FIELD_USER_COMPANY in user_dict_wrapped:
session_server.__dict__[cls._ATTRIBUTE_USER_COMPANY] = \
converter.deserialize(
endpoint.UserCompany,
user_dict_wrapped[cls._FIELD_USER_COMPANY]
)
elif cls._FIELD_USER_PERSON in user_dict_wrapped:
session_server.__dict__[cls._ATTRIBUTE_USER_PERSON] = \
converter.deserialize(
endpoint.UserPerson,
user_dict_wrapped[cls._FIELD_USER_PERSON]
)
elif cls._FIELD_USER_API_KEY in user_dict_wrapped:
session_server.__dict__[cls._ATTRIBUTE_USER_API_KEY] = \
converter.deserialize(
endpoint.UserApiKey,
user_dict_wrapped[cls._FIELD_USER_API_KEY]
)
else:
raise BunqException(cls._ERROR_COULD_NOT_DETERMINE_USER)
return session_server |
def rectify_multipart_form_data(self, data):
for name, field in self.base_fields.items():
try:
field.implode_multi_values(name, data)
except AttributeError:
pass
return data | If a widget was converted and the Form data was submitted through a multipart request,
then these data fields must be converted to suit the Django Form validation | ### Input:
If a widget was converted and the Form data was submitted through a multipart request,
then these data fields must be converted to suit the Django Form validation
### Response:
def rectify_multipart_form_data(self, data):
for name, field in self.base_fields.items():
try:
field.implode_multi_values(name, data)
except AttributeError:
pass
return data |
def positionAt( self, location, fixedX = None, fixedY = None ):
rect = self.sceneRect()
if rect.height() < self.minimumHeight():
rect.setHeight(self.minimumHeight())
if rect.width() < self.minimumWidth():
rect.setWidth(self.minimumWidth())
cx = rect.center().x()
cy = rect.center().y()
x = cx
y = cy
if ( location == XConnectionLocation.Left ):
x = rect.left()
elif ( location & XConnectionLocation.Right ):
x = rect.right()
elif ( location & XConnectionLocation.Top ):
y = rect.top()
elif location & XConnectionLocation.Bottom:
y = rect.bottom()
if fixedX != None:
x = rect.x() + fixedX
if fixedY != None:
y = rect.y() + fixedY
return QPointF(x, y) | Calculates the position at the inputed location.
:param location <XConnectionLocation>
:param fixedX <float> || None
:param fixedY <float> || None
:return <QPointF> | ### Input:
Calculates the position at the inputed location.
:param location <XConnectionLocation>
:param fixedX <float> || None
:param fixedY <float> || None
:return <QPointF>
### Response:
def positionAt( self, location, fixedX = None, fixedY = None ):
rect = self.sceneRect()
if rect.height() < self.minimumHeight():
rect.setHeight(self.minimumHeight())
if rect.width() < self.minimumWidth():
rect.setWidth(self.minimumWidth())
cx = rect.center().x()
cy = rect.center().y()
x = cx
y = cy
if ( location == XConnectionLocation.Left ):
x = rect.left()
elif ( location & XConnectionLocation.Right ):
x = rect.right()
elif ( location & XConnectionLocation.Top ):
y = rect.top()
elif location & XConnectionLocation.Bottom:
y = rect.bottom()
if fixedX != None:
x = rect.x() + fixedX
if fixedY != None:
y = rect.y() + fixedY
return QPointF(x, y) |
def delete_webhooks_with_name(api, name):
for webhook in api.webhooks.list():
if webhook.name == name:
print("Deleting Webhook:", webhook.name, webhook.targetUrl)
api.webhooks.delete(webhook.id) | Find a webhook by name. | ### Input:
Find a webhook by name.
### Response:
def delete_webhooks_with_name(api, name):
for webhook in api.webhooks.list():
if webhook.name == name:
print("Deleting Webhook:", webhook.name, webhook.targetUrl)
api.webhooks.delete(webhook.id) |
def _ReconstructPath(self, came_from, current_node):
if current_node in came_from:
(previous_node, previous_edge) = came_from[current_node]
if previous_edge.GetPoint(0) == current_node:
previous_edge = previous_edge.Reversed()
p = self._ReconstructPath(came_from, previous_node)
return Poly.MergePolys([p, previous_edge], merge_point_threshold=0)
else:
return Poly([], ) | Helper method for ShortestPath, to reconstruct path.
Arguments:
came_from: a dictionary mapping Point to (Point, Poly) tuples.
This dictionary keeps track of the previous neighbor to a node, and
the edge used to get from the previous neighbor to the node.
current_node: the current Point in the path.
Returns:
A Poly that represents the path through the graph from the start of the
search to current_node. | ### Input:
Helper method for ShortestPath, to reconstruct path.
Arguments:
came_from: a dictionary mapping Point to (Point, Poly) tuples.
This dictionary keeps track of the previous neighbor to a node, and
the edge used to get from the previous neighbor to the node.
current_node: the current Point in the path.
Returns:
A Poly that represents the path through the graph from the start of the
search to current_node.
### Response:
def _ReconstructPath(self, came_from, current_node):
if current_node in came_from:
(previous_node, previous_edge) = came_from[current_node]
if previous_edge.GetPoint(0) == current_node:
previous_edge = previous_edge.Reversed()
p = self._ReconstructPath(came_from, previous_node)
return Poly.MergePolys([p, previous_edge], merge_point_threshold=0)
else:
return Poly([], ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.