code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
query = [ 'gerrit', 'query', '--current-patch-set', str(self._filters), '--format=JSON'] results = self.client.exec_command(' '.join(query)) stdin, stdout, stderr = results for line in stdout: normalized = json.loads...
def _execute(self)
Executes the query and yields items.
8.557841
7.237
1.182512
flags = filters.Items() if self._status: flags.add_flags(self._status) if self._code_review is not None: flags.add_flags("code-review %s" % self._code_review) if self._verified is not None: flags.add_flags("verified %s" % self._verified) ...
def commit(self, message=None)
Executes the command :params message: The message to use as a comment for this action.
4.594922
4.613954
0.995875
try: bits = token.split_contents() tag_name, macro_name, arguments = bits[0], bits[1], bits[2:] except IndexError: raise template.TemplateSyntaxError( "'{0}' tag requires at least one argument (macro name)".format( token.contents.split()[0])) # use r...
def do_macro(parser, token)
the function taking the parsed tag and returning a DefineMacroNode object.
3.670961
3.629583
1.0114
try: tag_name, filename = token.split_contents() except ValueError: raise template.TemplateSyntaxError( "'{0}' tag requires exactly one argument (filename)".format( token.contents.split()[0])) if filename[0] in ('"', "'") and filename[-1] == filename[0]: ...
def do_loadmacros(parser, token)
The function taking a parsed tag and returning a LoadMacrosNode object, while also loading the macros into the page.
3.42379
3.335043
1.026611
try: bits = token.split_contents() tag_name, macro_name, values = bits[0], bits[1], bits[2:] except IndexError: raise template.TemplateSyntaxError( "{0} tag requires at least one argument (macro name)".format( token.contents.split()[0])) args = [] ...
def parse_macro_params(token)
Common parsing logic for both use_macro and macro_block
3.197557
3.189187
1.002625
tag_name, macro_name, args, kwargs = parse_macro_params(token) try: macro = parser._macros[macro_name] except (AttributeError, KeyError): raise template.TemplateSyntaxError( "Macro '{0}' is not defined previously to the {1} tag".format( macro_name, tag_name))...
def do_usemacro(parser, token)
The function taking a parsed template tag and returning a UseMacroNode.
3.48524
3.694788
0.943286
tag_name, macro_name, args, kwargs = parse_macro_params(token) # could add extra validation on the macro_name tag # here, but probably don't need to since we're checking # if there's a macro by that name anyway. try: # see if the macro is in the context. macro = parser._macros[m...
def do_macro_block(parser, token)
Function taking parsed template tag to a MacroBlockNode.
4.617342
4.622012
0.99899
# macro_arg takes no arguments, so we don't # need to split the token/do validation. nodelist = parser.parse(('endmacro_arg',)) parser.delete_first_token() # simply save the contents to a MacroArgNode. return MacroArgNode(nodelist)
def do_macro_arg(parser, token)
Function taking a parsed template tag to a MacroArgNode.
6.218577
6.219105
0.999915
try: tag_name, keyword = token.split_contents() except ValueError: raise template.TemplateSyntaxError( "{0} tag requires exactly one argument, a keyword".format( token.contents.split()[0])) # add some validation of the keyword argument here. nodelist = p...
def do_macro_kwarg(parser, token)
Function taking a parsed template tag to a MacroKwargNode.
2.522951
2.60013
0.970318
methods = ['get'] if (methods is None) else methods def decorator(func): func.bind_to_methods = methods func.detail = True func.kwargs = kwargs return func return decorator
def detail_route(methods=None, **kwargs)
Used to mark a method on a ViewSet that should be routed for detail requests. Usage:: class UserViewSet(ModelCRUDViewSet): model = User schema = UserSchema @detail_route(methods=['post'], url_path='lock-user') def lock_user(request, id): ......
3.822407
9.044782
0.422609
methods = ['get'] if (methods is None) else methods def decorator(func): func.bind_to_methods = methods func.detail = False func.kwargs = kwargs return func return decorator
def list_route(methods=None, **kwargs)
Used to mark a method on a ViewSet that should be routed for list requests. Usage:: class UserViewSet(ModelCRUDViewSet): model = User schema = UserSchema @list_route(methods=['get'], url_path='active-users') def active_users(request, *args, **kwargs): ...
4.724337
8.342068
0.566327
try: n = self.df[field].isnull().sum() except KeyError: self.warning("Can not find column", field) return except Exception as e: self.err(e, "Can not count nulls") return self.ok("Found", n, "nulls in column", field)
def count_nulls(self, field)
Count the number of null values in a column
3.744973
3.69857
1.012546
try: num = len(self.df.index) except Exception as e: self.err(e, "Can not count data") return self.ok("Found", num, "rows in the dataframe")
def count(self)
Counts the number of rows of the main dataframe
6.140582
5.494977
1.11749
try: num = len(self.df.index) except Exception as e: self.err(e, "Can not count data") return return num
def count_(self)
Returns the number of rows of the main dataframe
6.163986
5.356804
1.150683
try: df2 = self.df[[field]] vals = where(df2.applymap(lambda x: x == '')) num = len(vals[0]) except Exception as e: self.err(e, "Can not count empty values") return self.ok("Found", num, "empty rows in column " + field)
def count_empty(self, field)
List of empty row indices
5.756467
5.425262
1.061049
try: num = self.df[field].nunique() except Exception as e: self.err(e, "Can not count unique values") return self.ok("Found", num, "unique values in column", field)
def count_unique_(self, field)
Return the number of unique values in a column
4.708086
4.62857
1.01718
response = self.request(E.createCustomerRequest( E.companyName(company_name), E.vat(vat), E.name( E.initials(name.initials), E.firstName(name.first_name), E.prefix(name.prefix or ''), E.lastName(name.la...
def create_customer(self, name, gender, address, phone, email, vat=None, fax=None, company_name=None, additional_data=None, extension_additional_data=None)
Create a customer
2.316491
2.383296
0.97197
self.request(E.deleteCustomerRequest(E.handle(handle))) return True
def delete_customer(self, handle)
Delete a customer.
19.158854
17.404392
1.100806
self.request(E.modifyCustomerRequest( E.handle(handle), E.vat(vat or ''), _get_phone_xml('phone', phone), _get_phone_xml('fax', fax), E.address( E.street(address.street), E.number(address.number), ...
def modify_customer(self, handle, address, phone, email=None, vat=None, fax=None, company_name=None, additional_data=None, extension_additional_data=None)
Modify a customer.
2.483985
2.530285
0.981702
response = self.request(E.searchCustomerRequest( E.limit(limit), E.offset(offset), E.emailPattern(email_pattern or ''), E.lastNamePattern(last_name_pattern or ''), E.companyNamePattern(company_name_pattern or ''), E.withAdditional...
def search_customer(self, limit=100, offset=0, email_pattern=None, last_name_pattern=None, company_name_pattern=None, with_additional_data=False)
Search the list of customers.
2.542593
2.688155
0.94585
response = self.request(E.retrieveCustomerRequest( E.handle(handle), E.withAdditionalData(int(with_additional_data)), )) return response.as_model(Customer)
def retrieve_customer(self, handle, with_additional_data=False)
Retrieve information of an existing customer.
5.563652
5.684573
0.978728
parts = path.split('.') return getattr(importlib.import_module('.'.join(parts[0:-1])), parts[-1])
def import_namespaced_class(path)
Pass in a string in the format of foo.Bar, foo.bar.Baz, foo.bar.baz.Qux and it will return a handle to the class :param str path: The object path :rtype: class
2.659244
3.635031
0.73156
if is_frozen(): # find modules in library.zip filename zipname = os.path.dirname(os.path.dirname(__file__)) parentmodule = os.path.basename(os.path.dirname(__file__)) with zipfile.ZipFile(zipname, 'r') as f: prefix = "%s/%s/" % (parentmodule, folder) modn...
def get_modules(folder)
Find all valid modules in the given folder which must be in in the same directory as this loader.py module. A valid module has a .py extension, and is importable. @return: all loaded valid modules @rtype: iterator of module
3.188002
3.232786
0.986147
for fname in os.listdir(folder): if fname.endswith('.py') and not fname.startswith('_'): yield fname[:-3]
def get_importable_modules(folder)
Find all module files in the given folder that end with '.py' and don't start with an underscore. @return module names @rtype: iterator of string
2.637904
2.649534
0.995611
for module in modules: for plugin in get_module_plugins(module, classobj): yield plugin
def get_plugins(modules, classobj)
Find all class objects in all modules. @param modules: the modules to search @ptype modules: iterator of modules @return: found classes @rytpe: iterator of class objects
3.294985
4.779406
0.689413
try: names = module.__all__ except AttributeError: names = [x for x in vars(module) if not x.startswith('_')] for name in names: try: obj = getattr(module, name) except AttributeError: continue try: if issubclass(obj, classobj)...
def get_module_plugins(module, classobj)
Return all subclasses of a class in the module. If the module defines __all__, only those entries will be searched, otherwise all objects not starting with '_' will be searched.
2.02599
1.846275
1.097339
if chart_obj is None: if self.chart_obj is None: self.err( self.stack, "No chart object set: please provide one in parameters") return chart_obj = self.chart_obj try: seaborn_chart = None...
def stack(self, slug, chart_obj=None, title=None)
Get the html for a chart and store it
3.634425
3.59051
1.012231
if folderpath is None: if self.report_path is None: self.err( "Please set the report_path parameter or pass a path in arguments") return folderpath = self.report_path else: self.report_path = folderpath ...
def to_file(self, slug, folderpath=None, header=None, footer=None)
Writes the html report to a file from the report stack
3.457938
3.334987
1.036867
if len(self.reports) == 0: self.warning( "No charts to save. Use stack to add charts for saving") return if folderpath is None: if self.report_path is None and "seaborn" \ not in self.report_engines: self.er...
def to_files(self, folderpath=None)
Writes the html report to one file per report
4.267005
4.063685
1.050033
if chart_obj is None: if self.chart_obj is None: self.err( "No chart object registered, please provide " "one in parameters" ) return chart_obj = self.chart_obj try: if se...
def get_html(self, chart_obj=None, slug=None)
Get the html and script tag for a chart
2.514875
2.496536
1.007346
if header is None: html = self.header() else: html = header return html
def _get_header(self, header)
Gets the html header
6.263055
4.390334
1.426556
if footer is None: html = self.footer() else: html = footer return html
def _get_footer(self, footer)
Gets the html footer
5.731889
4.413879
1.298606
# check directories if not os.path.isdir(folderpath): try: os.makedirs(folderpath) self.info("Creating directory " + folderpath) except Exception as e: self.err(e) return # construct file path ...
def _write_file(self, slug, folderpath, html)
Writes a chart's html to a file
2.789078
2.783226
1.002103
html = if "bokeh" in self.report_engines: html += self.bokeh_header_() if "altair" in self.report_engines: html += self.altair_header_() if "chartjs" in self.report_engines: html += self.chartjs_header_() html += return html
def _header(self)
Default html header
4.074774
3.501531
1.163712
num = len(txt) ticks = "=" * num print(ticks) print(txt) print(ticks)
def title(self, txt)
Prints a title for pipelines
6.338637
5.732944
1.105651
num = len(txt) ticks = "-" * num print(txt) print(ticks)
def subtitle(self, txt)
Prints a subtitle for pipelines
9.27486
8.52158
1.088397
session = requests.session() page = urlopen(UPDATE_URL, session) version, url = None, None for line in page.text.splitlines(): if line.startswith(VERSION_TAG): version = line.split(':', 1)[1].strip() elif line.startswith(URL_TAG): url = line.split(':', 1)[1]....
def get_online_version ()
Download update info and parse it.
2.897913
2.769793
1.046256
return application.Application(self.settings, self.namespace.routes, self.port)
def create_application(self)
Create and return a new instance of tinman.application.Application
21.09844
13.302711
1.586026
return {config.NO_KEEP_ALIVE: self.namespace.server.get(config.NO_KEEP_ALIVE, False), config.SSL_OPTIONS: self.ssl_options, config.XHEADERS: self.namespace.server.get(config.XHEADERS, False)}
def http_config(self)
Return a dictionary of HTTPServer arguments using the default values as specified in the HTTPServer class docstrings if no values are specified. :param dict config: The HTTPServer specific section of the config :rtype: dict
5.504877
5.19369
1.059916
LOGGER.info('Stopping HTTP Server and IOLoop') self.http_server.stop() self.ioloop.stop()
def on_sigabrt(self, signal_unused, frame_unused)
Stop the HTTP Server and IO Loop, shutting down the process :param int signal_unused: Unused signal number :param frame frame_unused: Unused frame the signal was caught in
6.678831
4.07832
1.637643
# Update HTTP configuration for setting in self.http_config: if getattr(self.http_server, setting) != self.http_config[setting]: LOGGER.debug('Changing HTTPServer %s setting', setting) setattr(self.http_server, setting, self.http_config[setting]) ...
def on_sighup(self, signal_unused, frame_unused)
Reload the configuration :param int signal_unused: Unused signal number :param frame frame_unused: Unused frame the signal was caught in
3.469223
3.457815
1.003299
LOGGER.debug('Initializing process') # Setup logging self.logging_config = self.setup_logging() # Register the signal handlers self.setup_signal_handlers() # Create the application instance try: self.app = self.create_application() ...
def run(self)
Called when the process has started :param int port: The HTTP Server port
4.03464
3.896415
1.035475
LOGGER.debug('Registering signal handlers') signal.signal(signal.SIGABRT, self.on_sigabrt)
def setup_signal_handlers(self)
Called when a child process is spawned to register the signal handlers
4.505303
4.386001
1.027201
opts = self.namespace.server.get(config.SSL_OPTIONS) or dict() if config.CERT_REQS in opts: opts[config.CERT_REQS] = \ self.CERT_REQUIREMENTS[opts[config.CERT_REQS]] return opts or None
def ssl_options(self)
Check the config to see if SSL configuration options have been passed and replace none, option, and required with the correct values in the certreqs attribute if it is specified. :rtype: dict
5.996246
5.446838
1.100867
# Start the HTTP Server LOGGER.info("Starting Tornado v%s HTTPServer on port %i Args: %r", tornado_version, port, args) http_server = httpserver.HTTPServer(self.app, **args) http_server.bind(port, family=socket.AF_INET) http_server.start(1) re...
def start_http_server(self, port, args)
Start the HTTPServer :param int port: The port to run the HTTPServer on :param dict args: Dictionary of arguments for HTTPServer :rtype: tornado.httpserver.HTTPServer
3.442843
3.437753
1.001481
print("Parsing", url, file=sys.stderr) try: data = getPageContent(url, session) except IOError as msg: print("ERROR:", msg, file=sys.stderr) return for match in url_matcher.finditer(data): comicurl = match.group(1) name = format_name(comicurl.split('.', 1)[0]...
def handle_url(url, session, res)
Parse one search result page.
3.238267
3.203538
1.010841
# store info in a dictionary {name -> shortname} res = {} session = requests.Session() baseUrl = 'http://comicfury.com/search.php?search=1&webcomics=Search+for+webcomics&query=&worder=5&asc=1&incvi=1&incse=1&incnu=1&incla=1&all_ge=1&all_st=1&all_la=1&page=' pages = 382 for i in range(1, pag...
def get_results()
Parse all search result pages.
8.426646
8.163913
1.032182
min_comics, filename = args min_comics = int(min_comics) with codecs.open(filename, 'a', 'utf-8') as fp: for name, entry in sorted(load_result(json_file).items()): if name in exclude_comics: continue url, num, active = entry if num < min_comic...
def print_results(args)
Print all comics that have at least the given number of minimum comic strips.
5.369441
4.940657
1.086787
from ..models import Title qs = Title.objects.filter(slug=slug, language=language) if article.pk: qs = qs.exclude(Q(language=language) & Q(article=article)) qs = qs.exclude(article__publisher_public=article) if qs.count(): return False return True
def is_valid_article_slug(article, language, slug)
Validates given slug depending on settings.
3.828953
3.753564
1.020084
return np.product(array.shape)*np.dtype(array.dtype).itemsize
def array_bytes(array)
Estimates the memory of the supplied array in bytes
5.112932
3.988595
1.281888
arrays = ({ k : AttrDict(**a) for k, a in arrays.iteritems() } if copy else arrays) for n, a in arrays.iteritems(): a.shape = tuple(dims[v].extent_size if isinstance(v, str) else v for v in a.shape) return arrays
def reify_arrays(arrays, dims, copy=True)
Reify arrays, given the supplied dimensions. If copy is True, returns a copy of arrays else performs this inplace.
5.498098
7.008995
0.784435
ctx.obj = Wio() cur_dir = os.path.abspath(os.path.expanduser("~/.wio")) if not os.path.exists(cur_dir): text = {"email":"", "token":""} os.mkdir(cur_dir) open("%s/config.json"%cur_dir,"w").write(json.dumps(text)) db_file_path = '%s/config.json' % cur_dir config = json.lo...
def cli(ctx)
\b Welcome to the Wio Command line utility! https://github.com/Seeed-Studio/wio-cli For more information Run: wio <command_name> --help
3.287175
3.221134
1.020503
for permission in self.get_permissions(): if not permission.has_permission(request, self): self.permission_denied(request, message=getattr(permission, 'message', None))
def check_permissions(self, request)
Check if the request should be permitted. Raises an appropriate exception if the request is not permitted. :param request: Pyramid Request object.
2.820464
4.017654
0.702018
for permission in self.get_permissions(): if not permission.has_object_permission(request, self, obj): self.permission_denied(request, message=getattr(permission, 'message', None))
def check_object_permissions(self, request, obj)
Check if the request should be permitted for a given object. Raises an appropriate exception if the request is not permitted. :param request: Pyramid Request object. :param obj: The SQLAlchemy model instance that permissions will be evaluated against.
2.430132
3.249891
0.747758
response = Response() response.headers['Allow'] = ', '.join(self.allowed_methods) response.headers['Content-Length'] = '0' return response
def options(self, request, *args, **kwargs)
Handles responding to requests for the OPTIONS HTTP verb.
3.797814
2.594179
1.463975
return url in ( self.stripUrl % '130217', # video self.stripUrl % '130218', # video self.stripUrl % '130226', # video self.stripUrl % '130424', # video )
def shouldSkipUrl(self, url, data)
Skip pages without images.
3.790636
3.711105
1.021431
info = '%s_%s' % (self.model._meta.app_label, self.model._meta.model_name) def pat(regex, fn): return url(regex, self.admin_site.admin_view(fn), name='%s_%s' % (info, fn.__name__)) url_patterns = [ pat(r'^([0-9]+)/delete-translation/$', self.delete_translation)...
def get_urls(self)
Get the admin urls
2.320255
2.13977
1.084348
language = get_language_from_request(request) form = super(ArticleAdmin, self).get_form( request, obj, form=(obj and ArticleForm or ArticleCreateForm), **kwargs ) # get_form method operates by overriding initial fields value which # ma...
def get_form(self, request, obj=None, **kwargs)
Get ArticleForm for the Article model and modify its fields depending on the request.
3.847905
3.896367
0.987562
article = get_object_or_404(self.model, pk=article_id) if not article.has_publish_permission(request): return HttpResponseForbidden(force_text(_('You do not have permission to unpublish this article'))) if not article.publisher_public_id: return HttpResponseForbi...
def unpublish(self, request, article_id, language)
Publish or unpublish a language of a article
2.023568
2.048933
0.98762
article = get_object_or_404(self.model, id=object_id) attrs = '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON') attrs += '&language=' + language with force_language(language): url = article.get_absolute_url(language) + attrs return HttpResponseRedirect(url)
def preview_article(self, request, object_id, language)
Redirecting preview function based on draft_id
2.882582
2.883618
0.999641
try: cli = DataFrameClient(url, port, user, pwd, db) self.influx_cli = cli except Exception as e: self.err(e, self.influx_init, "Can not initialize Influxdb database")
def influx_init(self, url, port, user, pwd, db)
Initialize an Influxdb database client
5.701451
5.141541
1.108899
if self.influx_cli is None: self.err( self.influx_query_, "No database connected. Please initialize a connection") return try: return self.influx_cli.query(q) except Exception as e: self.err(e, self.influx_q...
def influx_query_(self, q)
Runs an Influx db query
4.661715
4.693981
0.993126
try: q = "select count(*) from " + measurement self.start("Querying: count ...") datalen = self.influx_cli.query(q) self.end("Finished querying") numrows = int(datalen[measurement][datalen[measurement].keys()[0]]) return numrows ...
def influx_count_(self, measurement)
Count the number of rows for a measurement
6.23774
6.006451
1.038507
if self.autoprint is True: print("Processing data from InfluxDb to csv") try: q = "select count(*) from " + measurement numrows = self.influx_cli.query(q)[measurement].iloc[0, 0] self.info("Processing", str(numrows), "datapoi...
def influx_to_csv(self, measurement, batch_size=5000)
Batch export data from an Influxdb measurement to csv
3.433196
3.36813
1.019318
if not comic: raise ValueError("empty comic name") candidates = [] cname = comic.lower() for scraperclass in get_scraperclasses(): lname = scraperclass.getName().lower() if lname == cname: # perfect match if not multiple_allowed: retur...
def find_scraperclasses(comic, multiple_allowed=False)
Get a list comic scraper classes. Can return more than one entries if multiple_allowed is True, else it raises a ValueError if multiple modules match. The match is a case insensitive substring search.
2.327156
2.313576
1.00587
global _scraperclasses if _scraperclasses is None: out.debug(u"Loading comic modules...") modules = loader.get_modules('plugins') plugins = loader.get_plugins(modules, Scraper) _scraperclasses = list(plugins) check_scrapers() out.debug(u"... %d modules loaded...
def get_scraperclasses()
Find all comic scraper classes in the plugins directory. The result is cached. @return: list of Scraper classes @rtype: list of Scraper
4.682578
4.117745
1.13717
d = {} for scraperclass in _scraperclasses: name = scraperclass.getName().lower() if name in d: name1 = scraperclass.getName() name2 = d[name].getName() raise ValueError('duplicate scrapers %s and %s found' % (name1, name2)) d[name] = scraperclass
def check_scrapers()
Check for duplicate scraper class names.
3.132528
2.635013
1.188809
imageUrls = self.fetchUrls(url, data, self.imageSearch) # map modifier function on image URLs imageUrls = [self.imageUrlModifier(x, data) for x in imageUrls] # remove duplicate URLs imageUrls = set(imageUrls) if len(imageUrls) > 1 and not self.multipleImagesPerSt...
def getComicStrip(self, url, data)
Get comic strip downloader for given URL and data.
4.00864
3.971903
1.009249
if maxstrips: word = u"strip" if maxstrips == 1 else "strips" msg = u'Retrieving %d %s' % (maxstrips, word) else: msg = u'Retrieving all strips' if self.indexes: if len(self.indexes) == 1: msg += u" for index %s" % self.ind...
def getStrips(self, maxstrips=None)
Get comic strips.
3.970949
3.754967
1.057519
self.hitFirstStripUrl = False seen_urls = set() while url: out.info(u'Get strip URL %s' % url, level=1) data = self.getPage(url) if self.shouldSkipUrl(url, data): out.info(u'Skipping URL %s' % url) self.skippedUrls.add(...
def getStripsFor(self, url, maxstrips)
Get comic strips for an URL. If maxstrips is a positive number, stop after retrieving the given number of strips.
3.745994
3.607789
1.038307
prevUrl = None if self.prevSearch: try: prevUrl = self.fetchUrl(url, data, self.prevSearch) except ValueError as msg: # assume there is no previous URL, but print a warning out.warn(u"%s Assuming no previous comic strips ex...
def getPrevUrl(self, url, data)
Find previous URL.
6.773088
6.513531
1.039849
url = configuration.VoteUrl + 'count/' uid = get_system_uid() data = {"name": cls.getName().replace('/', '_'), "uid": uid} page = urlopen(url, cls.session, data=data) return page.text
def vote(cls)
Cast a public vote for this comic.
12.509776
11.01377
1.135831
dirname = getDirname(self.getName()) return os.path.join(basepath, dirname, "complete.txt")
def getCompleteFile(self, basepath)
Get filename indicating all comics are downloaded.
6.036068
5.392595
1.119325
if self.endOfLife: filename = self.getCompleteFile(basepath) if not os.path.exists(filename): with open(filename, 'w') as f: f.write('All comics should be downloaded here.')
def setComplete(self, basepath)
Set complete flag for this comic, ie. all comics are downloaded.
5.473231
4.285808
1.277059
lang = 'Unknown (%s)' % cls.lang if pycountry is None: if cls.lang in languages.Languages: lang = languages.Languages[cls.lang] else: try: lang = pycountry.languages.get(alpha2 = cls.lang).name except KeyError: ...
def language(cls)
Return language of the comic as a human-readable language name instead of a 2-character ISO639-1 code.
2.841833
2.732037
1.040189
searchUrls = [] searches = makeSequence(urlSearch) for search in searches: for match in search.finditer(data[0]): searchUrl = match.group(1) if not searchUrl: raise ValueError("Pattern %s matched empty URL at %s." % (search...
def fetchUrls(cls, url, data, urlSearch)
Search all entries for given URL pattern(s) in a HTML page.
4.525865
4.363699
1.037162
if textSearch: match = textSearch.search(data[0]) if match: text = match.group(1) out.debug(u'matched text %r with pattern %s' % (text, textSearch.pattern)) return unescape(text).strip() if optional: ret...
def fetchText(cls, url, data, textSearch, optional)
Search text entry for given text pattern in a HTML page.
3.846351
3.744271
1.027263
searchUrls = [] if cls.css: searchFun = data.cssselect else: searchFun = data.xpath searches = makeSequence(urlSearch) for search in searches: for match in searchFun(search): try: for attrib in html_...
def fetchUrls(cls, url, data, urlSearch)
Search all entries for given XPath in a HTML page.
5.891313
5.675739
1.037982
if cls.css: searchFun = data.cssselect else: searchFun = data.xpath if textSearch: text = '' for match in searchFun(textSearch): try: text += ' ' + match.text_content() except AttributeEr...
def fetchText(cls, url, data, textSearch, optional)
Search text entry for given text XPath in a HTML page.
3.499631
3.34086
1.047524
try: df = self._resample_("sum", time_period, num_col, dateindex) self.df = df if df is None: self.err("Can not sum data") except Exceptions as e: self.err(e, "Can not sum data")
def rsum(self, time_period: str, num_col: str="Number", dateindex: str=None)
Resample and add a sum the main dataframe to a time period :param time_period: unit + period: periods are Y, M, D, H, Min, S :param time_period: str :param num_col: number of the new column, defaults to "Number" :param num_col: str, optional :param dateindex: column name to use as date index, defaults to Non...
5.310226
5.723681
0.927764
parser = argparse.ArgumentParser( description=( 'AntiNex - ' 'Get Token from Splunk')) parser.add_argument( '-u', help='username', required=False, dest='user') parser.add_argument( '-p', ...
def run_main()
run_main Get Splunk Service Token
2.602856
2.552341
1.019792
try: from PIL import Image except ImportError: return None img = Image.open(filename) width, height = img.size if width > maxsize[0] or height > maxsize[1]: img.thumbnail(maxsize) out.info("Downscaled display size from %s to %s" % ((width, height), img.size)) ...
def getDimensionForImage(filename, maxsize)
Return scaled image size in (width, height) format. The scaling preserves the aspect ratio. If PIL is not found returns None.
2.948705
2.76775
1.06538
if not issubclass(clazz, EventHandler): raise ValueError("%s must be subclassed from %s" % (clazz, EventHandler)) _handler_classes[clazz.name] = clazz
def addHandlerClass(clazz)
Register handler class.
3.226004
3.377251
0.955216
if basepath is None: basepath = '.' _handlers.append(_handler_classes[name](basepath, baseurl, allowDownscale))
def addHandler(name, basepath=None, baseurl=None, allowDownscale=False)
Add an event handler with given name.
4.450227
4.793038
0.928477
'''Return a file: URL that probably points to the basedir. This is used as a halfway sane default when the base URL is not provided; not perfect, but should work in most cases.''' components = util.splitpath(os.path.abspath(self.basepath)) url = '/'.join([url_quote(component, ''...
def getBaseUrl(self)
Return a file: URL that probably points to the basedir. This is used as a halfway sane default when the base URL is not provided; not perfect, but should work in most cases.
10.21174
2.807935
3.636744
components = util.splitpath(util.getRelativePath(self.basepath, filename)) url = '/'.join([url_quote(component, '') for component in components]) return self.baseurl + url
def getUrlFromFilename(self, filename)
Construct URL from filename.
7.20399
6.343047
1.13573
return os.path.abspath(os.path.join(self.basepath, 'dailydose.rss'))
def getFilename(self)
Return RSS filename.
13.710336
8.235983
1.664687
today = time.time() yesterday = today - 86400 today = time.localtime(today) yesterday = time.localtime(yesterday) link = configuration.Url self.rssfn = self.getFilename() if os.path.exists(self.rssfn): self.newfile = False self....
def start(self)
Log start event.
5.116757
4.928483
1.038201
imageUrl = self.getUrlFromFilename(filename) size = None if self.allowdownscale: size = getDimensionForImage(filename, MaxImageSize) title = '%s - %s' % (comic.name, os.path.basename(filename)) pageUrl = comic.referrer description = '<img src="%s"' % ...
def comicDownloaded(self, comic, filename, text=None)
Write RSS entry for downloaded comic.
4.018736
3.877543
1.036413
fn = time.strftime('comics-%Y%m%d', date) fn = os.path.join(self.basepath, 'html', fn + ".html") fn = os.path.abspath(fn) return fn
def fnFromDate(self, date)
Get filename from date.
4.853553
4.24409
1.143603
today = time.time() yesterday = today - 86400 tomorrow = today + 86400 today = time.localtime(today) yesterday = time.localtime(yesterday) tomorrow = time.localtime(tomorrow) fn = self.fnFromDate(today) if os.path.exists(fn): out.warn...
def start(self)
Start HTML output.
3.343598
3.246232
1.029994
if self.lastComic != comic.name: self.newComic(comic) size = None if self.allowdownscale: size = getDimensionForImage(filename, MaxImageSize) imageUrl = self.getUrlFromFilename(filename) pageUrl = comic.referrer if pageUrl != self.lastUrl:...
def comicDownloaded(self, comic, filename, text=None)
Write HTML entry for downloaded comic.
3.293329
3.231449
1.019149
if self.lastUrl is not None: self.html.write(u'</li>\n') if self.lastComic is not None: self.html.write(u'</ul>\n') self.html.write(u'<li>%s</li>\n' % comic.name) self.html.write(u'<ul>\n')
def newComic(self, comic)
Start new comic list in HTML.
2.636442
2.366088
1.114262
if self.lastUrl is not None: self.html.write(u'</li>\n') if self.lastComic is not None: self.html.write(u'</ul>\n') self.html.write(u'</ul>\n') self.addNavLinks() self.html.close()
def end(self)
End HTML output.
3.781233
3.412147
1.108168
fn = os.path.join(self.basepath, comic, 'dosage.json') fn = os.path.abspath(fn) return fn
def jsonFn(self, comic)
Get filename for the JSON file for a comic.
4.695962
4.307534
1.090174
if comic not in self.data: if os.path.exists(self.jsonFn(comic)): with codecs.open(self.jsonFn(comic), 'r', self.encoding) as f: self.data[comic] = json.load(f) else: self.data[comic] = {'pages':{}} return self.data[com...
def getComicData(self, comic)
Return dictionary with comic info.
2.421315
2.38863
1.013684
comicData = self.getComicData(comic) if url not in comicData['pages']: comicData['pages'][url] = {'images':{}} return comicData['pages'][url]
def getPageInfo(self, comic, url)
Return dictionary with comic page info.
2.878107
2.713664
1.060598
pageInfo = self.getPageInfo(comic.name, comic.referrer) pageInfo['images'][comic.url] = os.path.basename(filename)
def comicDownloaded(self, comic, filename, text=None)
Add URL-to-filename mapping into JSON.
7.314939
6.23854
1.17254
pageInfo = self.getPageInfo(comic, url) pageInfo['prev'] = prevUrl
def comicPageLink(self, comic, url, prevUrl)
Write previous link into JSON.
4.831079
3.975929
1.215082
for comic in self.data: with codecs.open(self.jsonFn(comic), 'w', self.encoding) as f: json.dump(self.data[comic], f, indent=2, separators=(',', ': '), sort_keys=True)
def end(self)
Write all JSON data to files.
3.993536
3.136524
1.273236