_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q231100 | ParamState.param_help_tree | train | def param_help_tree(self):
'''return a "help tree", a map between a parameter and its metadata. May return None if help is not available'''
if self.xml_filepath is not None:
print("param: using xml_filepath=%s" % self.xml_filepath)
path = self.xml_filepath
else:
... | python | {
"resource": ""
} |
q231101 | ParamState.param_apropos | train | def param_apropos(self, args):
'''search parameter help for a keyword, list those parameters'''
if len(args) == 0:
print("Usage: param apropos keyword")
return
htree = self.param_help_tree()
if htree is None:
return
contains = {}
for ... | python | {
"resource": ""
} |
q231102 | ParamModule.get_component_id_list | train | def get_component_id_list(self, system_id):
'''get list of component IDs with parameters for a given system ID'''
ret = []
for (s,c) in self.mpstate.mav_param_by_sysid.keys():
if s == system_id:
ret.append(c)
return ret | python | {
"resource": ""
} |
q231103 | ParamModule.get_sysid | train | def get_sysid(self):
'''get sysid tuple to use for parameters'''
component = self.target_component
if component == 0:
component = 1
return (self.target_system, component) | python | {
"resource": ""
} |
q231104 | OptionParser.parse_args | train | def parse_args( self, args = None, values = None ):
'''
multiprocessing wrapper around _parse_args
'''
q = multiproc.Queue()
p = multiproc.Process(target=self._parse_args, args=(q, args, values))
p.start()
ret = q.get()
p.join()
return ret | python | {
"resource": ""
} |
q231105 | OptionParser._parse_args | train | def _parse_args( self, q, args, values):
'''
This is the heart of it all - overrides optparse.OptionParser.parse_args
@param arg is irrelevant and thus ignored,
it is here only for interface compatibility
'''
if wx.GetApp() is None:
self.app = wx.App( F... | python | {
"resource": ""
} |
q231106 | DNFZ.distance_from | train | def distance_from(self, lat, lon):
'''get distance from a point'''
lat1 = self.pkt['I105']['Lat']['val']
lon1 = self.pkt['I105']['Lon']['val']
return mp_util.gps_distance(lat1, lon1, lat, lon) | python | {
"resource": ""
} |
q231107 | DNFZ.randpos | train | def randpos(self):
'''random initial position'''
self.setpos(gen_settings.home_lat, gen_settings.home_lon)
self.move(random.uniform(0, 360), random.uniform(0, gen_settings.region_width)) | python | {
"resource": ""
} |
q231108 | DNFZ.ground_height | train | def ground_height(self):
'''return height above ground in feet'''
lat = self.pkt['I105']['Lat']['val']
lon = self.pkt['I105']['Lon']['val']
global ElevationMap
ret = ElevationMap.GetElevation(lat, lon)
ret -= gen_settings.wgs84_to_AMSL
return ret * 3.2807 | python | {
"resource": ""
} |
q231109 | DNFZ.move | train | def move(self, bearing, distance):
'''move position by bearing and distance'''
lat = self.pkt['I105']['Lat']['val']
lon = self.pkt['I105']['Lon']['val']
(lat, lon) = mp_util.gps_newpos(lat, lon, bearing, distance)
self.setpos(lat, lon) | python | {
"resource": ""
} |
q231110 | Aircraft.update | train | def update(self, deltat=1.0):
'''fly a square circuit'''
DNFZ.update(self, deltat)
self.dist_flown += self.speed * deltat
if self.dist_flown > self.circuit_width:
self.desired_heading = self.heading + 90
self.dist_flown = 0
if self.getalt() < self.ground_h... | python | {
"resource": ""
} |
q231111 | BirdOfPrey.update | train | def update(self, deltat=1.0):
'''fly circles, then dive'''
DNFZ.update(self, deltat)
self.time_circling += deltat
self.setheading(self.heading + self.turn_rate * deltat)
self.move(self.drift_heading, self.drift_speed)
if self.getalt() > self.max_alt or self.getalt() < sel... | python | {
"resource": ""
} |
q231112 | BirdMigrating.update | train | def update(self, deltat=1.0):
'''fly in long curves'''
DNFZ.update(self, deltat)
if (self.distance_from_home() > gen_settings.region_width or
self.getalt() < self.ground_height() or
self.getalt() > self.ground_height() + 1000):
self.randpos()
self.... | python | {
"resource": ""
} |
q231113 | Weather.update | train | def update(self, deltat=1.0):
'''straight lines, with short life'''
DNFZ.update(self, deltat)
self.lifetime -= deltat
if self.lifetime <= 0:
self.randpos()
self.lifetime = random.uniform(300,600) | python | {
"resource": ""
} |
q231114 | GenobstaclesModule.cmd_dropobject | train | def cmd_dropobject(self, obj):
'''drop an object on the map'''
latlon = self.module('map').click_position
if self.last_click is not None and self.last_click == latlon:
return
self.last_click = latlon
if latlon is not None:
obj.setpos(latlon[0], latlon[1])
... | python | {
"resource": ""
} |
q231115 | GenobstaclesModule.cmd_genobstacles | train | def cmd_genobstacles(self, args):
'''genobstacles command parser'''
usage = "usage: genobstacles <start|stop|restart|clearall|status|set>"
if len(args) == 0:
print(usage)
return
if args[0] == "set":
gen_settings.command(args[1:])
elif args[0] =... | python | {
"resource": ""
} |
q231116 | GenobstaclesModule.start | train | def start(self):
'''start sending packets'''
if self.sock is not None:
self.sock.close()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.connect(('', gen_setting... | python | {
"resource": ""
} |
q231117 | GenobstaclesModule.mavlink_packet | train | def mavlink_packet(self, m):
'''trigger sends from ATTITUDE packets'''
if not self.have_home and m.get_type() == 'GPS_RAW_INT' and m.fix_type >= 3:
gen_settings.home_lat = m.lat * 1.0e-7
gen_settings.home_lon = m.lon * 1.0e-7
self.have_home = True
if self.... | python | {
"resource": ""
} |
q231118 | ADSBVehicle.update | train | def update(self, state, tnow):
'''update the threat state'''
self.state = state
self.update_time = tnow | python | {
"resource": ""
} |
q231119 | ADSBModule.cmd_ADSB | train | def cmd_ADSB(self, args):
'''adsb command parser'''
usage = "usage: adsb <set>"
if len(args) == 0:
print(usage)
return
if args[0] == "status":
print("total threat count: %u active threat count: %u" %
(len(self.threat_vehicles), len(s... | python | {
"resource": ""
} |
q231120 | ADSBModule.update_threat_distances | train | def update_threat_distances(self, latlonalt):
'''update the distance between threats and vehicle'''
for id in self.threat_vehicles.keys():
threat_latlonalt = (self.threat_vehicles[id].state['lat'] * 1e-7,
self.threat_vehicles[id].state['lon'] * 1e-7,
... | python | {
"resource": ""
} |
q231121 | ADSBModule.check_threat_timeout | train | def check_threat_timeout(self):
'''check and handle threat time out'''
for id in self.threat_vehicles.keys():
if self.threat_vehicles[id].update_time == 0:
self.threat_vehicles[id].update_time = self.get_time()
dt = self.get_time() - self.threat_vehicles[id].updat... | python | {
"resource": ""
} |
q231122 | GoProModule.cmd_gopro_status | train | def cmd_gopro_status(self, args):
'''show gopro status'''
master = self.master
if 'GOPRO_HEARTBEAT' in master.messages:
print(master.messages['GOPRO_HEARTBEAT'])
else:
print("No GOPRO_HEARTBEAT messages") | python | {
"resource": ""
} |
q231123 | ConsoleFrame.on_text_url | train | def on_text_url(self, event):
'''handle double clicks on URL text'''
try:
import webbrowser
except ImportError:
return
mouse_event = event.GetMouseEvent()
if mouse_event.LeftDClick():
url_start = event.GetURLStart()
url_end = event.... | python | {
"resource": ""
} |
q231124 | HeliPlaneModule.update_channels | train | def update_channels(self):
'''update which channels provide input'''
self.interlock_channel = -1
self.override_channel = -1
self.zero_I_channel = -1
self.no_vtol_channel = -1
# output channels
self.rsc_out_channel = 9
self.fwd_thr_channel = 10
fo... | python | {
"resource": ""
} |
q231125 | RallyModule.rallyloader | train | def rallyloader(self):
'''rally loader by system ID'''
if not self.target_system in self.rallyloader_by_sysid:
self.rallyloader_by_sysid[self.target_system] = mavwp.MAVRallyLoader(self.settings.target_system,
se... | python | {
"resource": ""
} |
q231126 | dataflash_logger.packet_is_for_me | train | def packet_is_for_me(self, m):
'''returns true if this packet is appropriately addressed'''
if m.target_system != self.master.mav.srcSystem:
return False
if m.target_component != self.master.mav.srcComponent:
return False
# if have a sender we can also check the s... | python | {
"resource": ""
} |
q231127 | _convert_agg_to_wx_image | train | def _convert_agg_to_wx_image(agg, bbox):
"""
Convert the region of the agg buffer bounded by bbox to a wx.Image. If
bbox is None, the entire buffer is converted.
Note: agg must be a backend_agg.RendererAgg instance.
"""
if bbox is None:
# agg => rgb -> image
image = wx.EmptyIma... | python | {
"resource": ""
} |
q231128 | _convert_agg_to_wx_bitmap | train | def _convert_agg_to_wx_bitmap(agg, bbox):
"""
Convert the region of the agg buffer bounded by bbox to a wx.Bitmap. If
bbox is None, the entire buffer is converted.
Note: agg must be a backend_agg.RendererAgg instance.
"""
if bbox is None:
# agg => rgba buffer -> bitmap
return w... | python | {
"resource": ""
} |
q231129 | _WX28_clipped_agg_as_bitmap | train | def _WX28_clipped_agg_as_bitmap(agg, bbox):
"""
Convert the region of a the agg buffer bounded by bbox to a wx.Bitmap.
Note: agg must be a backend_agg.RendererAgg instance.
"""
l, b, width, height = bbox.bounds
r = l + width
t = b + height
srcBmp = wx.BitmapFromBufferRGBA(int(agg.width... | python | {
"resource": ""
} |
q231130 | FigureCanvasWxAgg.draw | train | def draw(self, drawDC=None):
"""
Render the figure using agg.
"""
DEBUG_MSG("draw()", 1, self)
FigureCanvasAgg.draw(self)
self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None)
self._isDrawn = True
self.gui_repaint(drawDC=drawDC) | python | {
"resource": ""
} |
q231131 | FigureCanvasWxAgg.blit | train | def blit(self, bbox=None):
"""
Transfer the region of the agg buffer defined by bbox to the display.
If bbox is None, the entire buffer is transferred.
"""
if bbox is None:
self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None)
self.gui_repaint... | python | {
"resource": ""
} |
q231132 | AntennaModule.cmd_antenna | train | def cmd_antenna(self, args):
'''set gcs location'''
if len(args) != 2:
if self.gcs_location is None:
print("GCS location not set")
else:
print("GCS location %s" % str(self.gcs_location))
return
self.gcs_location = (float(args[0]... | python | {
"resource": ""
} |
q231133 | SigningModule.passphrase_to_key | train | def passphrase_to_key(self, passphrase):
'''convert a passphrase to a 32 byte key'''
import hashlib
h = hashlib.new('sha256')
h.update(passphrase)
return h.digest() | python | {
"resource": ""
} |
q231134 | SigningModule.cmd_signing_setup | train | def cmd_signing_setup(self, args):
'''setup signing key on board'''
if len(args) == 0:
print("usage: signing setup passphrase")
return
if not self.master.mavlink20():
print("You must be using MAVLink2 for signing")
return
passphrase = args[... | python | {
"resource": ""
} |
q231135 | SigningModule.allow_unsigned | train | def allow_unsigned(self, mav, msgId):
'''see if an unsigned packet should be allowed'''
if self.allow is None:
self.allow = {
mavutil.mavlink.MAVLINK_MSG_ID_RADIO : True,
mavutil.mavlink.MAVLINK_MSG_ID_RADIO_STATUS : True
}
if msgId in ... | python | {
"resource": ""
} |
q231136 | SigningModule.cmd_signing_key | train | def cmd_signing_key(self, args):
'''set signing key on connection'''
if len(args) == 0:
print("usage: signing setup passphrase")
return
if not self.master.mavlink20():
print("You must be using MAVLink2 for signing")
return
passphrase = args... | python | {
"resource": ""
} |
q231137 | SigningModule.cmd_signing_remove | train | def cmd_signing_remove(self, args):
'''remove signing from server'''
if not self.master.mavlink20():
print("You must be using MAVLink2 for signing")
return
self.master.mav.setup_signing_send(self.target_system, self.target_component, [0]*32, 0)
self.master.disable... | python | {
"resource": ""
} |
q231138 | OutputModule.cmd_output | train | def cmd_output(self, args):
'''handle output commands'''
if len(args) < 1 or args[0] == "list":
self.cmd_output_list()
elif args[0] == "add":
if len(args) != 2:
print("Usage: output add OUTPUT")
return
self.cmd_output_add(args[1... | python | {
"resource": ""
} |
q231139 | OutputModule.cmd_output_add | train | def cmd_output_add(self, args):
'''add new output'''
device = args[0]
print("Adding output %s" % device)
try:
conn = mavutil.mavlink_connection(device, input=False, source_system=self.settings.source_system)
conn.mav.srcComponent = self.settings.source_component
... | python | {
"resource": ""
} |
q231140 | OutputModule.cmd_output_sysid | train | def cmd_output_sysid(self, args):
'''add new output for a specific MAVLink sysID'''
sysid = int(args[0])
device = args[1]
print("Adding output %s for sysid %u" % (device, sysid))
try:
conn = mavutil.mavlink_connection(device, input=False, source_system=self.settings.s... | python | {
"resource": ""
} |
q231141 | OutputModule.cmd_output_remove | train | def cmd_output_remove(self, args):
'''remove an output'''
device = args[0]
for i in range(len(self.mpstate.mav_outputs)):
conn = self.mpstate.mav_outputs[i]
if str(i) == device or conn.address == device:
print("Removing output %s" % conn.address)
... | python | {
"resource": ""
} |
q231142 | MPSlipMap.set_center | train | def set_center(self, lat, lon):
'''set center of view'''
self.object_queue.put(SlipCenter((lat,lon))) | python | {
"resource": ""
} |
q231143 | MPSlipMap.get_event | train | def get_event(self):
'''return next event or None'''
if self.event_queue.qsize() == 0:
return None
evt = self.event_queue.get()
while isinstance(evt, win_layout.WinLayout):
win_layout.set_layout(evt, self.set_layout)
if self.event_queue.qsize() == 0:
... | python | {
"resource": ""
} |
q231144 | LayoutModule.cmd_layout | train | def cmd_layout(self, args):
'''handle layout command'''
from MAVProxy.modules.lib import win_layout
if len(args) < 1:
print("usage: layout <save|load>")
return
if args[0] == "load":
win_layout.load_layout(self.mpstate.settings.vehicle_name)
eli... | python | {
"resource": ""
} |
q231145 | download_files | train | def download_files(files):
'''download an array of files'''
for (url, file) in files:
print("Downloading %s as %s" % (url, file))
data = download_url(url)
if data is None:
continue
try:
open(file, mode='wb').write(data)
except Exception as e:
... | python | {
"resource": ""
} |
q231146 | null_term | train | def null_term(str):
'''null terminate a string for py3'''
if sys.version_info.major < 3:
return str
if isinstance(str, bytes):
str = str.decode("utf-8")
idx = str.find("\0")
if idx != -1:
str = str[:idx]
return str | python | {
"resource": ""
} |
q231147 | decode_devid | train | def decode_devid(devid, pname):
'''decode one device ID. Used for 'devid' command in mavproxy and MAVExplorer'''
devid = int(devid)
if devid == 0:
return
bus_type=devid & 0x07
bus=(devid>>3) & 0x1F
address=(devid>>8)&0xFF
devtype=(devid>>16)
bustypes = {
1: "I2C",
... | python | {
"resource": ""
} |
q231148 | _LDAPUser._authenticate_user_dn | train | def _authenticate_user_dn(self, password):
"""
Binds to the LDAP server with the user's DN and password. Raises
AuthenticationFailed on failure.
"""
if self.dn is None:
raise self.AuthenticationFailed("failed to map the username to a DN.")
try:
st... | python | {
"resource": ""
} |
q231149 | _LDAPUser._load_user_dn | train | def _load_user_dn(self):
"""
Populates self._user_dn with the distinguished name of our user.
This will either construct the DN from a template in
AUTH_LDAP_USER_DN_TEMPLATE or connect to the server and search for it.
If we have to search, we'll cache the DN.
"""
... | python | {
"resource": ""
} |
q231150 | _LDAPUser._search_for_user_dn | train | def _search_for_user_dn(self):
"""
Searches the directory for a user matching AUTH_LDAP_USER_SEARCH.
Populates self._user_dn and self._user_attrs.
"""
search = self.settings.USER_SEARCH
if search is None:
raise ImproperlyConfigured(
"AUTH_LDAP_... | python | {
"resource": ""
} |
q231151 | _LDAPUser._normalize_group_dns | train | def _normalize_group_dns(self, group_dns):
"""
Converts one or more group DNs to an LDAPGroupQuery.
group_dns may be a string, a non-empty list or tuple of strings, or an
LDAPGroupQuery. The result will be an LDAPGroupQuery. A list or tuple
will be joined with the | operator.
... | python | {
"resource": ""
} |
q231152 | _LDAPUser._normalize_mirror_settings | train | def _normalize_mirror_settings(self):
"""
Validates the group mirroring settings and converts them as necessary.
"""
def malformed_mirror_groups_except():
return ImproperlyConfigured(
"{} must be a collection of group names".format(
self.s... | python | {
"resource": ""
} |
q231153 | _LDAPUser._get_groups | train | def _get_groups(self):
"""
Returns an _LDAPUserGroups object, which can determine group
membership.
"""
if self._groups is None:
self._groups = _LDAPUserGroups(self)
return self._groups | python | {
"resource": ""
} |
q231154 | _LDAPUser._bind | train | def _bind(self):
"""
Binds to the LDAP server with AUTH_LDAP_BIND_DN and
AUTH_LDAP_BIND_PASSWORD.
"""
self._bind_as(self.settings.BIND_DN, self.settings.BIND_PASSWORD, sticky=True) | python | {
"resource": ""
} |
q231155 | _LDAPUser._bind_as | train | def _bind_as(self, bind_dn, bind_password, sticky=False):
"""
Binds to the LDAP server with the given credentials. This does not trap
exceptions.
If sticky is True, then we will consider the connection to be bound for
the life of this object. If False, then the caller only wishe... | python | {
"resource": ""
} |
q231156 | _LDAPUserGroups._init_group_settings | train | def _init_group_settings(self):
"""
Loads the settings we need to deal with groups.
Raises ImproperlyConfigured if anything's not right.
"""
self._group_type = self.settings.GROUP_TYPE
if self._group_type is None:
raise ImproperlyConfigured(
... | python | {
"resource": ""
} |
q231157 | _LDAPUserGroups.get_group_names | train | def get_group_names(self):
"""
Returns the set of Django group names that this user belongs to by
virtue of LDAP group memberships.
"""
if self._group_names is None:
self._load_cached_attr("_group_names")
if self._group_names is None:
group_infos ... | python | {
"resource": ""
} |
q231158 | _LDAPUserGroups.is_member_of | train | def is_member_of(self, group_dn):
"""
Returns true if our user is a member of the given group.
"""
is_member = None
# Normalize the DN
group_dn = group_dn.lower()
# If we have self._group_dns, we'll use it. Otherwise, we'll try to
# avoid the cost of loa... | python | {
"resource": ""
} |
q231159 | _LDAPConfig.get_ldap | train | def get_ldap(cls, global_options=None):
"""
Returns the configured ldap module.
"""
# Apply global LDAP options once
if not cls._ldap_configured and global_options is not None:
for opt, value in global_options.items():
ldap.set_option(opt, value)
... | python | {
"resource": ""
} |
q231160 | LDAPSearch.search_with_additional_terms | train | def search_with_additional_terms(self, term_dict, escape=True):
"""
Returns a new search object with additional search terms and-ed to the
filter string. term_dict maps attribute names to assertion values. If
you don't want the values escaped, pass escape=False.
"""
term_... | python | {
"resource": ""
} |
q231161 | PosixGroupType.user_groups | train | def user_groups(self, ldap_user, group_search):
"""
Searches for any group that is either the user's primary or contains the
user as a member.
"""
groups = []
try:
user_uid = ldap_user.attrs["uid"][0]
if "gidNumber" in ldap_user.attrs:
... | python | {
"resource": ""
} |
q231162 | PosixGroupType.is_member | train | def is_member(self, ldap_user, group_dn):
"""
Returns True if the group is the user's primary group or if the user is
listed in the group's memberUid attribute.
"""
try:
user_uid = ldap_user.attrs["uid"][0]
try:
is_member = ldap_user.conne... | python | {
"resource": ""
} |
q231163 | NestedMemberDNGroupType.user_groups | train | def user_groups(self, ldap_user, group_search):
"""
This searches for all of a user's groups from the bottom up. In other
words, it returns the groups that the user belongs to, the groups that
those groups belong to, etc. Circular references will be detected and
pruned.
"... | python | {
"resource": ""
} |
q231164 | LDAPGroupQuery.aggregator | train | def aggregator(self):
"""
Returns a function for aggregating a sequence of sub-results.
"""
if self.connector == self.AND:
aggregator = all
elif self.connector == self.OR:
aggregator = any
else:
raise ValueError(self.connector)
... | python | {
"resource": ""
} |
q231165 | LDAPGroupQuery._resolve_children | train | def _resolve_children(self, ldap_user, groups):
"""
Generates the query result for each child.
"""
for child in self.children:
if isinstance(child, LDAPGroupQuery):
yield child.resolve(ldap_user, groups)
else:
yield groups.is_member... | python | {
"resource": ""
} |
q231166 | gather_positions | train | def gather_positions(tree):
"""Makes a list of positions and position commands from the tree"""
pos = {'data-x': 'r0',
'data-y': 'r0',
'data-z': 'r0',
'data-rotate-x': 'r0',
'data-rotate-y': 'r0',
'data-rotate-z': 'r0',
'data-scale': 'r0',
... | python | {
"resource": ""
} |
q231167 | calculate_positions | train | def calculate_positions(positions):
"""Calculates position information"""
current_position = {'data-x': 0,
'data-y': 0,
'data-z': 0,
'data-rotate-x': 0,
'data-rotate-y': 0,
'data-rotate-z': 0,... | python | {
"resource": ""
} |
q231168 | update_positions | train | def update_positions(tree, positions):
"""Updates the tree with new positions"""
for step, pos in zip(tree.findall('step'), positions):
for key in sorted(pos):
value = pos.get(key)
if key.endswith("-rel"):
abs_key = key[:key.index("-rel")]
if valu... | python | {
"resource": ""
} |
q231169 | position_slides | train | def position_slides(tree):
"""Position the slides in the tree"""
positions = gather_positions(tree)
positions = calculate_positions(positions)
update_positions(tree, positions) | python | {
"resource": ""
} |
q231170 | copy_node | train | def copy_node(node):
"""Makes a copy of a node with the same attributes and text, but no children."""
element = node.makeelement(node.tag)
element.text = node.text
element.tail = node.tail
for key, value in node.items():
element.set(key, value)
return element | python | {
"resource": ""
} |
q231171 | Template.copy_resource | train | def copy_resource(self, resource, targetdir):
"""Copies a resource file and returns the source path for monitoring"""
final_path = resource.final_path()
if final_path[0] == '/' or (':' in final_path) or ('?' in final_path):
# Absolute path or URI: Do nothing
return
... | python | {
"resource": ""
} |
q231172 | generate | train | def generate(args):
"""Generates the presentation and returns a list of files used"""
source_files = {args.presentation}
# Parse the template info
template_info = Template(args.template)
if args.css:
presentation_dir = os.path.split(args.presentation)[0]
target_path = os.path.relpa... | python | {
"resource": ""
} |
q231173 | ModbusClient.port | train | def port(self, port=None):
"""Get or set TCP port
:param port: TCP port number or None for get value
:type port: int or None
:returns: TCP port or None if set fail
:rtype: int or None
"""
if (port is None) or (port == self.__port):
return self.__port
... | python | {
"resource": ""
} |
q231174 | ModbusClient.unit_id | train | def unit_id(self, unit_id=None):
"""Get or set unit ID field
:param unit_id: unit ID (0 to 255) or None for get value
:type unit_id: int or None
:returns: unit ID or None if set fail
:rtype: int or None
"""
if unit_id is None:
return self.__unit_id
... | python | {
"resource": ""
} |
q231175 | ModbusClient.timeout | train | def timeout(self, timeout=None):
"""Get or set timeout field
:param timeout: socket timeout in seconds or None for get value
:type timeout: float or None
:returns: timeout or None if set fail
:rtype: float or None
"""
if timeout is None:
return self._... | python | {
"resource": ""
} |
q231176 | ModbusClient.debug | train | def debug(self, state=None):
"""Get or set debug mode
:param state: debug state or None for get value
:type state: bool or None
:returns: debug state or None if set fail
:rtype: bool or None
"""
if state is None:
return self.__debug
self.__deb... | python | {
"resource": ""
} |
q231177 | ModbusClient.auto_open | train | def auto_open(self, state=None):
"""Get or set automatic TCP connect mode
:param state: auto_open state or None for get value
:type state: bool or None
:returns: auto_open state or None if set fail
:rtype: bool or None
"""
if state is None:
return sel... | python | {
"resource": ""
} |
q231178 | ModbusClient._can_read | train | def _can_read(self):
"""Wait data available for socket read
:returns: True if data available or None if timeout or socket error
:rtype: bool or None
"""
if self.__sock is None:
return None
if select.select([self.__sock], [], [], self.__timeout)[0]:
... | python | {
"resource": ""
} |
q231179 | ModbusClient._send | train | def _send(self, data):
"""Send data over current socket
:param data: registers value to write
:type data: str (Python2) or class bytes (Python3)
:returns: True if send ok or None if error
:rtype: bool or None
"""
# check link
if self.__sock is None:
... | python | {
"resource": ""
} |
q231180 | ModbusClient._recv | train | def _recv(self, max_size):
"""Receive data over current socket
:param max_size: number of bytes to receive
:type max_size: int
:returns: receive data or None if error
:rtype: str (Python2) or class bytes (Python3) or None
"""
# wait for read
if not self._... | python | {
"resource": ""
} |
q231181 | ModbusClient._send_mbus | train | def _send_mbus(self, frame):
"""Send modbus frame
:param frame: modbus frame to send (with MBAP for TCP/CRC for RTU)
:type frame: str (Python2) or class bytes (Python3)
:returns: number of bytes send or None if error
:rtype: int or None
"""
# for auto_open mode, ... | python | {
"resource": ""
} |
q231182 | ModbusClient._recv_mbus | train | def _recv_mbus(self):
"""Receive a modbus frame
:returns: modbus frame body or None if error
:rtype: str (Python2) or class bytes (Python3) or None
"""
# receive
# modbus TCP receive
if self.__mode == const.MODBUS_TCP:
# 7 bytes header (mbap)
... | python | {
"resource": ""
} |
q231183 | _wc_hard_wrap | train | def _wc_hard_wrap(line, length):
"""
Wrap text to length characters, breaking when target length is reached,
taking into account character width.
Used to wrap lines which cannot be wrapped on whitespace.
"""
chars = []
chars_len = 0
for char in line:
char_len = wcwidth(char)
... | python | {
"resource": ""
} |
q231184 | wc_wrap | train | def wc_wrap(text, length):
"""
Wrap text to given length, breaking on whitespace and taking into account
character width.
Meant for use on a single line or paragraph. Will destroy spacing between
words and paragraphs and any indentation.
"""
line_words = []
line_len = 0
words = re.... | python | {
"resource": ""
} |
q231185 | trunc | train | def trunc(text, length):
"""
Truncates text to given length, taking into account wide characters.
If truncated, the last char is replaced by an elipsis.
"""
if length < 1:
raise ValueError("length should be 1 or larger")
# Remove whitespace first so no unneccesary truncation is done.
... | python | {
"resource": ""
} |
q231186 | pad | train | def pad(text, length):
"""Pads text to given length, taking into account wide characters."""
text_length = wcswidth(text)
if text_length < length:
return text + ' ' * (length - text_length)
return text | python | {
"resource": ""
} |
q231187 | fit_text | train | def fit_text(text, length):
"""Makes text fit the given length by padding or truncating it."""
text_length = wcswidth(text)
if text_length > length:
return trunc(text, length)
if text_length < length:
return pad(text, length)
return text | python | {
"resource": ""
} |
q231188 | _get_error_message | train | def _get_error_message(response):
"""Attempt to extract an error message from response body"""
try:
data = response.json()
if "error_description" in data:
return data['error_description']
if "error" in data:
return data['error']
except Exception:
pass
... | python | {
"resource": ""
} |
q231189 | _get_next_path | train | def _get_next_path(headers):
"""Given timeline response headers, returns the path to the next batch"""
links = headers.get('Link', '')
matches = re.match('<([^>]+)>; rel="next"', links)
if matches:
parsed = urlparse(matches.group(1))
return "?".join([parsed.path, parsed.query]) | python | {
"resource": ""
} |
q231190 | TimelineApp.select_previous | train | def select_previous(self):
"""Move to the previous status in the timeline."""
self.footer.clear_message()
if self.selected == 0:
self.footer.draw_message("Cannot move beyond first toot.", Color.GREEN)
return
old_index = self.selected
new_index = self.sel... | python | {
"resource": ""
} |
q231191 | TimelineApp.select_next | train | def select_next(self):
"""Move to the next status in the timeline."""
self.footer.clear_message()
old_index = self.selected
new_index = self.selected + 1
# Load more statuses if no more are available
if self.selected + 1 >= len(self.statuses):
self.fetch_nex... | python | {
"resource": ""
} |
q231192 | TimelineApp.full_redraw | train | def full_redraw(self):
"""Perform a full redraw of the UI."""
self.left.draw_statuses(self.statuses, self.selected)
self.right.draw(self.get_selected_status())
self.header.draw(self.user)
self.draw_footer_status() | python | {
"resource": ""
} |
q231193 | size_as_drawn | train | def size_as_drawn(lines, screen_width):
"""Get the bottom-right corner of some text as would be drawn by draw_lines"""
y = 0
x = 0
for line in lines:
wrapped = list(wc_wrap(line, screen_width))
if len(wrapped) > 0:
for wrapped_line in wrapped:
x = len(wrapped_... | python | {
"resource": ""
} |
q231194 | _find_account | train | def _find_account(app, user, account_name):
"""For a given account name, returns the Account object.
Raises an exception if not found.
"""
if not account_name:
raise ConsoleError("Empty account name given")
accounts = api.search_accounts(app, user, account_name)
if account_name[0] == ... | python | {
"resource": ""
} |
q231195 | add_username | train | def add_username(user, apps):
"""When using broser login, username was not stored so look it up"""
if not user:
return None
apps = [a for a in apps if a.instance == user.instance]
if not apps:
return None
from toot.api import verify_credentials
creds = verify_credentials(apps.... | python | {
"resource": ""
} |
q231196 | get_text | train | def get_text(html):
"""Converts html to text, strips all tags."""
# Ignore warnings made by BeautifulSoup, if passed something that looks like
# a file (e.g. a dot which matches current dict), it will warn that the file
# should be opened instead of passing a filename.
with warnings.catch_warnings(... | python | {
"resource": ""
} |
q231197 | parse_html | train | def parse_html(html):
"""Attempt to convert html to plain text while keeping line breaks.
Returns a list of paragraphs, each being a list of lines.
"""
paragraphs = re.split("</?p[^>]*>", html)
# Convert <br>s to line breaks and remove empty paragraphs
paragraphs = [re.split("<br */?>", p) for ... | python | {
"resource": ""
} |
q231198 | format_content | train | def format_content(content):
"""Given a Status contents in HTML, converts it into lines of plain text.
Returns a generator yielding lines of content.
"""
paragraphs = parse_html(content)
first = True
for paragraph in paragraphs:
if not first:
yield ""
for line in... | python | {
"resource": ""
} |
q231199 | multiline_input | train | def multiline_input():
"""Lets user input multiple lines of text, terminated by EOF."""
lines = []
while True:
try:
lines.append(input())
except EOFError:
break
return "\n".join(lines).strip() | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.