code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
return bitcoin.core.script.CScript( bytes([bitcoin.core.script.OP_RETURN]) + bitcoin.core.script.CScriptOp.encode_op_pushdata(data))
def build_script(data)
Creates an output script containing an OP_RETURN and a PUSHDATA. :param bytes data: The content of the PUSHDATA. :return: The final script. :rtype: CScript
6.090275
5.065974
1.202192
result = 0 shift = 0 while True: character = data.read(1) if len(character) == 0: raise bitcoin.core.SerializationTruncationError('Invalid LEB128 integer') b = ord(character) result |= (b & 0x7f) << shift if b...
def leb128_decode(data)
Decodes a LEB128-encoded unsigned integer. :param BufferedIOBase data: The buffer containing the LEB128-encoded integer to decode. :return: The decoded integer. :rtype: int
3.065512
3.026133
1.013013
if value == 0: return b'\x00' result = [] while value != 0: byte = value & 0x7f value >>= 7 if value != 0: byte |= 0x80 result.append(byte) return bytes(result)
def leb128_encode(value)
Encodes an integer using LEB128. :param int value: The value to encode. :return: The LEB128-encoded integer. :rtype: bytes
1.971956
2.025666
0.973485
encoded = json.dumps(packet) self.ws.send(encoded)
def _send_packet(self, packet)
Sends <packet> (<dict>) to https://hack.chat.
8.048582
6.411378
1.255359
while True: result = json.loads(self.ws.recv()) if result["cmd"] == "chat" and not result["nick"] == self.nick: for handler in list(self.on_message): handler(self, result["text"], result["nick"]) elif result["cmd"] == "onlineAdd": ...
def run(self)
Sends data to the callback functions.
2.18176
2.185483
0.998296
session['openid'] = resp.identity_url user = User.get_collection().find_one({'openid':resp.identity_url}) if user is not None: flash(u'Successfully signed in') g.user = user return redirect(oid.get_next_url()) return redirect(url_for('create_profile', next=oid.get_next_url()...
def create_or_login(resp)
This is called when login with OpenID succeeded and it's not necessary to figure out if this is the users's first login or not. This function has to redirect otherwise the user will be presented with a terrible URL which we certainly don't want.
3.702486
3.463902
1.068877
if g.user is not None or 'openid' not in session: return redirect(url_for('index')) if request.method == 'POST': name = request.form['name'] email = request.form['email'] if not name: flash(u'Error: you have to provide a name') elif '@' not in email: ...
def create_profile()
If this is the user's first login, the create_or_login function will redirect here so that the user can set up his profile.
2.769311
2.770985
0.999396
if g.user is None: abort(401) form = dict(name=g.user.name, email=g.user.email) if request.method == 'POST': if 'delete' in request.form: User.get_collection().remove(g.user) session['openid'] = None flash(u'Profile deleted') return redire...
def edit_profile()
Updates a profile
2.061129
2.078638
0.991577
''' shift from ASM to DISASM ''' op_modes = config.get_op_modes() if arg in op_modes: op_mode = op_modes[arg] op_mode.cmdloop() else: print("Error: unknown operational mode, please use 'help setmode'.")
def do_setmode(self, arg)
shift from ASM to DISASM
8.475983
5.878451
1.441873
if not string: string = name self.symbols[name] = sympy.Symbol(string)
def add_symbol(self, name, string=None)
Add a symbol with key `name` to `scipy_data_fitting.Model.symbols`. Optionally, specify an alternative `string` to pass to [`sympy.Symbol`][1], otherwise `name` is used. [1]: http://docs.sympy.org/dev/modules/core.html#id4
4.713981
3.953477
1.192363
# When expression is a string, # get the expressions from self.expressions. if isinstance(expression, str): expression = self.expressions[expression] # Allow for replacements to be empty. if not replacements: return expression # Allow re...
def replace(self, expression, replacements)
All purpose method to reduce an expression by applying successive replacement rules. `expression` is either a SymPy expression or a key in `scipy_data_fitting.Model.expressions`. `replacements` can be any of the following, or a list of any combination of the following: ...
2.63157
2.656126
0.990755
if isinstance(expression, str): expression = self.expressions[expression] if hasattr(symbols, '__iter__'): variables = [] for s in symbols: if isinstance(s, str): variables.append(self.symbol(s)) else: ...
def lambdify(self, expression, symbols, **kwargs)
Converts a SymPy expression into a function using [`sympy.lambdify`][1]. `expression` can be a SymPy expression or the name of an expression in `scipy_data_fitting.Model.expressions`. `symbols` can be any of the following, or a list of any combination of the following: - A Sym...
2.151838
2.11017
1.019746
try: self.current_token = next(self.tokens) except StopIteration: raise MissingTokensError("Unexpected end of token stream at %d." % self.current_pos) self.current_pos += 1
def _forward(self)
Advance to the next token. Internal methods, updates: - self.current_token - self.current_pos Raises: MissingTokensError: when trying to advance beyond the end of the token flow.
5.734296
3.067621
1.869298
if expect_class and not isinstance(self.current_token, expect_class): raise InvalidTokenError("Unexpected token at %d: got %r, expected %s" % ( self.current_pos, self.current_token, expect_class.__name__)) current_token = self.current_token self._forward() ...
def consume(self, expect_class=None)
Retrieve the current token, then advance the parser. If an expected class is provided, it will assert that the current token matches that class (is an instance). Note that when calling a token's nud() or led() functions, the "current" token is the token following the token whose method...
3.127206
3.136014
0.997191
prev_token = self.consume() # Retrieve the value from the previous token situated at the # leftmost point in the expression left = prev_token.nud(context=self) while rbp < self.current_token.lbp: # Read incoming tokens with a higher 'left binding power'. ...
def expression(self, rbp=0)
Extract an expression from the flow of tokens. Args: rbp (int): the "right binding power" of the previous token. This represents the (right) precedence of the previous token, and will be compared to the (left) precedence of next tokens. Returns: ...
7.554431
7.203548
1.04871
expr = self.expression() if not isinstance(self.current_token, EndToken): raise InvalidTokenError("Unconsumed trailing tokens.") return expr
def parse(self)
Parse the flow of tokens, and return their evaluation.
10.349322
7.85908
1.316862
if type(value) is str: if hasattr(scipy.constants, value): return getattr(scipy.constants, value) else: return scipy.constants.physical_constants[value][0] else: return value
def get_constant(value)
When `value` is a string, get the corresponding constant from [`scipy.constants`][1]. [1]: http://docs.scipy.org/doc/scipy/reference/constants.html
2.647789
2.369537
1.117429
key = self.get_cache_key(*args, **kwargs) logger.debug(key) return self.cache.get(key, default=Ellipsis)
def get_cached_value(self, *args, **kwargs)
:returns: The cached value or ``Ellipsis``
4.024621
3.42942
1.173558
key = self.get_cache_key(*args, **kwargs) logger.debug(key) return namedtuple('Settable', ['to'])(lambda value: self.cache.set(key, value))
def set_cached_value(self, *args, **kwargs)
Sets the cached value
6.051749
6.286561
0.962649
arguments = docopt.docopt(__doc__, version='Coil CMS v{0}'.format( coil.__version__)) if arguments['write_users']: sys.exit(write_users(arguments)) elif arguments['devserver']: sys.exit(devserver(arguments)) elif arguments['unlock']: sys.exit(unlock(arguments))
def main()
The main function.
4.660648
4.382165
1.063549
import coil.init u = coil.utils.ask("Redis URL", "redis://localhost:6379/0") return coil.init.write_users(u)
def write_users(arguments)
Write users to the DB.
10.150736
9.252059
1.097133
import coil.web if coil.web.app: port = int(arguments['--port']) url = 'http://localhost:{0}/'.format(port) coil.web.configure_url(url) coil.web.app.config['DEBUG'] = True if arguments['--browser']: webbrowser.open(url) coil.web.app.logger.info(...
def devserver(arguments)
Run a development server.
3.728087
3.796061
0.982094
import redis u = coil.utils.ask("Redis URL", "redis://localhost:6379/0") db = redis.StrictRedis.from_url(u) db.set('site:lock', 0) print("Database unlocked.") return 0
def unlock(arguments)
Unlock the database.
6.635622
6.02814
1.100774
lval = self.keyword(token_stream, token, {}) token = next(token_stream) if token[0] == 'OR': op = or_ token = next(token_stream) elif token[0] == 'TEXT' or token[0] == 'COLOR': op = lambda l, r: list(flatten([l, r])) elif token[0] == '...
def expr(self, token_stream, token)
Top level parsing function. An expression is <keyword> <OR> <expr> or <keyword> <SEP> <expr> or <keyword>
2.780244
3.220497
0.863297
if token[0] == 'TEXT' or token[0] == 'COLOR': return SearchKeyword(token[1], **operators) elif token[0] == 'COMPARISON': operators['comparison'] = token[1] elif token[0] == 'NOT': operators['boolean'] = 'not' else: if token[1] == N...
def keyword(self, token_stream, token, operators)
Lowest level parsing function. A keyword consists of zero or more prefix operators (NOT, or COMPARISON) followed by a TEXT, COLOR, or NUMBER block.
3.48441
3.149801
1.106232
token_stream = self.lexer.tokenize(text) return self.expr(token_stream, next(token_stream))
def parse(self, text)
Parse the given text, return a list of Keywords.
6.2546
5.708255
1.095711
if self.mime_type: # Supposed validated by the factory return self.mime_type for pattern, mime_type in self._extpattern_to_mime.items(): if fnmatch.fnmatch(self.filename, pattern): return mime_type
def mimeType(self)
The official MIME type for this document, guessed from the extensions of the :py:attr:`openxmllib.document.Document.filename` attribute, as opposed to the :py:attr:`openxmllib.document.Document.mime_type` attribute. :return: ``application/xxx`` for this file
6.578699
6.861874
0.958732
rval = {} if not content_type in self.content_types.listMetaContentTypes: # We fail silently return rval for tree in self.content_types.getTreesFor(self, content_type): for elt in tree.getroot().getchildren(): tag = elt.tag.split('}')[...
def _tagValuedProperties(self, content_type)
Document properties for property files having constructs like <ns:name>value</ns:name> :param content_type: ``contenttypes.CT_CORE_PROPS`` or ``contenttypes.CT_EXT_PROPS`` :return: mapping like {'property name': 'property value', ...}
5.540539
5.543566
0.999454
rval = {} if len(self.content_types.getPathsForContentType(contenttypes.CT_CUSTOM_PROPS)) == 0: # We may have no custom properties at all. return rval XPath = lxml.etree.XPath # Class shortcut properties_xpath = XPath('custom-properties:property', namespa...
def customProperties(self)
Document custom properties added by the document author. We canot convert the properties as indicated with the http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes namespace :return: mapping of metadata
5.924757
5.806625
1.020344
rval = {} rval.update(self.coreProperties) rval.update(self.extendedProperties) rval.update(self.customProperties) return rval
def allProperties(self)
Helper that merges core, extended and custom properties :return: mapping of all properties
3.687909
2.656307
1.38836
rels_pth = os.path.join(self._cache_dir, "_rels", ".rels") rels_xml = lxml.etree.parse(xmlFile(rels_pth, 'rb')) thumb_ns = ns_map["thumbnails"] thumb_elm_xpr = "relationships:Relationship[@Type='%s']" % thumb_ns rels_xpath = lxml.etree.XPath(thumb_elm_xpr, namespaces=ns_...
def documentCover(self)
Cover page image :return: (file extension, file object) tuple.
3.914914
3.920768
0.998507
text = set() for extractor in self._text_extractors: if extractor.content_type in self.content_types.overrides: for tree in self.content_types.getTreesFor(self, extractor.content_type): words = extractor.indexableText(tree) tex...
def indexableText(self, include_properties=True)
Words found in the various texts of the document. :param include_properties: Adds words from properties :return: Space separated words of the document.
4.679329
4.763594
0.982311
supported_patterns = cls._extpattern_to_mime.keys() for pattern in supported_patterns: if fnmatch.fnmatch(filename, pattern): return True return False
def canProcessFilename(cls, filename)
Check if we can process such file based on name :param filename: File name as 'mydoc.docx' :return: True if we can process such file
4.778144
6.171608
0.774214
self._tokens.append((token, re.compile(regexp)))
def register(self, token, regexp)
Register a token. Args: token (Token): the token class to register regexp (str): the regexp for that token
5.370057
7.438997
0.721879
for token_class, regexp in self._tokens: match = regexp.match(text, pos=start) if match: yield token_class, match
def matching_tokens(self, text, start=0)
Retrieve all token definitions matching the beginning of a text. Args: text (str): the text to test start (int): the position where matches should be searched in the string (see re.match(rx, txt, pos)) Yields: (token_class, re.Match): all token class...
3.75969
3.29227
1.141975
best_class = best_match = None for token_class, match in self.matching_tokens(text): if best_match and best_match.end() >= match.end(): continue best_match = match best_class = token_class return best_class, best_match
def get_token(self, text, start=0)
Retrieve the next token from some text. Args: text (str): the text from which tokens should be extracted Returns: (token_kind, token_text): the token kind and its content.
3.977086
4.267831
0.931875
if regexp is None: regexp = token_class.regexp self.tokens.register(token_class, regexp)
def register_token(self, token_class, regexp=None)
Register a token class. Args: token_class (tdparser.Token): the token class to register regexp (optional str): the regexp for elements of that token. Defaults to the `regexp` attribute of the token class.
3.553049
4.112098
0.864048
pos = 0 while text: token_class, match = self.tokens.get_token(text) if token_class is not None: matched_text = text[match.start():match.end()] yield token_class(matched_text) text = text[match.end():] pos +...
def lex(self, text)
Split self.text into a list of tokens. Args: text (str): text to parse Yields: Token: the tokens generated from the given text.
2.699346
2.992615
0.902002
tokens = self.lex(text) parser = Parser(tokens) return parser.parse()
def parse(self, text)
Parse self.text. Args: text (str): the text to lex Returns: object: a node representing the current rule.
4.057261
6.57998
0.616607
json_directory = os.path.join('examples', 'json') plot_directory = os.path.join('examples', 'plots') if not os.path.isdir(json_directory): os.makedirs(json_directory) if not os.path.isdir(plot_directory): os.makedirs(plot_directory) fit.to_json(os.path.join(json_directory, fit.name + '.json'),...
def save_example_fit(fit)
Save fit result to a json file and a plot to an svg file.
2.202639
2.024813
1.087823
if os.path.isdir(directory): shutil.rmtree(directory) if not os.path.isdir(directory): os.makedirs(directory)
def reset_directory(directory)
Remove `directory` if it exists, then create it if it doesn't exist.
2.21801
2.087574
1.062482
if not hasattr(self, '_maps'): maps = {} maps['tex_symbol'] = {} maps['siunitx'] = {} maps['value_transforms'] = { '__default__': lambda x: round(x, 2), } self._maps = maps return self._maps
def maps(self)
A dictionary of dictionaries. Each dictionary defines a map which is used to extend the metadata. The precise way maps interact with the metadata is defined by `figure.fit._extend_meta`. That method should be redefined or extended to suit specific use cases.
5.880436
5.650359
1.040719
# Relative path without potential leading path separator # otherwise os.path.join doesn't work for rel_path in self.overrides[content_type]: if rel_path[0] in ('/', '\\'): rel_path = rel_path[1:] file_path = os.path.join(document._cache_dir, rel_...
def getTreesFor(self, document, content_type)
Provides all XML documents for that content type @param document: a Document or subclass object @param content_type: a MIME content type @return: list of etree._ElementTree of that content type
5.971591
5.869931
1.017319
all_md_content_types = ( CT_CORE_PROPS, CT_EXT_PROPS, CT_CUSTOM_PROPS) return [k for k in self.overrides.keys() if k in all_md_content_types]
def listMetaContentTypes(self)
The content types with metadata @return: ['application/xxx', ...]
6.755976
6.414268
1.053273
is_int = (number_str.startswith('-') and number_str[1:].isdigit()) or number_str.isdigit() # FIXME: this handles a wider range of numbers than allowed by the json standard, # etc.: float('nan') and float('inf'). But is this a problem? return int(number_str) if is_int else float(number_str)
def default_number_converter(number_str)
Converts the string representation of a json number into its python object equivalent, an int, long, float or whatever type suits.
5.452363
5.224976
1.043519
if not hasattr(self, '_figure'): self._figure = matplotlib.pyplot.figure() return self._figure
def figure(self)
The [`matplotlib.pyplot.figure`][1] instance. [1]: http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure
3.868234
3.678715
1.051518
if not hasattr(self, '_plot'): plot = self.figure.add_subplot(111) pointspace = self.fit.pointspace(num=self.options['points']) if any(v is not None for v in self.fit.data.error): plot_data = plot.errorbar self.options['data']['xerr']...
def plot(self)
The plot object, see [Pyplot][1]. If one does not exist, it will be created first with [`add_subplot`][2]. [1]: http://matplotlib.org/api/pyplot_api.html [2]: http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.add_subplot
2.835058
2.843005
0.997205
self.plot if not hasattr(self, '_plot') else None self.figure.savefig(path, **kwargs)
def save(self, path, **kwargs)
Save the plot to the file at `path`. Any keyword arguments are passed to [`matplotlib.pyplot.savefig`][1]. [1]: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig
8.100378
7.915277
1.023385
if isinstance(file_, my_basestring): with open(file_, 'rb') as f: buf = f.read() else: buf = file_.read() return decode_utf_text_buffer(buf, default_encoding, use_utf8_strings)
def load_utf_text_file(file_, default_encoding='UTF-8', use_utf8_strings=True)
Loads the specified text file and tries to decode it using one of the UTF encodings. :param file_: The path to the loadable text file or a file-like object with a read() method. :param default_encoding: The encoding to be used if the file doesn't have a BOM prefix. :param use_utf8_strings: Ignored in case o...
2.552445
3.004812
0.849452
buf, encoding = detect_encoding_and_remove_bom(buf, default_encoding) if python2 and use_utf8_strings: if are_encoding_names_equivalent(encoding, 'UTF-8'): return buf return buf.decode(encoding).encode('UTF-8') return buf.decode(encoding)
def decode_utf_text_buffer(buf, default_encoding='UTF-8', use_utf8_strings=True)
:param buf: Binary file contents with optional BOM prefix. :param default_encoding: The encoding to be used if the buffer doesn't have a BOM prefix. :param use_utf8_strings: Used only in case of python2: You can choose utf-8 str in-memory string representation in case of python. If use_utf8_strings is ...
3.91113
4.46583
0.87579
if not isinstance(buf, bytes): raise TypeError('buf should be a bytes instance but it is a %s: ' % type(buf).__name__) for bom, encoding in _byte_order_marks: if buf.startswith(bom): return buf[len(bom):], encoding return buf, default_encoding
def detect_encoding_and_remove_bom(buf, default_encoding='UTF-8')
:param buf: Binary file contents with an optional BOM prefix. :param default_encoding: The encoding to be used if the buffer doesn't have a BOM prefix. :return: (buf_without_bom_prefix, encoding)
3.357383
3.269448
1.026896
import csv with open(filename, 'r') as f: reader = csv.DictReader(f) row = reader.next() # Only one row in the file try: cls.ACCESS_KEY_ID = row['Access Key Id'] cls.SECRET_ACCESS_KEY = row['Secret Access Key'] except KeyError: ...
def from_file(cls, filename)
Load ACCESS_KEY_ID and SECRET_ACCESS_KEY from csv generated by Amazon's IAM. >>> ec2.credentials.from_file('credentials.csv')
3.661026
3.045108
1.202265
def headers(headerDict={}, **headerskwargs): ''' This function is the decorator which is used to wrap a Flask route with. Either pass a dictionary of headers to be set as the headerDict keyword argument, or pass header values as keyword arguments. Or, do both :-) The key and value of ite...
This function is the decorator which is used to wrap a Flask route with. Either pass a dictionary of headers to be set as the headerDict keyword argument, or pass header values as keyword arguments. Or, do both :-) The key and value of items in a dictionary will be converted to strings using ...
null
null
null
if mode == 'force': amode = ['-a'] else: amode = [] oldcwd = os.getcwd() os.chdir(sitedir) db = StrictRedis.from_url(dburl) job = get_current_job(db) job.meta.update({'out': '', 'milestone': 0, 'total': 1, 'return': None, 'status': None}) job.sav...
def build(dburl, sitedir, mode)
Build a site.
2.784085
2.759191
1.009022
oldcwd = os.getcwd() os.chdir(sitedir) db = StrictRedis.from_url(dburl) job = get_current_job(db) job.meta.update({'out': '', 'return': None, 'status': None}) job.save() returncode, out = orphans_single(default_exec=True) job.meta.update({'out': out, 'return': returncode, 'status':...
def orphans(dburl, sitedir)
Remove all orphans in the site.
4.224341
4.36021
0.968839
if mode == 'force': amode = ['-a'] else: amode = [] if executable.endswith('uwsgi'): # hack, might fail in some environments! _executable = executable[:-5] + 'python' else: _executable = executable p = subprocess.Popen([_executable, '-m', 'nikola', 'build...
def build_single(mode)
Build, in the single-user mode.
4.168952
4.07774
1.022368
if not default_exec and executable.endswith('uwsgi'): # default_exec => rq => sys.executable is sane _executable = executable[:-5] + 'python' else: _executable = executable p = subprocess.Popen([_executable, '-m', 'nikola', 'orphans'], stdout=subprocess....
def orphans_single(default_exec=False)
Remove all orphans in the site, in the single user-mode.
4.569438
4.616609
0.989782
self.plt.plot(*self.fit.data, **self.options['data'])
def plot_data(self)
Add the data points to the plot.
12.027627
8.801495
1.366544
self.plt.plot(*self.fit.fit, **self.options['fit'])
def plot_fit(self)
Add the fit to the plot.
10.360079
7.666698
1.351309
x = self.fit.meta['independent'] if not text: text = '$' + x['tex_symbol'] + r'$ $(\si{' + x['siunitx'] + r'})$' self.plt.set_xlabel(text)
def add_xlabel(self, text=None)
Add a label to the x-axis.
7.815975
7.400054
1.056205
y = self.fit.meta['dependent'] if not text: text = '$' + y['tex_symbol'] + r'$ $(\si{' + y['siunitx'] + r'})$' self.plt.set_ylabel(text)
def add_ylabel(self, text=None)
Add a label to the y-axis.
7.582192
7.243839
1.046709
for m, row in enumerate(rows): for n, column in enumerate(row): self.plt.text(r0[0] + dr[0] * n, r0[1] + dr[1] * m, column, transform=self.plt.axes.transAxes, **kwargs)
def add_text_table(self, rows, r0, dr, **kwargs)
Add text to a plot in a grid fashion. `rows` is a list of lists (the rows). Each row contains the columns, each column is text to add to the plot. `r0` is a tuple `(x, y)` that positions the initial text. `dr` is a tuple `(dx, dy)` that determines the column and row spacing. ...
2.408015
2.659618
0.905399
if not isinstance(parameters, list): parameters = [parameters] rows = [] for param in parameters: row = [] row.append('$' + param['tex_symbol'] + '$') row.append('$=$') row.append(r'$\SI{' + param['disply_value'] + '}{' + param['siunitx'] ...
def parameter_table(parameters)
Create
4.240063
4.339993
0.976974
data = { 'username': 'admin', 'realname': 'Website Administrator', 'email': 'coil@example.com', 'password': r'$bcrypt-sha256$2a,12$NNtd2TC9mZO6.EvLwEwlLO$axojD34/iE8x' r'QitQnCCOGPhofgmjNdq', } for p in PERMISSIONS: data[p] = '1' db ...
def write_users(dburl)
Write users to the DB.
12.969778
13.015871
0.996459
user_profile_module = getattr(settings, 'USER_PROFILE_MODULE', None) if user_profile_module: app_label, model_name = user_profile_module.split('.') return get_model(app_label, model_name) else: return None
def get_profile_model()
Returns configured user profile model or None if not found
2.165998
1.939439
1.116817
if 'next' in request.session: next_url = request.session['next'] del request.session['next'] elif 'next' in request.GET: next_url = request.GET.get('next') elif 'next' in request.POST: next_url = request.POST.get('next') else: ...
def _get_redirect_url(self, request)
Next gathered from session, then GET, then POST, then users absolute url.
1.684417
1.568349
1.074007
fh = file(path, mode) while fh.read(1) != '<': # Ignoring everything before '<?xml...' pass fh.seek(-1, 1) return fh
def xmlFile(path, mode='r')
lxml cannot parse XML files starting with a BOM (see http://www.w3.org/TR/2000/REC-xml-20001006 in F.1.) In case such XML file is used, we must skip these characters So we open all XML files for read with 'xmlFile'. TODO: File this issue to lxml ML or tracker (feature or bug ?) :param path: The pat...
6.657402
7.611972
0.874596
rval = set() root = tree.getroot() for txp in self.text_elts_xpaths: elts = txp(root) texts = [] # Texts in element may be empty for elt in elts: text = self.text_extract_xpath(elt) if len(text) > 0: ...
def indexableText(self, tree)
Provides the indexable - search engine oriented - raw text @param tree: an ElementTree @return: set(["foo", "bar", ...])
5.175937
4.971238
1.041177
result = [(element.text or '')] if element.attrib.get('alt'): result.append(Symbol(element.attrib.get('alt')).textbox) for sel in element: result.append(self._flatten(sel)) result.append(sel.tail or '') # prevent reminder text from getting to...
def _flatten(self, element)
Recursively enter and extract text from all child elements.
8.827111
8.294819
1.064172
return [n for n in re.split(r"/(?=([^{}]*{[^{}]*})*[^{}]*$)", text) if n is not None][:2]
def split_pow_tgh(self, text)
Split a power/toughness string on the correct slash. Correctly accounts for curly braces to denote fractions. E.g., '2/2' --> ['2', '2'] '3{1/2}/3{1/2}' --> ['3{1/2}', '3{1/2}']
6.564762
5.534833
1.186081
'''Get the storage instance. :return Redis: Redis instance ''' if self.storage: return self.storage self.storage = self.reconnect_redis() return self.storage
def get_storage(self)
Get the storage instance. :return Redis: Redis instance
7.841281
5.267691
1.488561
'''Callback executed when there is a redis error. :param string fname: Function name that was being called. :param type exc_type: Exception type :param Exception exc_value: The current exception :returns: Default value or raise the current exception ''' if self....
def on_redis_error(self, fname, exc_type, exc_value)
Callback executed when there is a redis error. :param string fname: Function name that was being called. :param type exc_type: Exception type :param Exception exc_value: The current exception :returns: Default value or raise the current exception
6.358309
3.859475
1.647454
if not args: return _undefined, () if isinstance(args[0], JSONValueMapper): default = _undefined mappers = args else: default = args[0] mappers = args[1:] for mapper in mappers: if not isinstance(mapper, JSONValueMapper): raise TypeError...
def _process_value_fetcher_call_args(args)
This function processes the incoming varargs of ValueNotFoundNode.__call__() and _ConfigNode.__call__(). :param args: A list or tuple containing positional function call arguments. The optional arguments we expect are the following: An optional default value followed by zero or more JSONValueMapper inst...
3.577179
2.458808
1.454843
if isinstance(config_node, ConfigNode): return _NodeLocation(config_node._line, config_node._column) if isinstance(config_node, ValueNotFoundNode): raise JSONConfigValueNotFoundError(config_node) raise TypeError('Expected a config node but received a %s instance.' % ...
def node_location(config_node)
Returns the location of this node in the file as a tuple (line, column). Both line and column are 1 based.
5.034063
4.590656
1.096589
app.config['COIL_URL'] = \ _site.config['SITE_URL'] = _site.config['BASE_URL'] =\ _site.GLOBAL_CONTEXT['blog_url'] =\ site.config['SITE_URL'] = site.config['BASE_URL'] =\ url
def configure_url(url)
Configure site URL.
6.524464
6.055476
1.077449
try: return bcrypt_sha256.encrypt(password) except TypeError: return bcrypt_sha256.encrypt(password.decode('utf-8'))
def password_hash(password)
Hash the password, using bcrypt+sha256. .. versionchanged:: 1.1.0 :param str password: Password in plaintext :return: password hash :rtype: str
3.362998
3.526427
0.953656
from flask.ext.bcrypt import Bcrypt app.config['BCRYPT_LOG_ROUNDS'] = 12 bcrypt = Bcrypt(app) return bcrypt.check_password_hash(pwdhash, password)
def check_old_password(pwdhash, password)
Check the old password hash from :func:`password_hash`. .. versionadded:: 1.1.0 :param str pwdhash: Hash from :func:`password_hash` to check :param str password: Password in plaintext :return: password match :rtype: bool
2.268406
2.434084
0.931934
if db is not None: needs_rebuild = db.get('site:needs_rebuild') else: needs_rebuild = site.coil_needs_rebuild if needs_rebuild not in (u'0', u'-1', b'0', b'-1'): return ('</li><li><a href="{0}"><i class="fa fa-fw ' 'fa-warning"></i> <strong>Rebuild</strong></a></...
def generate_menu()
Generate ``menu`` with the rebuild link. :return: HTML fragment :rtype: str
3.921886
3.758168
1.043563
if not current_user.is_authenticated(): return ('<li><a href="{0}"><i class="fa fa-fw fa-sign-in"></i> ' 'Log in</a></li>'.format(url_for('login'))) if db is not None and current_user.is_admin: edit_entry = ( '<li><a href="{0}"><i class="fa fa-fw fa-users"></i> '...
def generate_menu_alt()
Generate ``menu_alt`` with log in/out links. :return: HTML fragment :rtype: str
2.836302
2.834262
1.00072
u = post.meta('author.uid') return u if u else str(current_user.uid)
def _author_uid_get(post)
Get the UID of the post author. :param Post post: The post object to determine authorship of :return: Author UID :rtype: str
9.776914
12.9449
0.755271
if context is None: context = {} if headers is None: headers = {} context['g'] = g context['request'] = request context['session'] = session context['current_user'] = current_user context['_author_get'] = _author_get context['_author_uid_get'] = _author_uid_get ...
def render(template_name, context=None, code=200, headers=None)
Render a response using standard Nikola templates. :param str template_name: Template name :param dict context: Context (variables) to use in the template :param int code: HTTP status code :param headers: Headers to use for the response :return: HTML fragment :rtype: str
3.892458
4.090581
0.951566
l = "[{4}] {0} {1} {2} <{3}>".format(request.remote_addr, request.method, request.url, request.endpoint, resp.status_code) c = str(resp.status_code)[0] if c in ['1', '2'] or resp.status_code == 304: app.http_logge...
def log_request(resp)
Log a request.
2.981557
3.0233
0.986193
if db is not None: try: uid = uid.decode('utf-8') except AttributeError: pass d = db.hgetall('user:{0}'.format(uid)) if d: nd = {} # strings everywhere for k in d: try: nd[k.decode('u...
def get_user(uid)
Get an user by the UID. :param str uid: UID to find :return: the user :rtype: User object :raises ValueError: uid is not an integer :raises KeyError: if user does not exist
2.563823
2.680074
0.956624
if db is not None: uid = db.hget('users', username) if uid: return get_user(uid) else: for uid, u in app.config['COIL_USERS'].items(): if u['username'] == username: return get_user(uid)
def find_user_by_name(username)
Get an user by their username. :param str username: Username to find :return: the user :rtype: User object or None
4.072168
4.500064
0.904913
udata = {} for f in USER_FIELDS: udata[f] = getattr(user, f) for p in PERMISSIONS: udata[p] = '1' if getattr(user, p) else '0' db.hmset('user:{0}'.format(user.uid), udata)
def write_user(user)
Write an user ot the database. :param User user: User to write
3.540823
3.717339
0.952516
alert = None alert_status = 'danger' code = 200 captcha = app.config['COIL_LOGIN_CAPTCHA'] form = LoginForm() if request.method == 'POST': if form.validate(): user = find_user_by_name(request.form['username']) if not user: alert = 'Invalid cre...
def login()
Handle user authentication. If requested over GET, present login page. If requested over POST, log user in. :param str status: Status of previous request/login attempt
2.575542
2.591213
0.993952
context = {'postform': NewPostForm(), 'pageform': NewPageForm(), 'delform': DeleteForm()} n = request.args.get('all') if n is None: wants_now = None else: wants_now = n == '1' if wants_now is None and current_user.wants_all_posts: wants = ...
def index()
Show the index with all posts. :param int all: Whether or not should show all posts
3.747915
4.021384
0.931996
context = {'path': path, 'site': site} post = find_post(path) if post is None: return error("No such post or page.", 404) current_auid = int(post.meta('author.uid') or current_user.uid) if (not current_user.can_edit_all_posts and current_auid != current_user.uid): ...
def edit(path)
Edit a post. If requested over GET, shows the edit UI. If requested over POST, saves the post and shows the edit UI. :param path: Path to post to edit.
3.42686
3.503816
0.978036
form = DeleteForm() path = request.form['path'] post = find_post(path) if post is None: return error("No such post or page.", 404) if not form.validate(): return error("Bad Request", 400) current_auid = int(post.meta('author.uid') or current_user.uid) if (not current_u...
def delete()
Delete a post.
4.667552
4.544625
1.027049
if db is None: return '{"error": "single-user mode"}' build_job = q.fetch_job('build') orphans_job = q.fetch_job('orphans') if not build_job and not orphans_job: build_job = q.enqueue_call(func=coil.tasks.build, args=(app.config['REDIS_URL'], ...
def api_rebuild()
Rebuild the site (internally).
3.269479
3.265878
1.001102
scan_site() # for good measure if not current_user.can_rebuild_site: return error('You are not permitted to rebuild the site.</p>' '<p class="lead">Contact an administartor for ' 'more information.', 401) if db is not None: db.set('site:needs_r...
def rebuild(mode='')
Rebuild the site with a nice UI.
4.663407
4.484931
1.039795
title = request.form['title'] _site.config['ADDITIONAL_METADATA']['author.uid'] = current_user.uid try: title = title.encode(sys.stdin.encoding) except (AttributeError, TypeError): title = title.encode('utf-8') try: if obj == 'post': f = NewPostForm() ...
def new(obj)
Create a new post or page. :param str obj: Object to create (post or page)
3.821424
3.814801
1.001736
res = pkg_resources.resource_filename( 'coil', os.path.join('data', 'bower_components')) return send_from_directory(res, path)
def serve_bower_components(path)
Serve bower components. This is meant to be used ONLY by the internal dev server. Please configure your web server to handle requests to this URL:: /bower_components/ => coil/data/bower_components
3.859132
4.334975
0.890232
res = pkg_resources.resource_filename( 'coil', os.path.join('data', 'coil_assets')) return send_from_directory(res, path)
def serve_coil_assets(path)
Serve Coil assets. This is meant to be used ONLY by the internal dev server. Please configure your web server to handle requests to this URL:: /coil_assets/ => coil/data/coil_assets
3.209773
3.928246
0.817101
res = os.path.join(app.config['NIKOLA_ROOT'], _site.config["OUTPUT_FOLDER"], 'assets') return send_from_directory(res, path)
def serve_assets(path)
Serve Nikola assets. This is meant to be used ONLY by the internal dev server. Please configure your web server to handle requests to this URL:: /assets/ => output/assets
7.787484
8.151589
0.955333
if request.args.get('status') == 'pwdchange': alert = 'You must change your password before proceeding.' alert_status = 'danger' pwdchange_skip = True else: alert = '' alert_status = '' pwdchange_skip = False if db is None: form = PwdHashForm() ...
def acp_account()
Manage the user account of currently-logged-in users. This does NOT accept admin-specific options.
3.309616
3.31847
0.997332
if not current_user.is_admin: return error("Not authorized to edit users.", 401) if not db: return error('The ACP is not available in single-user mode.', 500) alert = '' alert_status = '' if request.args.get('status') == 'deleted': alert = 'User deleted.' alert_...
def acp_users()
List all users.
3.819891
3.771579
1.012809
global current_user if not current_user.is_admin: return error("Not authorized to edit users.", 401) if not db: return error('The ACP is not available in single-user mode.', 500) data = request.form form = UserEditForm() if not form.validate(): return error("Bad Req...
def acp_users_edit()
Edit an user account.
2.831871
2.825582
1.002226
if not current_user.is_admin: return error("Not authorized to edit users.", 401) if not db: return error('The ACP is not available in single-user mode.', 500) form = UserImportForm() if not form.validate(): return error("Bad Request", 400) fh = request.files['tsv'].stre...
def acp_users_import()
Import users from a TSV file.
5.548125
5.289262
1.048941
if not current_user.is_admin: return error("Not authorized to edit users.", 401) if not db: return error('The ACP is not available in single-user mode.', 500) form = UserDeleteForm() if not form.validate(): return error("Bad Request", 400) user = get_user(int(request.fo...
def acp_users_delete()
Delete or undelete an user account.
4.640918
4.535355
1.023276