code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
'''read and return txt content of file''' with open(os.path.join(os.path.dirname(__file__), *paths)) as fp: return fp.read()
def read(*paths)
read and return txt content of file
3.669281
2.860746
1.282631
'''reads a file and returns the defined __version__ value''' version_match = re.search(r"^__version__ ?= ?['\"]([^'\"]*)['\"]", read(*paths), re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string.")
def find_version(*paths)
reads a file and returns the defined __version__ value
2.783918
2.008401
1.386137
self.compiled_exclude_files = [] for pattern in self.exclude_files: try: self.compiled_exclude_files.append(re.compile(pattern)) except re.error as e: raise ValueError( "Bad python regex in exclude '%s': %s" % (pattern,...
def compile_excludes(self)
Compile a set of regexps for files to be exlcuded from scans.
3.098813
2.785861
1.112336
for pattern in self.compiled_exclude_files: if (pattern.match(file)): return(True) return(False)
def exclude_file(self, file)
True if file should be exclude based on name pattern.
5.011013
4.829602
1.037562
num = 0 # Either use resource_list passed in or make a new one if (resource_list is None): resource_list = ResourceList() # Compile exclude pattern matches self.compile_excludes() # Work out start paths from map if not explicitly specified if ...
def from_disk(self, resource_list=None, paths=None)
Create or extend resource_list with resources from disk scan. Assumes very simple disk path to URL mapping (in self.mapping): chop path and replace with url_path. Returns the new or extended ResourceList object. If a resource_list is specified then items are added to that rather ...
5.593524
5.145426
1.087087
# sanity if (path is None or resource_list is None or self.mapper is None): raise ValueError("Must specify path, resource_list and mapper") # is path a directory or a file? for each file: create Resource object, # add, increment counter if (sys.version_info <...
def from_disk_add_path(self, path=None, resource_list=None)
Add to resource_list with resources from disk scan starting at path.
3.102604
3.049254
1.017496
try: if self.exclude_file(file): self.logger.debug("Excluding file %s" % (file)) return # get abs filename and also URL if (dir is not None): file = os.path.join(dir, file) if (not os.path.isfile(file) or no...
def add_file(self, resource_list=None, dir=None, file=None)
Add a single file to resource_list. Follows object settings of set_path, set_hashes and set_length.
3.020091
2.799859
1.078658
'''Assert that a filepath has the required file extension :param filepath: string filepath presumably containing a file extension :param ext_required: the expected file extension examples: ".pdf", ".html", ".tex" ''' ext = os.path.splitext(filepath)[-1] if ext != ext_required: m...
def has_file_extension(filepath, ext_required)
Assert that a filepath has the required file extension :param filepath: string filepath presumably containing a file extension :param ext_required: the expected file extension examples: ".pdf", ".html", ".tex"
4.083366
2.304269
1.772087
'''Assert that a string represents a system binary Return true if a string represents a system binary Raise TypeError if the system_binary_str is not a string Raise ValueError if the system_binary_str is not a system binary :param system_binary_str: STR string representing a system binary ''' ...
def is_binary(system_binary_str)
Assert that a string represents a system binary Return true if a string represents a system binary Raise TypeError if the system_binary_str is not a string Raise ValueError if the system_binary_str is not a system binary :param system_binary_str: STR string representing a system binary
2.90074
1.871963
1.549572
'''Assert that a list contains only elements of type t Return True if list contains elements of type t Raise TypeError if t is not a class Raise TypeError if ls is not a list Raise TypeError if ls contains non-t elements :param ls: LIST :param t: python class ''' if not isclass(t):...
def list_is_type(ls, t)
Assert that a list contains only elements of type t Return True if list contains elements of type t Raise TypeError if t is not a class Raise TypeError if ls is not a list Raise TypeError if ls contains non-t elements :param ls: LIST :param t: python class
2.929881
1.730588
1.692997
def wrapper(f): f_oauth_required = oauth2.require_oauth()(f) @wraps(f) def decorated(*args, **kwargs): if not hasattr(current_user, 'login_via_oauth2'): if not current_user.is_authenticated: if allow_anonymous: ...
def require_api_auth(allow_anonymous=False)
Decorator to require API authentication using OAuth token. :param allow_anonymous: Allow access without OAuth token (default: ``False``).
4.621171
4.780443
0.966683
r required_scopes = set(scopes) def wrapper(f): @wraps(f) def decorated(*args, **kwargs): # Variable requests.oauth is only defined for oauth requests (see # require_api_auth() above). if hasattr(request, 'oauth') and request.oauth is not None: ...
def require_oauth_scopes(*scopes)
r"""Decorator to require a list of OAuth scopes. Decorator must be preceded by a ``require_api_auth()`` decorator. Note, API key authentication is bypassing this check. :param \*scopes: List of scopes required.
3.534837
3.516564
1.005196
nt = PrettyTable() nt.header = False nt.padding_width = 2 nt.border = False clr_num = C_TI + "NUM" clr_name = C_TI + "NAME" clr_state = "STATE" + C_NORM t_lu = {True: [clr_num, "NAME", "REGION", "CLOUD", "SIZE", "PUBLIC IP", clr_state], False: [clr_nam...
def indx_table(node_dict, tbl_mode=False)
Print Table for dict=formatted list conditionally include numbers.
3.335227
3.198214
1.04284
path = abspath(path.rstrip(sep)) template = template or DEFAULT_TEMPLATE_URL render_skeleton( template, path, include_this=['.gitignore'], filter_this=[ '~*', '*.py[co]', '__pycache__', '__pycache__/*', '.git', '.git/*', '.hg', '.h...
def new(path='.', template=None)
Creates a new project
5.752986
5.86564
0.980794
path = abspath(path) c = Clay(path) c.run(host=host, port=port)
def run(host=DEFAULT_HOST, port=DEFAULT_PORT, path='.')
Run the development server
6.648513
5.932061
1.120776
path = abspath(path) c = Clay(path) c.build(pattern)
def build(pattern=None, path='.')
Generates a static copy of the sources
10.117318
8.883665
1.138868
total = sum(frequency_map.values()) return {k: decorator(v / total) for k, v in frequency_map.items()}
def frequency_to_probability(frequency_map, decorator=lambda f: f)
Transform a ``frequency_map`` into a map of probability using the sum of all frequencies as the total. Example: >>> frequency_to_probability({'a': 2, 'b': 2}) {'a': 0.5, 'b': 0.5} Args: frequency_map (dict): The dictionary to transform decorator (function): A function to manipu...
2.29291
3.150551
0.727781
if not texts: raise ValueError("texts must not be empty") return statistics.mean(_calculate_index_of_coincidence(frequency_analyze(text), len(text)) for text in texts)
def index_of_coincidence(*texts)
Calculate the index of coincidence for one or more ``texts``. The results are averaged over multiple texts to return the delta index of coincidence. Examples: >>> index_of_coincidence("aabbc") 0.2 >>> index_of_coincidence("aabbc", "abbcc") 0.2 Args: *texts (variabl...
6.852831
7.214062
0.949927
if length <= 1: return 0 # We cannot error here as length can legitimiately be 1. # Imagine a ciphertext of length 3 and a key of length 2. # Spliting this text up and calculating the index of coincidence results in ['AC', 'B'] # IOC of B will be calcuated for the 2nd co...
def _calculate_index_of_coincidence(frequency_map, length)
A measure of how similar frequency_map is to the uniform distribution. Or the probability that two letters picked randomly are alike.
13.627063
13.105906
1.039765
# Ignore any symbols from source that are not in target. # TODO: raise Error if source_len is 0? target_prob = frequency_to_probability(target_frequency) source_len = sum(v for k, v in source_frequency.items() if k in target_frequency) result = 0 for symbol, prob in target_prob.items(): ...
def chi_squared(source_frequency, target_frequency)
Calculate the Chi Squared statistic by comparing ``source_frequency`` with ``target_frequency``. Example: >>> chi_squared({'a': 2, 'b': 3}, {'a': 1, 'b': 2}) 0.1 Args: source_frequency (dict): Frequency map of the text you are analyzing target_frequency (dict): Frequency map of...
4.433489
5.136009
0.863217
expected = source_len * target_prob return (source_freq - expected)**2 / expected
def _calculate_chi_squared(source_freq, target_prob, source_len)
A measure of the observed frequency of the symbol versus the expected frequency. If the value is 0 then the texts are exactly alike for that symbol.
4.372291
5.413913
0.807603
module = importlib.import_module('lantern.analysis.english_ngrams.{}'.format(name)) return getattr(module, name)
def _load_ngram(name)
Dynamically import the python module with the ngram defined as a dictionary. Since bigger ngrams are large files its wasteful to always statically import them if they're not used.
6.12502
5.190716
1.179995
if not score_functions: raise ValueError("score_functions must not be empty") return statistics.mean(func(text) for func in score_functions)
def score(text, *score_functions)
Score ``text`` using ``score_functions``. Examples: >>> score("abc", function_a) >>> score("abc", function_a, function_b) Args: text (str): The text to score *score_functions (variable length argument list): functions to score with Returns: Arithmetic mean of score...
3.899206
4.16316
0.936598
pattern = re.compile(regex) return lambda text: -1 if pattern.search(text) is None else 0
def PatternMatch(regex)
Compute the score of a text by determing if a pattern matches. Example: >>> fitness = PatternMatch("flag{.*}") >>> fitness("flag{example}") 0 >>> fitness("junk") -1 Args: regex (str): regular expression string to use as a pattern
3.958699
6.298617
0.628503
r = self._session.get(url=url, params=params, headers=DEFAULT_ORIGIN) return r
def _request(self, url, params={})
Makes a request using the currently open session. :param url: A url fragment to use in the creation of the master url
6.964939
10.738994
0.648565
for func in self._registered_events[event].values(): func(*args, **kwargs)
def emit(self, event, *args, **kwargs)
Send out an event and call it's associated functions :param event: Name of the event to trigger
5.676666
7.762491
0.731294
if event is not None: self._registered_events[event] = OrderedDict() else: self._registered_events = defaultdict(OrderedDict)
def remove_all_listeners(self, event=None)
Remove all functions for all events, or one event if one is specifed. :param event: Optional event you wish to remove all functions from
4.203654
5.397214
0.778856
url: str = get_url("/service/version.json") params = {"service": "remote"} r = self._request(url=url, params=params) return r.json()
def version(self)
Spotify version information
6.973504
5.719553
1.219239
url = get_url("/remote/status.json") params = {"oauth": self._oauth_token, "csrf": self._csrf_token} r = self._request(url=url, params=params) return r.json()
def get_current_status(self)
Returns the current state of the local spotify client
5.312636
4.506762
1.178814
url: str = get_url("/remote/pause.json") params = { "oauth": self._oauth_token, "csrf": self._csrf_token, "pause": "true" if pause else "false", } self._request(url=url, params=params)
def pause(self, pause=True)
Pauses the spotify player :param pause: boolean value to choose the pause/play state
4.838281
4.941664
0.979079
url: str = get_url("/remote/play.json") params = { "oauth": self._oauth_token, "csrf": self._csrf_token, "uri": uri, "context": uri, } r = self._request(url=url, params=params) return r.json()
def playURI(self, uri)
Play a Spotify uri, for example spotify:track:5Yn8WCB4Dqm8snemB5Mu4K :param uri: Playlist, Artist, Album, or Song Uri
5.110377
5.215021
0.979934
url = get_url("/remote/status.json") def listen_for_status_change(): params = {"oauth": self._oauth_token, "csrf": self._csrf_token} r = self._request(url=url, params=params) old = r.json() self.emit("status_change", old) params = { ...
def listen(self, wait=60, blocking=True)
Listen for events and call any associated callbacks when there is an event. There are three events you can subscribe too; **status_change**, **play_state_change**, **track_change** :param wait: how long to wait for a response before starting a new connection :param blocking: if listen should bl...
2.988687
2.784228
1.073435
resp = self.session.get(self.api_url, auth=self.auth) resp = self._process_response(resp) return resp
def authenticate(self)
Authenticate with the api
4.619878
4.179661
1.105324
resp = self.session.get(os.path.join(self.api_url, 'browsers.json')) resp = self._process_response(resp) return resp.json()
def get_os_and_browsers(self)
Get all supported OS/browser combinations JSON response
4.86733
4.430765
1.09853
headers = {'content-type': 'application/json', 'Accept': 'application/json'} resp = requests.post(self.api_url, data=json.dumps(self.config), \ headers=headers, auth=self.auth) resp = self._process_response(resp) return resp.json()
def generate_screenshots(self)
Take a config file as input and generate screenshots
3.179487
2.985058
1.065134
resp = self.session.get(os.path.join(self.api_url, '{0}.json'.format(jobid))) resp = self._process_response(resp) return True if resp.json()['state'] == 'done' else False
def screenshots_done(self, jobid)
Return true if the screenshots job is done
4.049931
3.889796
1.041168
if not self.mode['items'] or len(self.mode['items']) == 0: return # FIXME: Check if already contains self.collman.add(self.player) for k in self.mode['items']: item = self.mode['items'][k] #{'terminal': False, 'num': 50, 'scale': 1.0, 'reward': 2.0} ...
def create_items(self)
Create collidable items
5.954262
5.520368
1.078599
assert isinstance(radius, int) or isinstance(radius, float) assert isinstance(item_type, str) separation_scale = 1.1 min_separation = separation_scale * radius # Removable item item = Collidable(0, 0, radius, item_type, self.pics[item_type], True) cntTr...
def add_item(self, radius, item_type)
Add a single item in random open position
3.225866
3.188904
1.011591
if not self.mode['items'] or len(self.mode['items']) == 0: return # update collman # FIXME: Why update each frame? self.collman.clear() for z, node in self.children: if hasattr(node, 'cshape') and type(node.cshape) == cm.CircleShape: self.col...
def update_collisions(self)
Test player for collisions with items
7.364069
7.03896
1.046187
op.create_table( 'oauth2server_client', sa.Column('name', sa.String(length=40), nullable=True), sa.Column('description', sa.Text(), nullable=True), sa.Column( 'website', sqlalchemy_utils.types.url.URLType(), nullable=True), sa.Column('...
def upgrade()
Upgrade database.
1.392204
1.388108
1.002951
protected_view_class = self.view_class_factory(view_class) if 'endpoint' not in kwargs: kwargs['endpoint'] = view_class(*args, **kwargs).endpoint self.admin.add_view(protected_view_class(*args, **kwargs))
def register_view(self, view_class, *args, **kwargs)
Register an admin view on this admin instance. :param view_class: The view class name passed to the view factory. :param args: Positional arugments for view class. :param kwargs: Keyword arguments to view class.
3.428288
3.825284
0.896218
for ep in pkg_resources.iter_entry_points(group=entry_point_group): admin_ep = dict(ep.load()) keys = tuple( k in admin_ep for k in ('model', 'modelview', 'view_class')) if keys == (False, False, True): self.register_view( ...
def load_entry_point_group(self, entry_point_group)
Load administration interface from entry point group. :param str entry_point_group: Name of the entry point group.
3.301715
3.37021
0.979676
self.init_config(app) default_permission_factory = app.config['ADMIN_PERMISSION_FACTORY'] permission_factory = permission_factory or \ import_string(default_permission_factory) # Create administration app. admin = Admin( app, name=a...
def init_app(self, app, entry_point_group='invenio_admin.views', permission_factory=None, view_class_factory=protected_adminview_factory, index_view_class=AdminIndexView)
Flask application initialization. :param app: The Flask application. :param entry_point_group: Name of entry point group to load views/models from. (Default: ``'invenio_admin.views'``) :param permission_factory: Default permission factory to use when protecting an admin ...
2.739786
2.757867
0.993444
sub = "{0}.spotilocal.com".format("".join(choices(ascii_lowercase, k=10))) return "http://{0}:{1}{2}".format(sub, DEFAULT_PORT, url)
def get_url(url)
Ranomdly generates a url for use in requests. Generates a hostname with the port and the provided suffix url provided :param url: A url fragment to use in the creation of the master url
6.712545
8.373927
0.801601
url = "{0}/token".format(DEFAULT_ORIGIN["Origin"]) r = s.get(url=url) return r.json()["t"]
def get_oauth_token()
Retrieve a simple OAuth Token for use with the local http client.
11.288655
9.676041
1.166661
url = get_url("/simplecsrf/token.json") r = s.get(url=url, headers=DEFAULT_ORIGIN) return r.json()["token"]
def get_csrf_token()
Retrieve a simple csrf token for to prevent cross site request forgery.
7.797984
6.86985
1.135102
# Register settings menu item = current_menu.submenu('settings.admin') item.register( "admin.index", # NOTE: Menu item text (icon replaced by a cogs icon). _('%(icon)s Administration', icon='<i class="fa fa-cogs fa-fw"></i>'), visible_when=_has_admin_access, orde...
def init_menu()
Initialize menu before first request.
12.810328
11.744473
1.090754
class ProtectedAdminView(base_class): def _handle_view(self, name, **kwargs): invenio_app = current_app.extensions.get('invenio-app', None) if invenio_app: setattr(invenio_app.talisman.local_options, 'content_securit...
def protected_adminview_factory(base_class)
Factory for creating protected admin view classes. The factory will ensure that the admin view will check if a user is authenticated and has the necessary permissions (as defined by the permission factory). The factory creates a new class using the provided class as base class and overwrites ``is_a...
2.55885
2.560234
0.999459
'''validate_config High-level api: Validate config against models. ConfigError is raised if the config has issues. Returns ------- None There is no return of this method. Raises ------ ConfigError If config contains err...
def validate_config(self)
validate_config High-level api: Validate config against models. ConfigError is raised if the config has issues. Returns ------- None There is no return of this method. Raises ------ ConfigError If config contains error.
12.157886
3.306004
3.677517
'''xpath High-level api: It is a wrapper of xpath method in lxml package. If namespaces is not given, self.ns is used by default. Returns ------- boolean or float or str or list Refer to http://lxml.de/xpathxslt.html#xpath-return-values ''' ...
def xpath(self, *args, **kwargs)
xpath High-level api: It is a wrapper of xpath method in lxml package. If namespaces is not given, self.ns is used by default. Returns ------- boolean or float or str or list Refer to http://lxml.de/xpathxslt.html#xpath-return-values
6.900136
2.587851
2.666358
'''filter High-level api: Filter the config using xpath method. If namespaces is not given, self.ns is used by default. Returns ------- Config A new Config instance which has less content according to your filter xpath expression. ''' ...
def filter(self, *args, **kwargs)
filter High-level api: Filter the config using xpath method. If namespaces is not given, self.ns is used by default. Returns ------- Config A new Config instance which has less content according to your filter xpath expression.
7.216204
3.757233
1.920616
'''_validate_node Low-level api: Validate one config node. This is a recursive method. An exception will be raised if validation fails. Parameters ---------- node : `Element` An Element node in config tree. Returns ------- None ...
def _validate_node(self, node)
_validate_node Low-level api: Validate one config node. This is a recursive method. An exception will be raised if validation fails. Parameters ---------- node : `Element` An Element node in config tree. Returns ------- None Th...
3.767162
2.838309
1.327256
'''_node_filter Low-level api: Remove unrelated nodes in config. This is a recursive method. Parameters ---------- node : `Element` A node to be processed. ancestors : `list` A list of ancestors of filtrates. filtrates : `list`...
def _node_filter(self, node, ancestors, filtrates)
_node_filter Low-level api: Remove unrelated nodes in config. This is a recursive method. Parameters ---------- node : `Element` A node to be processed. ancestors : `list` A list of ancestors of filtrates. filtrates : `list` ...
2.995392
1.832263
1.634804
def wrapper(f): @wraps(f) def decorated(*args, **kwargs): if 'client_id' not in kwargs: abort(500) client = Client.query.filter_by( client_id=kwargs.pop('client_id'), user_id=current_user.get_id(), ).first() ...
def client_getter()
Decorator to retrieve Client object and check user permission.
2.048366
1.848484
1.108133
def wrapper(f): @wraps(f) def decorated(*args, **kwargs): if 'token_id' not in kwargs: abort(500) token = Token.query.filter_by( id=kwargs.pop('token_id'), user_id=current_user.get_id(), is_personal=is_pers...
def token_getter(is_personal=True, is_internal=False)
Decorator to retrieve Token object and check user permission. :param is_personal: Search for a personal token. (Default: ``True``) :param is_internal: Search for a internal token. (Default: ``False``)
1.901341
1.94179
0.979169
clients = Client.query.filter_by( user_id=current_user.get_id(), is_internal=False, ).all() tokens = Token.query.options(db.joinedload('client')).filter( Token.user_id == current_user.get_id(), Token.is_personal == True, # noqa Token.is_internal == False, ...
def index()
List user tokens.
2.1476
2.075814
1.034582
form = ClientForm(request.form) if form.validate_on_submit(): c = Client(user_id=current_user.get_id()) c.gen_salt() form.populate_obj(c) db.session.add(c) db.session.commit() return redirect(url_for('.client_view', client_id=c.client_id)) return render...
def client_new()
Create new client.
2.533473
2.437006
1.039584
if request.method == 'POST' and 'delete' in request.form: db.session.delete(client) db.session.commit() return redirect(url_for('.index')) form = ClientForm(request.form, obj=client) if form.validate_on_submit(): form.populate_obj(client) db.session.commit() ...
def client_view(client)
Show client's detail.
2.131101
2.087819
1.020731
if request.form.get('reset') == 'yes': client.reset_client_secret() db.session.commit() return redirect(url_for('.client_view', client_id=client.client_id))
def client_reset(client)
Reset client's secret.
3.186513
2.765847
1.152093
form = TokenForm(request.form) form.scopes.choices = current_oauth2server.scope_choices() if form.validate_on_submit(): t = Token.create_personal( form.data['name'], current_user.get_id(), scopes=form.scopes.data ) db.session.commit() session['show_personal_...
def token_new()
Create new token.
3.038228
3.021479
1.005543
if request.method == "POST" and 'delete' in request.form: db.session.delete(token) db.session.commit() return redirect(url_for('.index')) show_token = session.pop('show_personal_access_token', False) form = TokenForm(request.form, name=token.client.name, scopes=token.scopes) ...
def token_view(token)
Show token details.
2.54371
2.555094
0.995545
db.session.delete(token) db.session.commit() return redirect(url_for('.index'))
def token_revoke(token)
Revoke Authorized Application token.
2.734952
3.285762
0.832365
scopes = [current_oauth2server.scopes[x] for x in token.scopes] return render_template( "invenio_oauth2server/settings/token_permission_view.html", token=token, scopes=scopes, )
def token_permission_view(token)
Show permission garanted to authorized application token.
3.931067
3.930682
1.000098
md.inlinePatterns.add('del', SimpleTagPattern(DEL_RE, 'del'), '<not_strong') md.inlinePatterns.add('ins', SimpleTagPattern(INS_RE, 'ins'), '<not_strong') md.inlinePatterns.add('mark', SimpleTagPattern(MARK_RE, 'mark'), '<not_strong')
def extendMarkdown(self, md, md_globals)
Modifies inline patterns.
1.824341
1.707207
1.068612
parser = ConfigParser() parser.read(self.status_file) status_section = 'incremental' if (not parser.has_section(status_section)): parser.add_section(status_section) if (timestamp is None): parser.remove_option( status_section, ...
def set_state(self, site, timestamp=None)
Write status dict to client status file. FIXME - should have some file lock to avoid race
2.360219
2.246625
1.050562
parser = ConfigParser() status_section = 'incremental' parser.read(self.status_file) timestamp = None try: timestamp = float( parser.get( status_section, self.config_site_to_name(site))) except N...
def get_state(self, site)
Read client status file and return dict.
5.057703
4.698168
1.076527
'''Escape a latex string''' if not isinstance(value, str): return value for regex, replace_text in REGEX_ESCAPE_CHARS: value = re.sub(regex, replace_text, value) value = re.sub(REGEX_BACKSLASH, r'\\\\', value) return value
def escape_latex_str_if_str(value)
Escape a latex string
3.352109
3.483083
0.962397
# element names depending on sitemapindex or not root_element = ('sitemapindex' if (sitemapindex) else 'urlset') item_element = ('sitemap' if (sitemapindex) else 'url') # namespaces and other settings namespaces = {'xmlns': SITEMAP_NS, 'xmlns:rs': RS_NS} root = E...
def resources_as_xml(self, resources, sitemapindex=False, fh=None)
Write or return XML for a set of resources in sitemap format. Arguments: - resources - either an iterable or iterator of Resource objects; if there an md attribute this will go to <rs:md> if there an ln attribute this will go to <rs:ln> - sitemapindex...
2.690854
2.516506
1.069282
e = Element(element_name) sub = Element('loc') sub.text = resource.uri e.append(sub) if (resource.timestamp is not None): # Create appriate element for timestamp sub = Element('lastmod') sub.text = str(resource.lastmod) # W3C Datetime...
def resource_etree_element(self, resource, element_name='url')
Return xml.etree.ElementTree.Element representing the resource. Returns and element for the specified resource, of the form <url> with enclosed properties that are based on the sitemap with extensions for ResourceSync.
3.813093
3.837445
0.993654
e = self.resource_etree_element(resource) if (sys.version_info >= (3, 0)): # python3.x return(tostring(e, encoding='unicode', method='xml')) elif (sys.version_info >= (2, 7)): s = tostring(e, encoding='UTF-8', method='xml') else: #...
def resource_as_xml(self, resource)
Return string for the resource as part of an XML sitemap. Returns a string with the XML snippet representing the resource, without any XML declaration.
3.661216
3.582842
1.021875
loc_elements = etree.findall('{' + SITEMAP_NS + "}loc") if (len(loc_elements) > 1): raise SitemapParseError( "Multiple <loc> elements while parsing <url> in sitemap") elif (len(loc_elements) == 0): raise SitemapParseError( "Missing...
def resource_from_etree(self, etree, resource_class)
Construct a Resource from an etree. Parameters: etree - the etree to parse resource_class - class of Resource object to create The parsing is properly namespace aware but we search just for the elements wanted and leave everything else alone. Will raise an error if th...
3.314096
3.222858
1.02831
md = {} # grab all understood attributes into md dict for att in ('capability', 'change', 'hash', 'length', 'path', 'mime_type', 'md_at', 'md_completed', 'md_from', 'md_until'): xml_att = self._xml_att_name(att) val = md_element.attrib.get(xml...
def md_from_etree(self, md_element, context='')
Parse rs:md attributes returning a dict of the data. Parameters: md_element - etree element <rs:md> context - context for error reporting
4.394362
4.243905
1.035452
ln = {} # grab all understood attributes into ln dict for att in ('hash', 'href', 'length', 'modified', 'path', 'rel', 'pri', 'mime_type'): xml_att = self._xml_att_name(att) val = ln_element.attrib.get(xml_att, None) if (val is not...
def ln_from_etree(self, ln_element, context='')
Parse rs:ln element from an etree, returning a dict of the data. Parameters: md_element - etree element <rs:md> context - context string for error reporting
2.737839
2.686558
1.019088
xml_atts = {} for att in atts.keys(): val = atts[att] if (val is not None): xml_atts[self._xml_att_name(att)] = str(val) if (len(xml_atts) > 0): e = Element(name, xml_atts) if (self.pretty_xml): e.tail = "\n...
def add_element_with_atts_to_etree(self, etree, name, atts)
Add element with name and atts to etree iff there are any atts. Parameters: etree - an etree object name - XML element name atts - dicts of attribute values. Attribute names are transformed
2.510888
2.763747
0.908508
if (use_default_path and len(mappings) == 1 and re.search(r"=", mappings[0]) is None): path = self.path_from_uri(mappings[0]) self.logger.warning("Using URI mapping: %s -> %s" % (mappings[0], path)) self...
def parse(self, mappings, use_default_path=False)
Parse a list of map strings (mappings). Accepts two distinct formats: 1. If there are exactly two entries then these may be the source base URI and the destination base path. Neither may contain an equals (=) sign. 2. For any number of mapping stings interpret each as a mapping ...
2.180642
2.08076
1.048002
for map in self.mappings: src_uri = map.dst_to_src(dst_file) if (src_uri is not None): return(src_uri) # Must have failed if loop exited raise MapperError( "Unable to translate destination path (%s) " "into a source URI." %...
def dst_to_src(self, dst_file)
Map destination path to source URI.
5.379525
4.323445
1.244268
for map in self.mappings: dst_path = map.src_to_dst(src_uri) if (dst_path is not None): return(dst_path) # Must have failed if loop exited raise MapperError( "Unable to translate source URI (%s) into " "a destination path."...
def src_to_dst(self, src_uri)
Map source URI to destination path.
4.692251
4.12848
1.136556
(scheme, netloc, path, params, query, frag) = urlparse(uri) if (netloc == ''): return(uri) path = '/'.join([netloc, path]) path = re.sub('[^\w\-\.]', '_', path) path = re.sub('__+', '_', path) path = re.sub('[_\.]+$', '', path) path = re.sub('...
def path_from_uri(self, uri)
Make a safe path name from uri. In the case that uri is already a local path then the same path is returned.
2.543042
2.606709
0.975575
m = re.match(r"(.*)/+$", path) if (m is None): return(path) return(m.group(1))
def strip_trailing_slashes(self, path)
Return input path minus any trailing slashes.
3.840203
3.172768
1.210364
m = re.match(self.dst_path + "/(.*)$", dst_file) if (m is None): return(None) rel_path = m.group(1) return(self.src_uri + '/' + rel_path)
def dst_to_src(self, dst_file)
Return the src URI from the dst filepath. This does not rely on the destination filepath actually existing on the local filesystem, just on pattern matching. Return source URI on success, None on failure.
3.917641
3.408746
1.149291
m = re.match(self.src_uri + "/(.*)$", src_uri) if (m is None): return(None) rel_path = m.group(1) return(self.dst_path + '/' + rel_path)
def src_to_dst(self, src_uri)
Return the dst filepath from the src URI. Returns None on failure, destination path on success.
3.638773
3.329262
1.092967
(scheme, netloc, path, params, query, frag) = urlparse(self.src_uri) if (scheme != ''): return(False) s = os.path.normpath(self.src_uri) d = os.path.normpath(self.dst_path) lcp = os.path.commonprefix([s, d]) return(s == lcp or d == lcp)
def unsafe(self)
True if the mapping is unsafe for an update. Applies only to local source. Returns True if the paths for source and destination are the same, or if one is a component of the other path.
3.639713
3.299666
1.103055
exclude = ''.join(str(symbol) for symbol in exclude) return text.translate(str.maketrans('', '', exclude))
def remove(text, exclude)
Remove ``exclude`` symbols from ``text``. Example: >>> remove("example text", string.whitespace) 'exampletext' Args: text (str): The text to modify exclude (iterable): The symbols to exclude Returns: ``text`` with ``exclude`` symbols removed
4.636564
6.773874
0.684477
if n_columns <= 0 or n_columns > len(text): raise ValueError("n_columns must be within the bounds of 1 and text length") return [text[i::n_columns] for i in range(n_columns)]
def split_columns(text, n_columns)
Split ``text`` into ``n_columns`` many columns. Example: >>> split_columns("example", 2) ['eape', 'xml'] Args: text (str): The text to split n_columns (int): The number of columns to create Returns: List of columns Raises: ValueError: If n_cols is <= 0...
2.654592
3.025889
0.877293
columns_zipped = itertools.zip_longest(*columns) return ''.join(x for zipped in columns_zipped for x in zipped if x)
def combine_columns(columns)
Combine ``columns`` into a single string. Example: >>> combine_columns(['eape', 'xml']) 'example' Args: columns (iterable): ordered columns to combine Returns: String of combined columns
4.829141
6.461512
0.74737
if n <= 0: raise ValueError("n must be a positive integer") return [text[i: i + n] for i in range(len(text) - n + 1)]
def iterate_ngrams(text, n)
Generator to yield ngrams in ``text``. Example: >>> for ngram in iterate_ngrams("example", 4): ... print(ngram) exam xamp ampl mple Args: text (str): text to iterate over n (int): size of window for iteration Returns: Generator e...
2.3992
3.225129
0.743908
if size <= 0: raise ValueError("n must be a positive integer") return [text[i:i + size] for i in range(0, len(text), size)]
def group(text, size)
Group ``text`` into blocks of ``size``. Example: >>> group("test", 2) ['te', 'st'] Args: text (str): text to separate size (int): size of groups to split the text into Returns: List of n-sized groups of text Raises: ValueError: If n is non positive
2.801574
3.016885
0.928631
evald_funcs = cls._evaluate_functions(funcs, nodes) evald_rhs = problem.rhs(nodes, *evald_funcs, **problem.params) return evald_rhs
def _evaluate_rhs(cls, funcs, nodes, problem)
Compute the value of the right-hand side of the system of ODEs. Parameters ---------- basis_funcs : list(function) nodes : numpy.ndarray problem : TwoPointBVPLike Returns ------- evaluated_rhs : list(float)
3.794708
4.912951
0.772389
interior_residuals = self._compute_interior_residuals(derivs, funcs, nodes, problem) boundary_residuals = self._compute_boundary_residuals(boundary_points, funcs, problem)...
def _assess_approximation(self, boundary_points, derivs, funcs, nodes, problem)
Parameters ---------- basis_derivs : list(function) basis_funcs : list(function) problem : TwoPointBVPLike Returns ------- resids : numpy.ndarray
2.726275
2.852038
0.955904
coefs_list = self._array_to_list(coefs_array, problem.number_odes) derivs, funcs = self._construct_approximation(basis_kwargs, coefs_list) resids = self._assess_approximation(boundary_points, derivs, funcs, nodes, problem) return resid...
def _compute_residuals(self, coefs_array, basis_kwargs, boundary_points, nodes, problem)
Return collocation residuals. Parameters ---------- coefs_array : numpy.ndarray basis_kwargs : dict problem : TwoPointBVPLike Returns ------- resids : numpy.ndarray
5.016379
5.904302
0.849614
derivs = self._construct_derivatives(coefs_list, **basis_kwargs) funcs = self._construct_functions(coefs_list, **basis_kwargs) return derivs, funcs
def _construct_approximation(self, basis_kwargs, coefs_list)
Construct a collection of derivatives and functions that approximate the solution to the boundary value problem. Parameters ---------- basis_kwargs : dict(str: ) coefs_list : list(numpy.ndarray) Returns ------- basis_derivs : list(function) basis...
3.126706
2.393654
1.306248
return [self.basis_functions.derivatives_factory(coef, **kwargs) for coef in coefs]
def _construct_derivatives(self, coefs, **kwargs)
Return a list of derivatives given a list of coefficients.
6.62066
5.637675
1.17436
return [self.basis_functions.functions_factory(coef, **kwargs) for coef in coefs]
def _construct_functions(self, coefs, **kwargs)
Return a list of functions given a list of coefficients.
8.268579
6.805095
1.215057
soln_coefs = self._array_to_list(coefs_array, problem.number_odes) soln_derivs = self._construct_derivatives(soln_coefs, **basis_kwargs) soln_funcs = self._construct_functions(soln_coefs, **basis_kwargs) soln_residual_func = self._interior_residuals_factory(soln_derivs, ...
def _solution_factory(self, basis_kwargs, coefs_array, nodes, problem, result)
Construct a representation of the solution to the boundary value problem. Parameters ---------- basis_kwargs : dict(str : ) coefs_array : numpy.ndarray problem : TwoPointBVPLike result : OptimizeResult Returns ------- solution : SolutionLike
3.582289
3.735616
0.958955
result = optimize.root(self._compute_residuals, x0=coefs_array, args=(basis_kwargs, boundary_points, nodes, problem), **solver_options) solution = self._solution_factory(basis_kwargs, result.x, nodes, ...
def solve(self, basis_kwargs, boundary_points, coefs_array, nodes, problem, **solver_options)
Solve a boundary value problem using the collocation method. Parameters ---------- basis_kwargs : dict Dictionary of keyword arguments used to build basis functions. coefs_array : numpy.ndarray Array of coefficients for basis functions defining the initial ...
3.323286
3.718077
0.893819
fmt = '%(asctime)s | %(name)s | %(levelname)s | %(message)s' formatter = UTCFormatter(fmt) if human: # Create a special handler designed just for human readable output hh = logging.StreamHandler() hh.setLevel(logging.INFO if (verbose) else logging.WARNING) hh.setFormatt...
def init_logging(to_file=False, logfile=None, default_logfile='/tmp/resync.log', human=True, verbose=False, eval_mode=False, default_logger='client', extra_loggers=None)
Initialize logging. Use of log levels: DEBUG - very verbose, for evaluation of output (-e) INFO - verbose, only seen by users if they ask for it (-v) WARNING - messages output messages to console Logging to a file: If to_file is True then output will be written to a file. This will be logfile ...
2.455418
2.565747
0.956999
links = [] if (args_link is not None): for link_str in args_link: try: links.append(parse_link(link_str)) except ClientFatalError as e: raise ClientFatalError( "Bad --link option '%s' (%s)" % (link_str, ...
def parse_links(args_link)
Parse --link options. Uses parse_link() to parse each option.
3.160803
3.077755
1.026983
atts = {} help_str = "--link option '%s' (format rel,href,att1=val1...)" % (link_str) try: segs = link_str.split(',') # First segments are relation and subject atts['rel'] = segs.pop(0) atts['href'] = segs.pop(0) if (atts['href'] == ''): raise ClientF...
def parse_link(link_str)
Parse one --link option to add to <rs:ln> links. Input string of the form: rel,href,att1=val1,att2=val2
3.841487
3.321756
1.156463
capabilities = {} try: segs = caps_str.split(',') for term in segs: (k, v) = term.split('=') capabilities[k] = v except ValueError as e: raise ClientFatalError( "Bad component of --capabilitylist option '%s' (%s)" % (caps_str, str(...
def parse_capabilities(caps_str)
Parse list of capabilities in --capabilitylist option. Input string of the form: cap_name=uri,cap_name=uri
4.771544
3.941567
1.21057
if (not re.match(r'''\w+:''', uri)): uri = 'file:' + uri return(urlopen(uri))
def url_or_file_open(uri)
Wrapper around urlopen() to prepend file: if no scheme provided.
5.743357
4.071723
1.410547