code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
self.event_queue.append((event, args))
self.process_events() | def fire_event(self, event, *args, **kwargs) | Fires a event. | 5.473311 | 5.418861 | 1.010048 |
for event, args in iter_except(self.event_queue.popleft, IndexError):
for callback in self.event_callbacks[event]:
callback(*args) | def process_events(self) | Processes any events in the queue. | 5.972476 | 5.388619 | 1.10835 |
self.running = True
while self.running:
for fd, event in self.epoll.poll(self.epoll_timeout):
callback = self.callbacks.get(fd)
if callback:
callback() | def run(self) | Starts the loop. | 3.565156 | 3.107794 | 1.147166 |
self.running = False
self.callbacks = {}
self.epoll = epoll()
self.event_queue = deque()
self.event_callbacks = defaultdict(set) | def stop(self) | Stops the loop. | 6.603007 | 5.856209 | 1.127523 |
monitor = Monitor.from_netlink(context)
monitor.filter_by("hidraw")
monitor.start()
self._scanning_log_message()
for device in iter(monitor.poll, None):
if device.action == "add":
# Sometimes udev rules has not been applied at this point,
... | def _get_future_devices(self, context) | Return a generator yielding new devices. | 9.716131 | 8.969907 | 1.083192 |
context = Context()
existing_devices = context.list_devices(subsystem="hidraw")
future_devices = self._get_future_devices(context)
for hidraw_device in itertools.chain(existing_devices, future_devices):
hid_device = hidraw_device.parent
if hid_device.su... | def devices(self) | Wait for new DS4 devices to appear. | 3.740136 | 3.593376 | 1.040842 |
self._control(small_rumble=small, big_rumble=big) | def rumble(self, small=0, big=0) | Sets the intensity of the rumble motors. Valid range is 0-255. | 8.317454 | 8.724868 | 0.953304 |
self._led = (red, green, blue)
self._control() | def set_led(self, red=0, green=0, blue=0) | Sets the LED color. Values are RGB between 0-255. | 7.749553 | 7.15756 | 1.082709 |
if not self._led_flashing:
self._led_flash = (on, off)
self._led_flashing = True
self._control() | def start_led_flash(self, on, off) | Starts flashing the LED. | 4.092704 | 4.071171 | 1.005289 |
if self._led_flashing:
self._led_flash = (0, 0)
self._led_flashing = False
# Call twice, once to stop flashing...
self._control()
# ...and once more to make sure the LED is on.
self._control() | def stop_led_flash(self) | Stops flashing the LED. | 6.231398 | 5.679289 | 1.097214 |
dpad = buf[5] % 16
return DS4Report(
# Left analog stick
buf[1], buf[2],
# Right analog stick
buf[3], buf[4],
# L2 and R2 analog
buf[8], buf[9],
# DPad up, down, left, right
(dpad in (0, 1, 7)), ... | def parse_report(self, buf) | Parse a buffer containing a HID report. | 2.160737 | 2.141595 | 1.008938 |
controller.logger.info("Executing: {0} {1}", cmd, " ".join(args))
try:
subprocess.check_call([cmd] + list(args))
except (OSError, subprocess.CalledProcessError) as err:
controller.logger.error("Failed to execute process: {0}", err) | def exec_(controller, cmd, *args) | Executes a subprocess in the foreground, blocking until returned. | 2.638005 | 2.508104 | 1.051792 |
controller.logger.info("Executing in the background: {0} {1}",
cmd, " ".join(args))
try:
subprocess.Popen([cmd] + list(args),
stdout=open(os.devnull, "wb"),
stderr=open(os.devnull, "wb"))
except OSError as err:
... | def exec_background(controller, cmd, *args) | Executes a subprocess in the background. | 2.534198 | 2.338984 | 1.083461 |
if mapping not in _mappings:
raise DeviceError("Unknown device mapping: {0}".format(mapping))
try:
mapping = _mappings[mapping]
device = UInputDevice(mapping)
except UInputError as err:
raise DeviceError(err)
return device | def create_uinput_device(mapping) | Creates a uinput device. | 3.199826 | 3.109447 | 1.029066 |
axes, buttons, mouse, mouse_options = {}, {}, {}, {}
description = "ds4drv custom mapping ({0})".format(name)
for key, attr in mapping.items():
key = key.upper()
if key.startswith("BTN_") or key.startswith("KEY_"):
buttons[key] = attr
elif key.startswith("ABS_"):
... | def parse_uinput_mapping(name, mapping) | Parses a dict of mapping options. | 3.290608 | 3.274622 | 1.004882 |
for i in range(100):
dev = "/dev/input/js{0}".format(i)
if not os.path.exists(dev):
return dev | def next_joystick_device() | Finds the next available js device name. | 3.041479 | 2.421774 | 1.255889 |
events = {ecodes.EV_ABS: [], ecodes.EV_KEY: [],
ecodes.EV_REL: []}
# Joystick device
if layout.axes or layout.buttons or layout.hats:
self.joystick_dev = next_joystick_device()
for name in layout.axes:
params = layout.axes_options.get(... | def create_device(self, layout) | Creates a uinput device using the specified layout. | 2.527504 | 2.48947 | 1.015278 |
last_value = self._write_cache.get(code)
if last_value != value:
self.device.write(etype, code, value)
self._write_cache[code] = value | def write_event(self, etype, code, value) | Writes a event to the device, if it has changed. | 3.390403 | 2.984029 | 1.136183 |
for name, attr in self.layout.axes.items():
value = getattr(report, attr)
self.write_event(ecodes.EV_ABS, name, value)
for name, attr in self.layout.buttons.items():
attr, modifier = attr
if attr in self.ignored_buttons:
value = ... | def emit(self, report) | Writes axes, buttons and hats with values from the report to
the device. | 2.930504 | 2.689829 | 1.089476 |
for name in self.layout.axes:
params = self.layout.axes_options.get(name, DEFAULT_AXIS_OPTIONS)
self.write_event(ecodes.EV_ABS, name, int(sum(params[1:3]) / 2))
for name in self.layout.buttons:
self.write_event(ecodes.EV_KEY, name, False)
for name i... | def emit_reset(self) | Resets the device to a blank state. | 3.39279 | 3.262386 | 1.039972 |
for name, attr in self.layout.mouse.items():
# If the attr is a tuple like (left_analog_y, "-")
# then set the attr to just be the first item
attr, modifier = attr
if attr.startswith("trackpad_touch"):
active_attr = attr[:16] + "active"
... | def emit_mouse(self, report) | Calculates relative mouse values from a report and writes them. | 3.694668 | 3.68553 | 1.002479 |
super(GMLLogger, self).start_output()
if self.has_part("intro"):
self.write_intro()
self.writeln()
self.writeln(u"graph [")
self.writeln(u" directed 1")
self.flush() | def start_output (self) | Write start of checking info as gml comment. | 6.597315 | 5.024301 | 1.313081 |
self.writeln(s=u'comment "%s"' % s, **args) | def comment (self, s, **args) | Write GML comment. | 13.661053 | 11.775554 | 1.16012 |
node = self.get_node(url_data)
if node:
self.writeln(u" node [")
self.writeln(u" id %d" % node["id"])
self.writeln(u' label "%s"' % node["label"])
if self.has_part("realurl"):
self.writeln(u' url "%s"' % node["url"]... | def log_url (self, url_data) | Write one node. | 2.495979 | 2.406212 | 1.037306 |
self.writeln(u" edge [")
self.writeln(u' label "%s"' % node["edge"])
self.writeln(u" source %d" % self.nodes[node["parent_url"]]["id"])
self.writeln(u" target %d" % node["id"])
if self.has_part("result"):
self.writeln(u" valid %d" % node["valid... | def write_edge (self, node) | Write one edge. | 3.741121 | 3.598806 | 1.039545 |
parsed = [mail for name, mail in AddressList(addr).addresslist if mail]
if parsed:
addresses = parsed
elif addr:
# we could not parse any mail addresses, so try with the raw string
addresses = [addr]
else:
addresses = []
return addresses | def getaddresses (addr) | Return list of email addresses from given field value. | 7.973633 | 6.717865 | 1.18693 |
super(MailtoUrl, self).build_url()
self.addresses = set()
self.subject = None
self.parse_addresses()
if self.addresses:
for addr in sorted(self.addresses):
self.check_email_syntax(addr)
if not self.valid:
br... | def build_url (self) | Call super.build_url(), extract list of mail addresses from URL,
and check their syntax. | 5.515849 | 4.518134 | 1.220825 |
# cut off leading mailto: and unquote
url = urllib.unquote(self.base_url[7:])
# search for cc, bcc, to and store in headers
mode = 0 # 0=default, 1=quote, 2=esc
quote = None
i = 0
for i, c in enumerate(url):
if mode == 0:
if c ... | def parse_addresses (self) | Parse all mail addresses out of the URL target. Also parses
optional CGI headers like "?to=foo@example.org".
Stores parsed addresses in the self.addresses set. | 3.793486 | 3.54749 | 1.069344 |
for mail in sorted(self.addresses):
self.check_smtp_domain(mail)
if not self.valid:
break | def check_connection (self) | Verify a list of email addresses. If one address fails,
the whole list will fail.
For each mail address the MX DNS records are found.
If no MX records are found, print a warning and try
to look for A DNS records. If no A records are found either
print an error. | 12.882866 | 8.711618 | 1.478814 |
from dns.exception import DNSException
log.debug(LOG_CHECK, "checking mail address %r", mail)
mail = strformat.ascii_safe(mail)
username, domain = mail.rsplit('@', 1)
log.debug(LOG_CHECK, "looking up MX mailhost %r", domain)
try:
answers = resolver.qu... | def check_smtp_domain (self, mail) | Check a single mail address. | 3.706748 | 3.647082 | 1.01636 |
emails = u",".join(sorted(self.addresses))
self.cache_url = u"%s:%s" % (self.scheme, emails) | def set_cache_url(self) | The cache url is a comma separated list of emails. | 7.399207 | 5.592144 | 1.323143 |
expanded = os.path.expanduser(os.path.expandvars(path))
return os.path.normcase(os.path.normpath(expanded)) | def normpath (path) | Norm given system path with all available norm or expand functions
in os.path. | 2.414844 | 2.754178 | 0.876793 |
module_infos = []
for (mod, name, version_attr) in Modules:
if not fileutil.has_module(mod):
continue
if hasattr(mod, version_attr):
attr = getattr(mod, version_attr)
version = attr() if callable(attr) else attr
module_infos.append("%s %s" % (... | def get_modules_info() | Return unicode string with detected module info. | 4.571223 | 4.119272 | 1.109716 |
paths = [get_share_dir()]
if devel_dir is not None:
# when developing
paths.insert(0, devel_dir)
for path in paths:
fullpath = os.path.join(path, filename)
if os.path.isfile(fullpath):
return fullpath
# not found
msg = "%s not found in %s; check your ... | def get_share_file (filename, devel_dir=None) | Return a filename in the share directory.
@param devel_dir: directory to search when developing
@ptype devel_dir: string
@param filename: filename to search for
@ptype filename: string
@return: the found filename or None
@rtype: string
@raises: ValueError if not found | 2.773544 | 2.633293 | 1.053261 |
if os.name == 'posix':
filename = "/etc/ssl/certs/ca-certificates.crt"
if os.path.isfile(filename):
return filename
msg = "no system certificate file found"
raise ValueError(msg) | def get_system_cert_file() | Try to find a system-wide SSL certificate file.
@return: the filename to the cert file
@raises: ValueError when no system cert file could be found | 3.138557 | 3.053055 | 1.028005 |
import certifi
filename = certifi.where()
if os.path.isfile(filename):
return filename
msg = "%s not found; check your certifi installation" % filename
raise ValueError(msg) | def get_certifi_file() | Get the SSL certifications installed by the certifi package.
@return: the filename to the cert file
@rtype: string
@raises: ImportError when certifi is not installed or ValueError when
the file is not found | 3.812977 | 3.919824 | 0.972742 |
folders = []
defaultfolder = normpath("~/.linkchecker/plugins")
if not os.path.exists(defaultfolder) and not Portable:
try:
make_userdir(defaultfolder)
except Exception as errmsg:
msg = _("could not create plugin directory %(dirname)r: %(errmsg)r")
ar... | def get_plugin_folders() | Get linkchecker plugin folders. Default is ~/.linkchecker/plugins/. | 5.233065 | 4.50322 | 1.162072 |
userdir = os.path.dirname(child)
if not os.path.isdir(userdir):
if os.name == 'nt':
# Windows forbids filenames with leading dot unless
# a trailing dot is added.
userdir += "."
os.mkdir(userdir, 0700) | def make_userdir(child) | Create a child directory. | 4.346975 | 4.402244 | 0.987445 |
# initial config (with all options explained)
initialconf = normpath(os.path.join(get_share_dir(), "linkcheckerrc"))
# per user config settings
userconf = normpath("~/.linkchecker/linkcheckerrc")
if os.path.isfile(initialconf) and not os.path.exists(userconf) and \
not Portable:
... | def get_user_config() | Get the user configuration filename.
If the user configuration file does not exist, copy it from the initial
configuration file, but only if this is not a portable installation.
Returns path to user config file (which might not exist due to copy
failures or on portable systems).
@return configuratio... | 5.555781 | 4.931456 | 1.126601 |
try:
import gconf
except ImportError:
return None
try:
client = gconf.client_get_default()
if client.get_bool("/system/http_proxy/use_http_proxy"):
host = client.get_string("/system/http_proxy/host")
port = client.get_int("/system/http_proxy/port"... | def get_gconf_http_proxy () | Return host:port for GConf HTTP proxy if found, else None. | 2.690792 | 2.665414 | 1.009521 |
config_dir = get_kde_config_dir()
if not config_dir:
# could not find any KDE configuration directory
return
try:
data = read_kioslaverc(config_dir)
return data.get("http_proxy")
except Exception as msg:
log.debug(LOG_CHECK, "error getting HTTP proxy from KDE... | def get_kde_http_proxy () | Return host:port for KDE HTTP proxy if found, else None. | 6.674493 | 6.481009 | 1.029854 |
if os.environ.get("KDEHOME"):
kde_home = os.path.abspath(os.environ["KDEHOME"])
else:
home = os.environ.get("HOME")
if not home:
# $HOME is not set
return
kde3_home = os.path.join(home, ".kde")
kde4_home = os.path.join(home, ".kde4")
i... | def get_kde_home_dir () | Return KDE home directory or None if not found. | 1.941027 | 1.912433 | 1.014952 |
data = {}
filename = os.path.join(kde_config_dir, "kioslaverc")
with open(filename) as fd:
# First read all lines into dictionary since they can occur
# in any order.
for line in fd:
line = line.rstrip()
if line.startswith('['):
in_proxy_... | def read_kioslaverc (kde_config_dir) | Read kioslaverc into data dictionary. | 3.949237 | 3.831905 | 1.03062 |
if key == "ProxyType":
mode = None
int_value = int(value)
if int_value == 1:
mode = "manual"
elif int_value == 2:
# PAC URL
mode = "pac"
elif int_value == 3:
# WPAD.
mode = "wpad"
elif int_value == 4:
... | def add_kde_setting (key, value, data) | Add a KDE proxy setting value to data dictionary. | 3.500892 | 3.414041 | 1.025439 |
value = data[key]
env_value = os.environ.get(value)
if env_value:
if splithosts:
data[key] = split_hosts(env_value)
else:
data[key] = env_value
else:
del data[key] | def resolve_indirect (data, key, splithosts=False) | Replace name of environment variable with its value. | 2.627466 | 2.203272 | 1.192529 |
if "mode" not in data:
return
if data["mode"] == "indirect":
for key in ("http_proxy", "https_proxy", "ftp_proxy"):
if key in data:
resolve_indirect(data, key)
if "ignore_hosts" in data:
resolve_indirect(data, "ignore_hosts", splithosts=True)
... | def resolve_kde_settings (data) | Write final proxy configuration values in data dictionary. | 3.337101 | 3.092825 | 1.078982 |
args = self[loggername]
args.update(kwargs)
return self.loggers[loggername](**args) | def logger_new (self, loggername, **kwargs) | Instantiate new logger and return it. | 5.625944 | 4.459073 | 1.261685 |
self.loggers[loggerclass.LoggerName] = loggerclass
self[loggerclass.LoggerName] = {} | def logger_add (self, loggerclass) | Add a new logger type to the known loggers. | 4.749342 | 3.909502 | 1.21482 |
if files is None:
cfiles = []
else:
cfiles = files[:]
if not cfiles:
userconf = get_user_config()
if os.path.isfile(userconf):
cfiles.append(userconf)
# filter invalid files
filtered_cfiles = []
for ... | def read (self, files=None) | Read settings from given config files.
@raises: LinkCheckerError on syntax errors in the config file(s) | 3.105494 | 3.014451 | 1.030202 |
if not user or not pattern:
log.warn(LOG_CHECK,
_("missing user or URL pattern in authentication data."))
return
entry = dict(
user=user,
password=password,
pattern=re.compile(pattern),
)
self["authenticatio... | def add_auth (self, user=None, password=None, pattern=None) | Add given authentication data. | 7.377691 | 6.680212 | 1.10441 |
for auth in self["authentication"]:
if auth['pattern'].match(url):
return (auth['user'], auth['password'])
return (None, None) | def get_user_password (self, url) | Get tuple (user, password) from configured authentication
that matches the given URL.
Both user and password can be None if not specified, or no
authentication matches the given URL. | 5.561617 | 3.998357 | 1.390976 |
"Make sure the configuration is consistent."
if self['logger'] is None:
self.sanitize_logger()
if self['loginurl']:
self.sanitize_loginurl()
self.sanitize_proxies()
self.sanitize_plugins()
self.sanitize_ssl()
# set default socket timeout
... | def sanitize (self) | Make sure the configuration is consistent. | 7.085931 | 5.932701 | 1.194385 |
if not self['output']:
log.warn(LOG_CHECK, _("activating text logger output."))
self['output'] = 'text'
self['logger'] = self.logger_new(self['output']) | def sanitize_logger (self) | Make logger configuration consistent. | 14.969351 | 13.045285 | 1.147491 |
url = self["loginurl"]
disable = False
if not self["loginpasswordfield"]:
log.warn(LOG_CHECK,
_("no CGI password fieldname given for login URL."))
disable = True
if not self["loginuserfield"]:
log.warn(LOG_CHECK,
_("no ... | def sanitize_loginurl (self) | Make login configuration consistent. | 3.182448 | 3.072095 | 1.035921 |
if os.name != 'posix':
return
if "http" not in self["proxy"]:
http_proxy = get_gconf_http_proxy() or get_kde_http_proxy()
if http_proxy:
self["proxy"]["http"] = http_proxy
if "ftp" not in self["proxy"]:
ftp_proxy = get_gcon... | def sanitize_proxies (self) | Try to read additional proxy settings which urllib does not
support. | 2.598372 | 2.437701 | 1.065911 |
if self["sslverify"] is True:
try:
self["sslverify"] = get_system_cert_file()
except ValueError:
try:
self["sslverify"] = get_certifi_file()
except (ValueError, ImportError):
try:
... | def sanitize_ssl(self) | Use local installed certificate file if available.
Tries to get system, then certifi, then the own
installed certificate file. | 4.515902 | 3.349833 | 1.348098 |
cmd = None
count = len(self.command_list)
if count > 0:
cmd = self.command_list.pop(0)
## If that was the last line, turn off lines_pending
if count == 1:
self.cmd_ready = False
return cmd | def get_command(self) | Get a line of text that was received from the DE. The class's
cmd_ready attribute will be true if lines are available. | 5.787488 | 3.992778 | 1.449489 |
if text:
self.send_buffer += text.replace('\n', '\r\n')
self.send_pending = True | def send(self, text) | Send raw text to the distant end. | 4.941742 | 4.713865 | 1.048342 |
lines = word_wrap(text, self.columns)
for line in lines:
self.send_cc(line + '\n') | def send_wrapped(self, text) | Send text padded and wrapped to the user's screen width. | 6.025608 | 5.916009 | 1.018526 |
self._iac_will(ECHO)
self._note_reply_pending(ECHO, True)
self.telnet_echo = True | def request_will_echo(self) | Tell the DE that we would like to echo their text. See RFC 857. | 24.894564 | 20.675215 | 1.204078 |
self._iac_wont(ECHO)
self._note_reply_pending(ECHO, True)
self.telnet_echo = False | def request_wont_echo(self) | Tell the DE that we would like to stop echoing their text.
See RFC 857. | 24.470085 | 20.028545 | 1.22176 |
if len(self.send_buffer):
try:
sent = self.sock.send(self.send_buffer)
except socket.error, err:
print("!! SEND error '%d:%s' from %s" % (err[0], err[1],
self.addrport()))
self.active = False
ret... | def socket_send(self) | Called by TelnetServer when send data is ready. | 3.359864 | 3.216389 | 1.044608 |
try:
data = self.sock.recv(2048)
except socket.error, ex:
print ("?? socket.recv() error '%d:%s' from %s" %
(ex[0], ex[1], self.addrport()))
raise BogConnectionLost()
## Did they close the connection?
size = len(data)
... | def socket_recv(self) | Called by TelnetServer when recv data is ready. | 5.253327 | 5.006774 | 1.049244 |
## Filter out non-printing characters
#if (byte >= ' ' and byte <= '~') or byte == '\n':
if self.telnet_echo:
self._echo_byte(byte)
self.recv_buffer += byte | def _recv_byte(self, byte) | Non-printable filtering currently disabled because it did not play
well with extended character sets. | 6.806343 | 5.349172 | 1.272411 |
if byte == '\n':
self.send_buffer += '\r'
if self.telnet_echo_password:
self.send_buffer += '*'
else:
self.send_buffer += byte | def _echo_byte(self, byte) | Echo a character back to the client and convert LF into CR\LF. | 4.839528 | 3.894881 | 1.242535 |
## Are we not currently in an IAC sequence coming from the DE?
if self.telnet_got_iac is False:
if byte == IAC:
## Well, we are now
self.telnet_got_iac = True
return
## Are we currenty in a sub-negotion?
elif ... | def _iac_sniffer(self, byte) | Watches incomming data for Telnet IAC sequences.
Passes the data, if any, with the IAC commands stripped to
_recv_byte(). | 3.606504 | 3.573154 | 1.009334 |
#print "got two byte cmd %d" % ord(cmd)
if cmd == SB:
## Begin capturing a sub-negotiation string
self.telnet_got_sb = True
self.telnet_sb_buffer = ''
elif cmd == SE:
## Stop capturing a sub-negotiation string
self.telnet_got... | def _two_byte_cmd(self, cmd) | Handle incoming Telnet commands that are two bytes long. | 4.538093 | 3.998694 | 1.134894 |
#print "at decoder"
bloc = self.telnet_sb_buffer
if len(bloc) > 2:
if bloc[0] == TTYPE and bloc[1] == IS:
self.terminal_type = bloc[2:]
#print "Terminal type = '%s'" % self.terminal_type
if bloc[0] == NAWS:
if len... | def _sb_decoder(self) | Figures out what to do with a received sub-negotiation block. | 3.786846 | 3.503345 | 1.080923 |
if not self.telnet_opt_dict.has_key(option):
self.telnet_opt_dict[option] = TelnetOption()
return self.telnet_opt_dict[option].local_option | def _check_local_option(self, option) | Test the status of local negotiated Telnet options. | 3.690477 | 2.67803 | 1.378057 |
if not self.telnet_opt_dict.has_key(option):
self.telnet_opt_dict[option] = TelnetOption()
self.telnet_opt_dict[option].local_option = state | def _note_local_option(self, option, state) | Record the status of local negotiated Telnet options. | 3.271981 | 2.385708 | 1.371493 |
if not self.telnet_opt_dict.has_key(option):
self.telnet_opt_dict[option] = TelnetOption()
return self.telnet_opt_dict[option].remote_option | def _check_remote_option(self, option) | Test the status of remote negotiated Telnet options. | 3.576775 | 2.632448 | 1.358726 |
if not self.telnet_opt_dict.has_key(option):
self.telnet_opt_dict[option] = TelnetOption()
self.telnet_opt_dict[option].remote_option = state | def _note_remote_option(self, option, state) | Record the status of local negotiated Telnet options. | 3.219886 | 2.384494 | 1.350343 |
if not self.telnet_opt_dict.has_key(option):
self.telnet_opt_dict[option] = TelnetOption()
return self.telnet_opt_dict[option].reply_pending | def _check_reply_pending(self, option) | Test the status of requested Telnet options. | 3.274519 | 2.379442 | 1.376171 |
if not self.telnet_opt_dict.has_key(option):
self.telnet_opt_dict[option] = TelnetOption()
self.telnet_opt_dict[option].reply_pending = state | def _note_reply_pending(self, option, state) | Record the status of requested Telnet options. | 3.268141 | 2.203057 | 1.483457 |
p1 = subprocess.Popen(cmd1, stdout=subprocess.PIPE)
p2 = subprocess.Popen(cmd2, stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
return p2.communicate()[0] | def pipecmd (cmd1, cmd2) | Return output of "cmd1 | cmd2". | 1.504 | 1.467039 | 1.025194 |
res = pipecmd(["ifconfig", iface], ["grep", "inet "])
info = {}
lastpart = None
for part in res.split():
# Linux systems have prefixes for each value
if part.startswith("addr:"):
info["address"] = part[5:]
elif part.startswith("Bcast:"):
info["broadca... | def ifconfig_inet (iface) | Return parsed IPv4 info from ifconfig(8) binary. | 3.293319 | 3.147819 | 1.046223 |
import fcntl
return fcntl.ioctl(self.sockfd.fileno(), func, args) | def _ioctl (self, func, args) | Call ioctl() with given parameters. | 5.112918 | 4.151554 | 1.231567 |
try:
result = self._ioctl(func, self._getifreq(ifname))
except IOError as msg:
log.warn(LOG_CHECK,
"error getting addr for interface %r: %s", ifname, msg)
return None
return socket.inet_ntoa(result[20:24]) | def _getaddr (self, ifname, func) | Get interface address. | 5.975683 | 5.531688 | 1.080264 |
if sys.platform == 'darwin':
command = ['ifconfig', '-l']
if flags & self.IFF_UP:
command.append('-u')
# replace with subprocess.check_output() for Python 2.7
res = subprocess.Popen(command, stdout=subprocess.PIPE).communicate()[0]
... | def getInterfaceList (self, flags=0) | Get all interface names in a list. | 3.693851 | 3.658887 | 1.009556 |
try:
result = self._ioctl(self.SIOCGIFFLAGS, self._getifreq(ifname))
except IOError as msg:
log.warn(LOG_CHECK,
"error getting flags for interface %r: %s", ifname, msg)
return 0
# extract the interface's flags from the return value
... | def getFlags (self, ifname) | Get the flags for an interface | 6.345718 | 6.198202 | 1.0238 |
if sys.platform == 'darwin':
return ifconfig_inet(ifname).get('address')
return self._getaddr(ifname, self.SIOCGIFADDR) | def getAddr (self, ifname) | Get the inet addr for an interface.
@param ifname: interface name
@type ifname: string | 7.560298 | 7.455357 | 1.014076 |
if sys.platform == 'darwin':
return ifconfig_inet(ifname).get('netmask')
return self._getaddr(ifname, self.SIOCGIFNETMASK) | def getMask (self, ifname) | Get the netmask for an interface.
@param ifname: interface name
@type ifname: string | 7.482025 | 7.090104 | 1.055277 |
if sys.platform == 'darwin':
return ifconfig_inet(ifname).get('broadcast')
return self._getaddr(ifname, self.SIOCGIFBRDADDR) | def getBroadcast (self, ifname) | Get the broadcast addr for an interface.
@param ifname: interface name
@type ifname: string | 8.208501 | 8.001996 | 1.025807 |
# since not all systems have IFF_LOOPBACK as a flag defined,
# the ifname is tested first
if ifname.startswith('lo'):
return True
return (self.getFlags(ifname) & self.IFF_LOOPBACK) != 0 | def isLoopback (self, ifname) | Check whether interface is a loopback device.
@param ifname: interface name
@type ifname: string | 6.310505 | 6.209358 | 1.016289 |
config = dict()
config[cls._filename_re_key] = configparser.get(cls.__name__, cls._filename_re_key) \
if configparser.has_option(cls.__name__, cls._filename_re_key) else None
return config | def read_config(cls, configparser) | Read configuration file options. | 3.350739 | 3.12685 | 1.071602 |
content = url_data.get_content()
self._check_by_re(url_data, content)
self._check_inline_links(url_data, content) | def check(self, url_data) | Extracts urls from the file. | 5.370212 | 5.626418 | 0.954464 |
line = content.count('\n', 0, url_pos) + 1
column = url_pos - content.rfind('\n', 0, url_pos)
url_data.add_url(url_text.translate(None, '\n '), line=line, column=column) | def _save_url(self, url_data, content, url_text, url_pos) | Saves url. Converts url to 1-line text and url position as offset from the file beginning to (line, column).
:param url_data: object for url storing
:param content: file content
:param url_text: url text
:param url_pos: url position from the beginning | 3.059732 | 2.838342 | 1.078 |
for link_re in self._link_res:
for u in link_re.finditer(content):
self._save_url(url_data, content, u.group(1), u.start(1)) | def _check_by_re(self, url_data, content) | Finds urls by re.
:param url_data: object for url storing
:param content: file content | 5.132959 | 5.57189 | 0.921224 |
i = start
l = len(text)
count = 1
while count > 0 and i < l:
if text[i] == open_c:
count += 1
elif text[i] == close_c:
count -= 1
i += 1
return i | def _find_balanced(self, text, start, open_c, close_c) | Returns the index where the open_c and close_c characters balance
out - the same number of open_c and close_c are encountered - or the
end of string if it's reached before the balance point is found. | 1.896542 | 1.882114 | 1.007666 |
# text[start] equals the opening parenthesis
idx = self._whitespace.match(text, start + 1).end()
if idx == len(text):
return None, None
end_idx = idx
has_anglebrackets = text[idx] == "<"
if has_anglebrackets:
end_idx = self._find_balanced(... | def _extract_url_and_title(self, text, start) | Extracts the url from the tail of a link. | 3.144058 | 3.076269 | 1.022036 |
MAX_LINK_TEXT_SENTINEL = 3000
curr_pos = 0
content_length = len(content)
while True: # Handle the next link.
# The next '[' is the start of:
# - an inline anchor: [text](url "title")
# - an inline img: 
... | def _check_inline_links(self, url_data, content) | Checks inline links.
:param url_data: url_data object
:param content: content for processing | 3.970764 | 3.965476 | 1.001334 |
res = False
if attr == "content":
equiv = attrs.get_true('http-equiv', u'').lower()
scheme = attrs.get_true('scheme', u'').lower()
res = equiv in (u'refresh',) or scheme in (u'dcterms.uri',)
if attr == "href":
rel = attrs.get_true('rel', u'').lower()
res = rel in... | def is_meta_url (attr, attrs) | Check if the meta attributes contain a URL. | 4.864189 | 4.519745 | 1.076209 |
res = False
if attr == "action":
method = attrs.get_true('method', u'').lower()
res = method != 'post'
return res | def is_form_get(attr, attrs) | Check if this is a GET form action URL. | 8.257244 | 7.509088 | 1.099633 |
if tag == 'title':
data = self.parser.peek(MAX_TITLELEN)
data = data.decode(self.parser.encoding, "ignore")
self.title = linkname.title_name(data)
raise StopParse("found <title> tag")
elif tag == 'body':
raise StopParse("found <body> t... | def start_element (self, tag, attrs) | Search for <title> tag. | 6.362761 | 5.63134 | 1.129884 |
if tag == 'meta' and attrs.get('name') == 'robots':
val = attrs.get_true('content', u'').lower().split(u',')
self.follow = u'nofollow' not in val
self.index = u'noindex' not in val
raise StopParse("found <meta name=robots> tag")
elif tag == 'body'... | def start_element (self, tag, attrs) | Search for meta robots.txt "nofollow" and "noindex" flags. | 5.074957 | 3.82936 | 1.325275 |
log.debug(LOG_CHECK, "LinkFinder tag %s attrs %s", tag, attrs)
log.debug(LOG_CHECK, "line %d col %d old line %d old col %d", self.parser.lineno(), self.parser.column(), self.parser.last_lineno(), self.parser.last_column())
if tag == "base" and not self.base_ref:
self.base_re... | def start_element (self, tag, attrs) | Search for links and store found URLs in a list. | 4.88661 | 4.65495 | 1.049766 |
if tag == 'a' and attr == 'href':
# Look for name only up to MAX_NAMELEN characters
data = self.parser.peek(MAX_NAMELEN)
data = data.decode(self.parser.encoding, "ignore")
name = linkname.href_name(data)
if not name:
name = att... | def get_link_name (self, tag, attrs, attr) | Parse attrs for link name. Return name of link. | 4.514584 | 4.250113 | 1.062227 |
assert isinstance(tag, unicode), repr(tag)
assert isinstance(attr, unicode), repr(attr)
assert isinstance(name, unicode), repr(name)
assert isinstance(base, unicode), repr(base)
assert isinstance(value, unicode) or value is None, repr(value)
# look for meta refre... | def parse_tag (self, tag, attr, value, name, base) | Add given url data to url list. | 2.665482 | 2.51865 | 1.058298 |
assert isinstance(url, unicode) or url is None, repr(url)
self.callback(url, line=self.parser.last_lineno(),
column=self.parser.last_column(), name=name, base=base) | def found_url(self, url, name, base) | Add newly found URL to queue. | 5.769055 | 5.46511 | 1.055616 |
if isinstance(name, (str, unicode)):
name = dns.name.from_text(name, None)
if isinstance(rdclass, (str, unicode)):
rdclass = dns.rdataclass.from_text(rdclass)
if isinstance(rdtype, (str, unicode)):
rdtype = dns.rdatatype.from_text(rdtype)
r = RRset(name, rdclass, rdtype)
... | def from_text_list(name, ttl, rdclass, rdtype, text_rdatas) | Create an RRset with the specified name, TTL, class, and type, and with
the specified list of rdatas in text format.
@rtype: dns.rrset.RRset object | 1.821087 | 1.808513 | 1.006953 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.