code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
ORIENTATION_PORTRAIT = 0
ORIENTATION_LANDSCAPE = 1
scaling = 2.0
img = self.img
(width, height) = img.size
# take care of rotating the image if required
if print_context.get_width() <= print_context.get_height():
print_orientation = ORIENTAT... | def print_page_cb(self, print_op, print_context, keep_refs={}) | Called for printing operation by Gtk | 3.298718 | 3.363269 | 0.980807 |
src = {}
src["box"] = self.__get_box_path()
src["img"] = self.__get_img_path()
src["thumb"] = self._get_thumb_path()
page_nb = self.page_nb
page_nb += offset
logger.info("--> Moving page %d (+%d) to index %d"
% (self.page_nb, offset... | def change_index(self, offset=0) | Move the page number by a given offset. Beware to not let any hole
in the page numbers when doing this. Make sure also that the wanted
number is available.
Will also change the page number of the current object. | 2.706415 | 2.62634 | 1.030489 |
logger.info("Destroying page: %s" % self)
if self.doc.nb_pages <= 1:
self.doc.destroy()
return
doc_pages = self.doc.pages[:]
current_doc_nb_pages = self.doc.nb_pages
paths = [
self.__get_box_path(),
self.__get_img_path(),
... | def destroy(self) | Delete the page. May delete the whole document if it's actually the
last page. | 3.732415 | 3.319595 | 1.124359 |
other_doc = other_page.doc
other_doc_pages = other_doc.pages[:]
other_doc_nb_pages = other_doc.nb_pages
other_page_nb = other_page.page_nb
to_move = [
(other_page.__get_box_path(), self.__get_box_path()),
(other_page.__get_img_path(), self.__get_... | def _steal_content(self, other_page) | Call ImgDoc.steal_page() instead | 2.801374 | 2.66181 | 1.052432 |
logger.info("Reloading %s ..." % self.__configfile)
# smash the previous config
self._configparser = configparser.SafeConfigParser()
self._configparser.read([self.__configfile])
sections = set()
for setting in self.settings.values():
sections.add(se... | def read(self) | (Re)read the configuration.
Beware that the current work directory may affect this operation:
If there is a 'paperwork.conf' in the current directory, it will be
read instead of '~/.paperwork.conf', see __init__()) | 3.408715 | 3.3105 | 1.029667 |
logger.info("Updating %s ..." % self.__configfile)
for setting in self.settings.values():
setting.update(self._configparser)
file_path = self.__configfile
try:
with open(file_path, 'w') as file_descriptor:
self._configparser.write(file_d... | def write(self) | Rewrite the configuration file. It rewrites the same file than
PaperworkConfig.read() read. | 3.59584 | 3.402047 | 1.056964 |
if parent._children is None:
parent._children = set()
if child._parents is None:
child._parents = set()
parent._children.add(child)
child._parents.add(parent) | def pclink(self, parent, child) | Create a parent-child relationship. | 2.299243 | 2.060755 | 1.115729 |
#eps = np.finfo(float).eps
#pitch = median_filter(pitch, 7)+eps
self.pitch = median_filter(self.pitch, 7)
pitch_quantized = np.zeros(len(self.pitch))
pitch_quantized[0] = utils.find_nearest_index(intervals, self.pitch[0])
pitch_quantized[-1] = utils.find_neares... | def discretize(self, intervals, slope_thresh=1500, cents_thresh=50) | This function takes the pitch data and returns it quantized to given
set of intervals. All transactions must happen in cent scale.
slope_thresh is the bound beyond which the pitch contour is said to transit
from one svara to another. It is specified in cents/sec.
cents_thresh is a limi... | 2.001625 | 1.89406 | 1.056791 |
i = 1
while i < len(self.pitch)-1:
if self.pitch[i] == -10000:
i += 1
continue
if self.pitch[i]-self.pitch[i-1] != 0 and self.pitch[i+1]-self.pitch[i] == 0:
start = i
while i < len(self.pitch) and self.pitch... | def enforce_duration(self, duration_thresh) | This method takes a quantized pitch contour and filters out
those time sections where the contour is not long enough, as specified
by duration threshold (given in milliseconds).
All transactions assume data in cent scale. | 2.38937 | 2.319257 | 1.030231 |
if self._bits is None:
value = self._DEFAULT_BITS.get(self.arch)
if value is None:
raise NotImplementedError('Could not determine the default word size of %s architecture.' % self.arch)
return value
else:
return self._bits | def bits(self) | The target architecture word size. One of :class:`Target.Bits`. | 4.823519 | 3.798917 | 1.269709 |
if self._endian is None:
value = self._DEFAULT_ENDIAN[self.arch]
if value is None:
raise NotImplementedError('Could not determine the default byte order of %s architecture.' % self.arch)
return value
else:
return self._endian | def endian(self) | The target architecture byte order. One of :class:`Target.Endian`. | 5.010695 | 4.148012 | 1.207975 |
self._arch = other._arch
self._bits = other._bits
self._endian = other._endian
self._mode = other._mode | def assume(self, other) | Assume the identity of another target. This can be useful to make the
global target assume the identity of an ELF executable.
Arguments:
other(:class:`Target`): The target whose identity to assume.
Example:
>>> from pwny import *
>>> target.assume(ELF('my-ex... | 4.148312 | 4.325696 | 0.958993 |
user = request.user
if not user.is_authenticated():
return False
elif user.is_superuser:
return True
elif user.is_staff:
return True
else:
return False | def has_read_permission(self, request, path) | Just return True if the user is an authenticated staff member.
Extensions could base the permissions on the path too. | 2.229434 | 1.964793 | 1.134692 |
try:
children = parent.enumerate_children(
Gio.FILE_ATTRIBUTE_STANDARD_NAME,
Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,
None
)
except GLib.GError:
# assumes it's a file and not a directory
yield paren... | def _recurse(self, parent, dir_included=False) | Yield all the children (depth first), but not the parent. | 3.564273 | 3.451382 | 1.032709 |
'''
Fetches rows from the local cache or from the db if there's no cache.
:param table: table name to select
:cols: list of columns to select
:return: list of rows
:rtype: list
'''
if self.orng_tables:
data = []
for... | def rows(self, table, cols) | Fetches rows from the local cache or from the db if there's no cache.
:param table: table name to select
:cols: list of columns to select
:return: list of rows
:rtype: list | 5.129996 | 2.69241 | 1.905355 |
'''
SELECT with WHERE clause.
:param table: target table
:param cols: list of columns to select
:param pk_att: attribute for the where clause
:param pk: the id that the pk_att should match
:return: rows from the given table and cols, with the ... | def select_where(self, table, cols, pk_att, pk) | SELECT with WHERE clause.
:param table: target table
:param cols: list of columns to select
:param pk_att: attribute for the where clause
:param pk: the id that the pk_att should match
:return: rows from the given table and cols, with the condition pk_att==pk... | 4.194966 | 2.153852 | 1.947657 |
result=".".join([ str(ord(s)) for s in string ])
return "%s." % (len(string)) + result | def encode(string) | Encode the given string as an OID.
>>> import snmp_passpersist as snmp
>>> snmp.PassPersist.encode("hello")
'5.104.101.108.108.111'
>>> | 10.600646 | 12.838223 | 0.82571 |
try:
self.lock.acquire()
if oid not in self.data:
return "NONE"
else:
return self.base_oid + oid + '\n' + self.data[oid]['type'] + '\n' + str(self.data[oid]['value'])
finally:
self.lock.release() | def get(self,oid) | Return snmp value for the given OID. | 3.047859 | 2.999539 | 1.016109 |
try: # Nested try..except because of Python 2.4
self.lock.acquire()
try:
# remove trailing zeroes from the oid
while len(oid) > 0 and oid[-2:] == ".0" and oid not in self.data:
oid = oid[:-2];
return self.get(self.data_idx[self.data_idx.index(oid)+1])
except ValueError:
# Not found: t... | def get_next(self,oid) | Return snmp value for the next OID. | 4.047814 | 3.97256 | 1.018943 |
try: # Nested try..except because of Python 2.4
self.lock.acquire()
try:
return self.get(self.data_idx[0])
except (IndexError, ValueError):
return "NONE"
finally:
self.lock.release() | def get_first(self) | Return snmp value for the first OID. | 5.08357 | 4.866953 | 1.044508 |
if not full_oid.startswith(self.base_oid.rstrip('.')):
return None
else:
return full_oid[len(self.base_oid):] | def cut_oid(self,full_oid) | Remove the base OID from the given string.
>>> import snmp_passpersist as snmp
>>> pp=snmp.PassPersist(".1.3.6.1.3.53.8")
>>> pp.cut_oid(".1.3.6.1.3.53.8.28.12")
'28.12' | 2.783391 | 3.47434 | 0.801128 |
if self.debug:
print('DEBUG: %s %s %s %s'%(oid,type,value,label))
item={'type': str(type), 'value': str(value)}
if label is not None:
item['label']=str(label)
self.pending[oid]=item | def add_oid_entry(self, oid, type, value, label=None) | General function to add an oid entry to the MIB subtree. | 3.540414 | 3.675845 | 0.963156 |
self.add_oid_entry(oid,'OBJECTID',value,label=label) | def add_oid(self,oid,value,label=None) | Short helper to add an object ID value to the MIB subtree. | 7.691412 | 7.465779 | 1.030222 |
self.add_oid_entry(oid,'INTEGER',value,label=label) | def add_int(self,oid,value,label=None) | Short helper to add an integer value to the MIB subtree. | 6.316198 | 5.550931 | 1.137863 |
self.add_oid_entry(oid,'OCTET',value,label=label) | def add_oct(self,oid,value,label=None) | Short helper to add an octet value to the MIB subtree. | 7.084996 | 5.801859 | 1.22116 |
self.add_oid_entry(oid,'STRING',value,label=label) | def add_str(self,oid,value,label=None) | Short helper to add a string value to the MIB subtree. | 6.821361 | 5.43587 | 1.254879 |
self.add_oid_entry(oid,'IPADDRESS',value,label=label) | def add_ip(self,oid,value,label=None) | Short helper to add an IP address value to the MIB subtree. | 7.410359 | 6.244767 | 1.186651 |
# Truncate integer to 32bits ma,x
self.add_oid_entry(oid,'Counter32',int(value)%4294967296,label=label) | def add_cnt_32bit(self,oid,value,label=None) | Short helper to add a 32 bit counter value to the MIB subtree. | 8.7669 | 8.468801 | 1.0352 |
# Truncate integer to 64bits ma,x
self.add_oid_entry(oid,'Counter64',int(value)%18446744073709551615,label=label) | def add_cnt_64bit(self,oid,value,label=None) | Short helper to add a 64 bit counter value to the MIB subtree. | 6.250907 | 6.247524 | 1.000542 |
self.add_oid_entry(oid,'GAUGE',value,label=label) | def add_gau(self,oid,value,label=None) | Short helper to add a gauge value to the MIB subtree. | 8.405045 | 5.183262 | 1.621574 |
def add_tt(self,oid,value,label=None):
self.add_oid_entry(oid,'TIMETICKS',value,label=label) | Short helper to add a timeticks value to the MIB subtree. | null | null | null | |
line = sys.stdin.readline().strip()
if not line:
raise EOFError()
if 'PING' in line:
print("PONG")
elif 'getnext' in line:
oid = self.cut_oid(sys.stdin.readline().strip())
if oid is None:
print("NONE")
elif oid == "":
# Fallback to the first entry
print(self.get_first())
else:
... | def main_passpersist(self) | Main function that handle SNMP's pass_persist protocol, called by
the start method.
Direct call is unnecessary. | 2.723524 | 2.669013 | 1.020424 |
# Generate index before acquiring lock to keep locked section fast
# Works because this thread is the only writer of self.pending
pending_idx = sorted(list(self.pending.keys()), key=lambda k: tuple(int(part) for part in k.split('.')))
# Commit new data
try:
self.lock.acquire()
self.data=self.pendin... | def commit(self) | Commit change made by the add_* methods.
All previous values with no update will be lost.
This method is automatically called by the updater thread. | 6.298032 | 6.059519 | 1.039362 |
# Renice updater thread to limit overload
try:
os.nice(1)
except AttributeError as er:
pass # os.nice is not available on windows
time.sleep(self.refresh)
try:
while True:
# We pick a timestamp to take in account the time used by update()
timestamp=time.time()
# Update data with user... | def main_update(self) | Main function called by the updater thread.
Direct call is unnecessary. | 9.419914 | 9.074982 | 1.038009 |
if hasattr(self.setter, oid):
return self.setter[oid]
parents = [ poid for poid in list(self.setter.keys()) if oid.startswith(poid) ]
if parents:
return self.setter[max(parents)]
return self.default_setter | def get_setter(self, oid) | Retrieve the nearest parent setter function for an OID | 3.346545 | 2.986765 | 1.120458 |
success = False
type_ = typevalue.split()[0]
value = typevalue.lstrip(type_).strip().strip('"')
ret_value = self.get_setter(oid)(oid, type_, value)
if ret_value:
if ret_value in ErrorValues or ret_value == 'DONE':
print(ret_value)
elif ret_value == True:
print('DONE')
elif ret_value == Fal... | def set(self, oid, typevalue) | Call the default or user setter function if available | 4.137453 | 4.038957 | 1.024386 |
self.update=user_func
self.refresh=refresh
self.error=None
# First load
self.update()
self.commit()
# Start updater thread
up = threading.Thread(None,self.main_update,"Updater")
up.daemon = True
up.start()
# Main loop
while up.isAlive(): # Do not serve data if the Updater thread has died
... | def start(self, user_func, refresh) | Start the SNMP's protocol handler and the updater thread
user_func is a reference to an update function, ran every 'refresh' seconds. | 5.718042 | 5.739529 | 0.996256 |
if not issubclass(type(obj), ModelBase):
obj = obj.__class__
key_hash = []
for key in dir(obj):
try:
attr = getattr(obj, key)
except AttributeError as e:
try:
attr = obj.__dict__[key]
except KeyError:
raise At... | def _get_members_of_type(obj, member_type) | Finds members of a certain type in obj.
:param obj: A model instance or class.
:param member_type: The type of the menber we are trying to find.
:rtype: A :class:`list` of ``member_type`` found in ``obj`` | 3.398639 | 3.319817 | 1.023743 |
if self.idx >= len(self.page_list):
raise StopIteration()
page = self.page_list[self.idx]
self.idx += 1
return page | def next(self) | Provide the next element of the list. | 2.807192 | 2.832834 | 0.990948 |
try:
filelist = self.fs.listdir(self.path)
count = 0
for filepath in filelist:
filename = self.fs.basename(filepath)
if (filename[-4:].lower() != "." + ImgPage.EXT_IMG or
(filename[-10:].lower() == "." + ImgPage.EXT... | def _get_nb_pages(self) | Compute the number of pages in the document. It basically counts
how many JPG files there are in the document. | 3.168052 | 2.999027 | 1.05636 |
page = ImgPage(self, page_nb)
page.print_page_cb(print_op, print_context, keep_refs=keep_refs) | def print_page_cb(self, print_op, print_context, page_nb, keep_refs={}) | Called for printing operation by Gtk | 3.818848 | 4.044816 | 0.944134 |
if page.doc == self:
return
self.fs.mkdir_p(self.path)
new_page = ImgPage(self, self.nb_pages)
logger.info("%s --> %s" % (str(page), str(new_page)))
new_page._steal_content(page) | def steal_page(self, page) | Steal a page from another document | 6.637754 | 6.065442 | 1.094356 |
try:
if not getattr(RECURSION_LEVEL_DICT, 'key', False):
RECURSION_LEVEL_DICT.key = 0
RECURSION_LEVEL_DICT.key += 1
yield RECURSION_LEVEL_DICT.key
RECURSION_LEVEL_DICT.key -= 1
except Exception as e:
RECURSION_LEVEL_DICT.key = 0
raise e | def recursion_depth(key) | A context manager used to guard recursion depth for some function.
Multiple functions can be kept separately because it will be
counted per key.
Any exceptions raise in the recursive function will reset the counter,
because the stack will be unwinded.
usage::
with recursion_depth('some_fu... | 2.704005 | 2.612982 | 1.034835 |
for item in lst:
val = predicate(item)
if val is not None:
return val
return None | def first_match(predicate, lst) | returns the first value of predicate applied to list, which
does not return None
>>>
>>> def return_if_even(x):
... if x % 2 is 0:
... return x
... return None
>>>
>>> first_match(return_if_even, [1, 3, 4, 7])
4
>>> first_match(return_if_even, [1, 3, 5, 7])
>... | 3.795305 | 4.392674 | 0.864008 |
for base in cls.__bases__:
yield base
for more in bases_walker(base):
yield more | def bases_walker(cls) | Loop through all bases of cls
>>> str = u'hai'
>>> for base in bases_walker(unicode):
... isinstance(str, base)
True
True
:param cls: The class in which we want to loop through the base classes. | 3.94059 | 6.076525 | 0.648494 |
parsed_url = urlparse.urlsplit(url)
params = urlparse.parse_qsl(parsed_url.query)
parsed_url = list(parsed_url)
for pair in kwargs.iteritems():
params.append(pair)
parsed_url[3] = urllib.urlencode(params)
return urlparse.urlunsplit(parsed_url) | def url_add_params(url, **kwargs) | Add parameters to an url
>>> url_add_params('http://example.com/', a=1, b=3)
'http://example.com/?a=1&b=3'
>>> url_add_params('http://example.com/?c=8', a=1, b=3)
'http://example.com/?c=8&a=1&b=3'
>>> url_add_params('http://example.com/#/irock', a=1, b=3)
'http://example.com/?a=1&b=3#/irock'
... | 1.980187 | 2.591646 | 0.764065 |
if not hasattr(request, '_cache_update_cache') or not request._cache_update_cache:
# We don't need to update the cache, just return.
return response
if request.method != 'GET':
# This is a stronger requirement than above. It is needed
# because of... | def process_response(self, request, response) | Sets the cache, if needed. | 4.546263 | 4.434461 | 1.025212 |
if self.cache_anonymous_only:
assert hasattr(request, 'user'), "The Django cache middleware with CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True requires authentication middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.auth.middleware.AuthenticationMiddleware' ... | def process_request(self, request) | Checks whether the page is already cached and returns the cached
version if available. | 2.998705 | 2.963167 | 1.011993 |
xsl_path = find_template_path(template)
xml = xmltree.xml(object)
result = transform(xml, str(xsl_path), params)
return HttpResponse(result, mimetype=mimetype) | def render_to_response(template, object, params=None, mimetype='text/html') | ``object`` will be converted to xml using :func:`easymode.tree.xml`. The resulting xml
will be transformed using ``template``.
The result will be a :class:`~django.http.HttpResponse` object,
containing the transformed xml as the body.
:param template: an xslt template name.
:param object: an o... | 6.031165 | 5.477227 | 1.101135 |
xsl_path = find_template_path(template)
xml = xmltree.xml(object)
result = transform(xml, str(xsl_path), params)
return result | def render_to_string(template, object, params=None) | ``object`` will be converted to xml using :func:`easymode.tree.xml`. The resulting xml
will be transformed using ``template``.
The result is a unicode string containing the transformed xml.
:param template: an xslt template name.
:param object: an object that has an ``__xml__`` method. (See :func:... | 7.748269 | 7.743943 | 1.000559 |
xsl_path = find_template_path(template)
result = transform(input, str(xsl_path), params)
return result | def render_xml_to_string(template, input, params=None) | Transforms ``input`` using ``template``, which should be an xslt.
:param template: an xslt template name.
:param input: an string that contains xml
:param params: A dictionary containing xslt parameters. Use :func:`~easymode.xslt.prepare_string_param`\
on strings you want to pass in.
:rtype... | 7.81682 | 10.565274 | 0.73986 |
obj_class = obj.__class__
if obj_class is bool or obj_class is NoneType:
# we can not have a standing for bool or NoneType
# because too many code uses a is True or a is None.
# Also you can never get isinstance(standin, bool) and
# isinstance(standin, NoneType) to work... | def standin_for(obj, **attrs) | Returns an object that can be used as a standin for the original object.
The standin object will have extra attrs, which you can define passed as keyword arguments.
Use standin like this:
>>> a = u'I am E.T.'
>>> b = standin_for(a, origin='outerspace', package='easymode.utils.standin')
... | 5.145723 | 4.443543 | 1.158023 |
'''
Runs TreeLiker with the given settings.
:param cleanup: deletes temporary files after completion
:param printOutput: print algorithm output to the terminal
'''
self._copy_data()
self._batch()
dumpFile = None
if not printOutput:
... | def run(self, cleanup=True, printOutput=False) | Runs TreeLiker with the given settings.
:param cleanup: deletes temporary files after completion
:param printOutput: print algorithm output to the terminal | 4.704619 | 3.536294 | 1.330381 |
'''
Creates the batch file to run the experiment.
'''
self.batch = '%s/%s.treeliker' % (self.tmpdir, self.basename)
commands = []
if not self.test_dataset:
commands.append('set(output_type, single)')
commands.append("set(examples, '%s.txt')" % sel... | def _batch(self) | Creates the batch file to run the experiment. | 3.27149 | 3.010483 | 1.086699 |
if fmt.lower() == 'jd':
return jd
elif fmt.lower() == 'mjd':
return jd - 2400000.5
elif fmt.lower() == 'rjd':
return jd - 2400000
else:
raise ValueError('Invalid Format') | def __to_format(jd: float, fmt: str) -> float | Converts a Julian Day object into a specific format. For
example, Modified Julian Day.
Parameters
----------
jd: float
fmt: str
Returns
-------
jd: float | 2.119792 | 2.071487 | 1.023319 |
if fmt.lower() == 'jd':
# If jd has a fractional component of 0, then we are 12 hours into
# the day
return math.floor(jd + 0.5), jd + 0.5 - math.floor(jd + 0.5)
elif fmt.lower() == 'mjd':
return __from_format(jd + 2400000.5, 'jd')
elif fmt.lower() == 'rjd':
retu... | def __from_format(jd: float, fmt: str) -> (int, float) | Converts a Julian Day format into the "standard" Julian
day format.
Parameters
----------
jd
fmt
Returns
-------
(jd, fractional): (int, float)
A tuple representing a Julian day. The first number is the
Julian Day Number, and the second is the fractional component of ... | 2.710151 | 2.672632 | 1.014038 |
a = math.floor((14-dt.month)/12)
y = dt.year + 4800 - a
m = dt.month + 12*a - 3
jdn = dt.day + math.floor((153*m + 2)/5) + 365*y + math.floor(y/4) - math.floor(y/100) + math.floor(y/400) - 32045
jd = jdn + (dt.hour - 12) / 24 + dt.minute / 1440 + dt.second / 86400 + dt.microsecond / 864000000... | def to_jd(dt: datetime, fmt: str = 'jd') -> float | Converts a given datetime object to Julian date.
Algorithm is copied from https://en.wikipedia.org/wiki/Julian_day
All variable names are consistent with the notation on the wiki page.
Parameters
----------
fmt
dt: datetime
Datetime object to convert to MJD
Returns
-------
... | 1.739476 | 1.753617 | 0.991936 |
jd, jdf = __from_format(jd, fmt)
l = jd+68569
n = 4*l//146097
l = l-(146097*n+3)//4
i = 4000*(l+1)//1461001
l = l-1461*i//4+31
j = 80*l//2447
k = l-2447*j//80
l = j//11
j = j+2-12*l
i = 100*(n-49)+i+l
year = int(i)
month = int(j)
day = int(k)
# in micr... | def from_jd(jd: float, fmt: str = 'jd') -> datetime | Converts a Julian Date to a datetime object.
Algorithm is from Fliegel and van Flandern (1968)
Parameters
----------
jd: float
Julian Date as type specified in the string fmt
fmt: str
Returns
-------
dt: datetime | 2.076122 | 2.194215 | 0.94618 |
self.log('Reading: %s'%table)
# Entity class
cls = self.FACTORIES[table]
f = self._open(table)
# csv reader
if unicodecsv:
data = unicodecsv.reader(f, encoding='utf-8-sig')
else:
data = csv.reader(f)
header = data.next()
headerlen = len(header)
ent = collections.... | def iterread(self, table) | Iteratively read data from a GTFS table. Returns namedtuples. | 4.175957 | 4.051419 | 1.030739 |
# Table exists
if table in self.by_id:
return self.by_id[table].values()
if table in self.cache:
return self.cache[table]
# Read table
cls = self.FACTORIES[table]
key = cls.KEY
if key:
if table not in self.by_id:
self.by_id[table] = {}
t = self.by_id[tabl... | def read(self, table) | ... | 2.65486 | 2.615685 | 1.014977 |
if os.path.exists(filename):
raise IOError('File exists: %s'%filename)
# Make sure we have all the entities loaded.
if sortkey:
entities = sorted(entities, key=lambda x:x[sortkey])
if not columns:
columns = set()
for entity in entities:
columns |= set(entity.keys())
... | def write(self, filename, entities, sortkey=None, columns=None) | Write entities out to filename in csv format.
Note: this doesn't write directly into a Zip archive, because this behavior
is difficult to achieve with Zip archives. Use make_zip() to create a new
GTFS Zip archive. | 2.411841 | 2.415045 | 0.998673 |
if filename and os.path.exists(filename):
raise IOError('File exists: %s'%filename)
files = files or []
arcnames = []
if path and os.path.isdir(path):
files += glob.glob(os.path.join(path, '*.txt'))
if compress:
compress_level = zipfile.ZIP_DEFLATED
else:
compress_le... | def make_zip(self, filename, files=None, path=None, clone=None, compress=True) | Create a Zip archive.
Provide any of the following:
files - A list of files
path - A directory of .txt files
clone - Copy any files from a zip archive not specified above
Duplicate files will be ignored. The 'files' argument will be used first,
then files found in the specified 'path', t... | 2.124793 | 2.094384 | 1.014519 |
# Todo: Cache?
if self._shapes:
return self._shapes
# Group together by shape_id
self.log("Generating shapes...")
ret = collections.defaultdict(entities.ShapeLine)
for point in self.read('shapes'):
ret[point['shape_id']].add_child(point)
self._shapes = ret
return self._s... | def shapes(self) | Return the route shapes as a dictionary. | 8.126877 | 7.126139 | 1.140432 |
validator = validation.make_validator(validator)
self.log('Loading...')
self.preload()
# required
required = [
'agency',
'stops',
'routes',
'trips',
'stop_times',
'calendar'
]
for f in required:
self.log("Validating required file: %s"%f)
d... | def validate(self, validator=None, skip_relations=False) | Validate a GTFS
:param validator: a ValidationReport
:param (bool) skip_relations: skip validation of relations between entities (e.g. stop_times to stops)
:return: | 2.487607 | 2.374416 | 1.047671 |
if isinstance(value, six.binary_type):
return self._alloc_data(value)
elif isinstance(value, six.text_type):
return self._alloc_data(value.encode('utf-8') + b'\0')
else:
raise TypeError('No idea how to encode %s' % repr(value)) | def alloc_data(self, value) | Allocate a piece of data that will be included in the shellcode body.
Arguments:
value(...): The value to add to the shellcode. Can be bytes or
string type.
Returns:
~pwnypack.types.Offset: The offset used to address the data. | 2.713134 | 2.813135 | 0.964452 |
buf = Buffer(sum(len(v) for v in six.iterkeys(self.data)) + sum(v.length for v in self.buffers), length)
self.buffers.append(buf)
return buf | def alloc_buffer(self, length) | Allocate a buffer (a range of uninitialized memory).
Arguments:
length(int): The length of the buffer to allocate.
Returns:
~pwnypack.types.Buffer: The object used to address this buffer. | 5.9579 | 7.317632 | 0.814184 |
if isinstance(value, (six.text_type, six.binary_type)):
value = self.alloc_data(value)
if value is None:
return self.reg_load_imm(reg, 0)
elif isinstance(value, Register):
if reg is not value:
return self.reg_load_reg(reg, value)
... | def reg_load(self, reg, value) | Load a value into a register. The value can be a string or binary (in
which case the value is passed to :meth:`alloc_data`), another
:class:`Register`, an :class:`Offset` or :class:`Buffer`, an integer
immediate, a ``list`` or ``tuple`` or a syscall invocation.
Arguments:
re... | 2.506975 | 2.220714 | 1.128905 |
if value is None:
return []
elif isinstance(value, Register):
return self.reg_add_reg(reg, value)
elif isinstance(value, (Buffer, six.integer_types)):
if isinstance(reg, Buffer):
value = sum(len(v) for v in six.iterkeys(self.data)) ... | def reg_add(self, reg, value) | Add a value to a register. The value can be another :class:`Register`,
an :class:`Offset`, a :class:`Buffer`, an integer or ``None``.
Arguments:
reg(pwnypack.shellcode.types.Register): The register to add the
value to.
value: The value to add to the register.
... | 3.066066 | 2.781916 | 1.102142 |
def _compile():
code = []
for op in ops:
if isinstance(op, SyscallInvoke):
code.extend(self.syscall(op))
elif isinstance(op, LoadRegister):
code.extend(self.reg_load(op.register, op.value))
... | def compile(self, ops) | Translate a list of operations into its assembler source.
Arguments:
ops(list): A list of shellcode operations.
Returns:
str: The assembler source code that implements the shellcode. | 5.665988 | 5.482687 | 1.033433 |
return pwnypack.asm.asm(self.compile(ops), target=self.target) | def assemble(self, ops) | Assemble a list of operations into executable code.
Arguments:
ops(list): A list of shellcode operations.
Returns:
bytes: The executable code that implements the shellcode. | 18.368961 | 18.378075 | 0.999504 |
def decorator(f):
@functools.wraps(f)
def proxy(*p_args, **p_kwargs):
env = cls(**kwargs)
result = translate(env, f, *p_args, **p_kwargs)
if output == cls.TranslateOutput.code:
return env.assemble(result)
... | def translate(cls, f=None, output=0, **kwargs) | translate(f=None, *, output=TranslateOutput.code, **kwargs)
Decorator that turns a function into a shellcode emitting function.
Arguments:
f(callable): The function to decorate. If ``f`` is ``None`` a
decorator will be returned instead.
output(~pwnypack.shellcode... | 3.420102 | 2.944202 | 1.16164 |
arr = np.array(arr)
index = (abs(arr-value)).argmin()
return index | def find_nearest_index(arr, value) | For a given value, the function finds the nearest value
in the array and returns its index. | 3.182111 | 3.110409 | 1.023052 |
num_samples = y.size
x = np.insert(x, 0, np.ones(num_samples), axis=1)
return pinv(x)*y | def normal_equation(x, y) | X: matrix of features, one sample per row (without bias unit)
y: values (continuous) corresponding to rows (samples) in X | 5.036131 | 4.256679 | 1.183113 |
d = b''
while n:
try:
block = self._process.stdout.read(n)
except ValueError:
block = None
if not block:
self._process.poll()
raise EOFError('Process ended')
d += block
n... | def read(self, n) | Read *n* bytes from the subprocess' output channel.
Args:
n(int): The number of bytes to read.
Returns:
bytes: *n* bytes of output.
Raises:
EOFError: If the process exited. | 3.69786 | 3.118193 | 1.185898 |
self._process.poll()
if self._process.returncode is not None:
raise EOFError('Process ended')
self._process.stdin.write(data) | def write(self, data) | Write *n* bytes to the subprocess' input channel.
Args:
data(bytes): The data to write.
Raises:
EOFError: If the process exited. | 4.771498 | 3.84436 | 1.241168 |
d = b''
while n:
try:
block = self._socket.recv(n)
except socket.error:
block = None
if not block:
raise EOFError('Socket closed')
d += block
n -= len(block)
return d | def read(self, n) | Receive *n* bytes from the socket.
Args:
n(int): The number of bytes to read.
Returns:
bytes: *n* bytes read from the socket.
Raises:
EOFError: If the socket was closed. | 3.14422 | 2.81336 | 1.117603 |
while data:
try:
n = self._socket.send(data)
except socket.error:
n = None
if not n:
raise EOFError('Socket closed')
data = data[n:] | def write(self, data) | Send *n* bytes to socket.
Args:
data(bytes): The data to send.
Raises:
EOFError: If the socket was closed. | 3.784265 | 3.02367 | 1.251547 |
self._socket.shutdown(socket.SHUT_RDWR)
self._socket.close() | def kill(self) | Shut down the socket immediately. | 4.867965 | 3.091548 | 1.574604 |
d = self.channel.read(n)
if echo or (echo is None and self.echo):
sys.stdout.write(d.decode('latin1'))
sys.stdout.flush()
return d | def read(self, n, echo=None) | Read *n* bytes from the channel.
Args:
n(int): The number of bytes to read from the channel.
echo(bool): Whether to write the read data to stdout.
Returns:
bytes: *n* bytes of data.
Raises:
EOFError: If the channel was closed. | 3.484277 | 4.071218 | 0.855832 |
d = b''
while True:
try:
d += self.read(1, echo)
except EOFError:
return d | def read_eof(self, echo=None) | Read until the channel is closed.
Args:
echo(bool): Whether to write the read data to stdout.
Returns:
bytes: The read data. | 4.984551 | 4.824236 | 1.033231 |
s_len = len(s)
buf = self.read(s_len, echo)
while buf[-s_len:] != s:
buf += self.read(1, echo)
return buf | def read_until(self, s, echo=None) | Read until a certain string is encountered..
Args:
s(bytes): The string to wait for.
echo(bool): Whether to write the read data to stdout.
Returns:
bytes: The data up to and including *s*.
Raises:
EOFError: If the channel was closed. | 3.034734 | 3.746766 | 0.809961 |
return [
self.until(b'\n', echo)
for _ in range(n)
] | def readlines(self, n, echo=None) | Read *n* lines from channel.
Args:
n(int): The number of lines to read.
echo(bool): Whether to write the read data to stdout.
Returns:
list of bytes: *n* lines which include new line characters.
Raises:
EOFError: If the channel was closed before... | 7.684766 | 10.243248 | 0.750227 |
if echo or (echo is None and self.echo):
sys.stdout.write(data.decode('latin1'))
sys.stdout.flush()
self.channel.write(data) | def write(self, data, echo=None) | Write data to channel.
Args:
data(bytes): The data to write to the channel.
echo(bool): Whether to echo the written data to stdout.
Raises:
EOFError: If the channel was closed before all data was sent. | 3.963491 | 3.924538 | 1.009925 |
self.write(sep.join(lines + [b'']), echo) | def writelines(self, lines, sep=b'\n', echo=None) | Write a list of byte sequences to the channel and terminate them
with a separator (line feed).
Args:
lines(list of bytes): The lines to send.
sep(bytes): The separator to use after each line.
echo(bool): Whether to echo the written data to stdout.
Raises:
... | 8.098674 | 9.313395 | 0.869573 |
self.writelines([line], sep, echo) | def writeline(self, line=b'', sep=b'\n', echo=None) | Write a byte sequences to the channel and terminate it with carriage
return and line feed.
Args:
line(bytes): The line to send.
sep(bytes): The separator to use after each line.
echo(bool): Whether to echo the written data to stdout.
Raises:
EOFE... | 11.725892 | 12.201635 | 0.96101 |
sockets = [sys.stdin, self.channel]
while True:
ready = select.select(sockets, [], [])[0]
if sys.stdin in ready:
line = sys.stdin.readline().encode('latin1')
if not line:
break
self.write(line)
... | def interact(self) | Interact with the socket. This will send all keyboard input to the
socket and input from the socket to the console until an EOF occurs. | 3.632255 | 3.090743 | 1.175204 |
echo = kwargs.pop('echo', False)
return cls(ProcessChannel(executable, *arguments, **kwargs), echo=echo) | def execute(cls, executable, *arguments, **kwargs) | execute(executable, argument..., redirect_stderr=False, echo=False):
Set up a :class:`ProcessChannel` and create a :class:`Flow` instance
for it.
Args:
executable(str): The executable to start.
argument...(list of str): The arguments to pass to the executable.
... | 7.066454 | 4.853972 | 1.455809 |
return cls(TCPClientSocketChannel(host, port), echo=echo) | def connect_tcp(cls, host, port, echo=False) | Set up a :class:`TCPClientSocketChannel` and create a :class:`Flow`
instance for it.
Args:
host(str): The hostname or IP address to connect to.
port(int): The port number to connect to.
echo(bool): Whether to echo read/written data to stdout by default.
Retu... | 13.746572 | 9.184129 | 1.496775 |
return cls(TCPServerSocketChannel(host, port), echo=echo) | def listen_tcp(cls, host='', port=0, echo=False) | Set up a :class:`TCPServerSocketChannel` and create a :class:`Flow`
instance for it.
Args:
host(str): The hostname or IP address to bind to.
port(int): The port number to listen on.
echo(bool): Whether to echo read/written data to stdout by default.
Returns:... | 15.166449 | 9.787481 | 1.549576 |
client = SSHClient()
client.connect(*args, **kwargs)
return client | def connect_ssh(*args, **kwargs) | Create a new connected :class:`SSHClient` instance. All arguments
are passed to :meth:`SSHClient.connect`. | 5.46755 | 3.951128 | 1.383795 |
pty = kwargs.pop('pty', False)
echo = kwargs.pop('echo', False)
client = cls.connect_ssh(*args, **kwargs)
f = client.execute(command, pty=pty, echo=echo)
f.client = client
return f | def execute_ssh(cls, command, *args, **kwargs) | execute_ssh(command, arguments..., pty=False, echo=False)
Execute `command` on a remote server. It first calls
:meth:`Flow.connect_ssh` using all positional and keyword
arguments, then calls :meth:`SSHClient.execute` with the command
and pty / echo options.
Args:
co... | 3.504308 | 2.480492 | 1.412747 |
pty = kwargs.pop('pty', True)
echo = kwargs.pop('echo', False)
client = cls.connect_ssh(*args, **kwargs)
f = client.invoke_shell(pty=pty, echo=echo)
f.client = client
return f | def invoke_ssh_shell(cls, *args, **kwargs) | invoke_ssh(arguments..., pty=False, echo=False)
Star a new shell on a remote server. It first calls
:meth:`Flow.connect_ssh` using all positional and keyword
arguments, then calls :meth:`SSHClient.invoke_shell` with the
pty / echo options.
Args:
arguments...: The op... | 3.503007 | 2.661922 | 1.315969 |
if cls._meta.abstract:
raise Exception("You can not use toxml on abstract classes")
def __xml__(self):
ser = RecursiveXmlSerializer()
return ser.serialize([self])
cls.add_to_class('objects', QuerySetManager(XmlSerializableQuerySet))
cls.__xml__ = ... | def toxml(cls) | adds an ``__xml__`` method to both the queryset as the model class.
usage::
from easymode.tree.xml.decorators import toxml
@toxml
class Foo(models.ModelAdmin):
title = models.CharField(max_length=255)
content = TextField()
class Bar(models.ModelAdm... | 7.785472 | 7.453169 | 1.044585 |
importers = []
for importer in IMPORTERS:
if importer.can_import(file_uris, current_doc):
importers.append(importer)
return importers | def get_possible_importers(file_uris, current_doc=None) | Return all the importer objects that can handle the specified files.
Possible imports may vary depending on the currently active document | 2.405689 | 2.639125 | 0.911548 |
if len(file_uris) <= 0:
return False
for uri in file_uris:
uri = self.fs.safe(uri)
if not self.check_file_type(uri):
return False
return True | def can_import(self, file_uris, current_doc=None) | Check that the specified file looks like a PDF | 3.938048 | 3.871771 | 1.017118 |
doc = None
docs = []
pages = []
file_uris = [self.fs.safe(uri) for uri in file_uris]
imported = []
for file_uri in file_uris:
if docsearch.is_hash_in_index(PdfDoc.hash_file(self.fs, file_uri)):
logger.info("Document %s already found i... | def import_doc(self, file_uris, docsearch, current_doc=None) | Import the specified PDF file | 3.82454 | 3.847478 | 0.994038 |
if len(file_uris) <= 0:
return False
try:
for file_uri in file_uris:
file_uri = self.fs.safe(file_uri)
for child in self.fs.recurse(file_uri):
if self.check_file_type(child):
return True
... | def can_import(self, file_uris, current_doc=None) | Check that the specified file looks like a directory containing many
pdf files | 3.589438 | 3.564679 | 1.006946 |
doc = None
docs = []
pages = []
file_uris = [self.fs.safe(uri) for uri in file_uris]
imported = []
for file_uri in file_uris:
logger.info("Importing PDF from '%s'" % (file_uri))
idx = 0
for child in self.fs.recurse(file_uri)... | def import_doc(self, file_uris, docsearch, current_doc=None) | Import the specified PDF files | 4.092986 | 4.165735 | 0.982536 |
if (current_doc is None or
current_doc.is_new or
not current_doc.can_edit):
if not current_doc or not current_doc.can_edit:
current_doc = ImgDoc(self.fs, docsearch.rootdir)
new_docs = [current_doc]
upd_docs = []
... | def import_doc(self, file_uris, docsearch, current_doc=None) | Import the specified PDF files | 3.018154 | 3.08531 | 0.978233 |
if len(file_uris) <= 0:
return False
for file_uri in file_uris:
file_uri = self.fs.safe(file_uri)
if not self.check_file_type(file_uri):
return False
return True | def can_import(self, file_uris, current_doc=None) | Check that the specified file looks like an image supported by PIL | 3.332312 | 3.05209 | 1.091813 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.