code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if not image_id_or_slug: msg = 'image_id_or_slug is required to transfer an image!' raise DOPException(msg) if not region_id: raise DOPException('region_id is required to transfer an image!') params = {'region_id': region_id} json = self.requ...
def transfer_image(self, image_id_or_slug, region_id)
This method allows you to transfer an image to a specified region. Required parameters image_id: Numeric, this is the id of the image you would like to transfer. region_id Numeric, this is the id of the region to which you would like to transfer.
2.637637
2.812102
0.937959
params = {} json = self.request('/ssh_keys', method='GET', params=params) status = json.get('status') if status == 'OK': ssh_keys_json = json.get('ssh_keys', []) keys = [SSHKey.from_json(ssh_key) for ssh_key in ssh_keys_json] return keys ...
def ssh_keys(self)
This method lists all the available public SSH keys in your account that can be added to a droplet.
3.013654
2.997716
1.005316
params = {'name': name, 'ssh_pub_key': ssh_pub_key} json = self.request('/ssh_keys/new', method='GET', params=params) status = json.get('status') if status == 'OK': ssh_key_json = json.get('ssh_key') ssh_key = SSHKey.from_json(ssh_key_json) re...
def add_ssh_key(self, name, ssh_pub_key)
This method allows you to add a new public SSH key to your account. Required parameters name: String, the name you want to give this SSH key. ssh_pub_key: String, the actual public SSH key.
2.552723
2.672313
0.955249
params = {} json = self.request('/ssh_keys/%s' % ssh_key_id, method='GET', params=params) status = json.get('status') if status == 'OK': ssh_key_json = json.get('ssh_key') ssh_key = SSHKey.from_json(ssh_key_json) return ssh_key else: ...
def show_ssh_key(self, ssh_key_id)
This method shows a specific public SSH key in your account that can be added to a droplet.
2.593323
2.600205
0.997354
json = self.request('/ssh_keys/%s/destroy' % ssh_key_id, method='GET') status = json.get('status') return status
def destroy_ssh_key(self, ssh_key_id)
This method will delete the SSH key from your account.
4.123308
4.134199
0.997366
json = self.request('/sizes', method='GET') status = json.get('status') if status == 'OK': sizes_json = json.get('sizes', []) sizes = [Size.from_json(s) for s in sizes_json] return sizes else: message = json.get('message') ...
def sizes(self)
This method returns all the available sizes that can be used to create a droplet.
3.39381
3.152773
1.076452
json = self.request('/domains', method='GET') status = json.get('status') if status == 'OK': domains_json = json.get('domains', []) domains = [Domain.from_json(domain) for domain in domains_json] return domains else: message = json...
def domains(self)
This method returns all of your current domains.
3.261702
3.102642
1.051266
params = {'name': name, 'ip_address': ip_address} json = self.request('/domains/new', method='GET', params=params) status = json.get('status') if status == 'OK': domain_json = json.get('domain') domain = Domain.from_json(domain_json) return do...
def create_domain(self, name, ip_address)
This method creates a new domain name with an A record for the specified [ip_address]. Required parameters name: String, the name you want to give this SSH key. ip_address: String, ip address for the domain's initial a record.
2.786232
2.909701
0.957567
json = self.request('/domains/%s' % domain_id, method='GET') status = json.get('status') if status == 'OK': domain_json = json.get('domain') domain = Domain.from_json(domain_json) return domain else: message = json.get('message') ...
def show_domain(self, domain_id)
This method returns the specified domain. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain to display.
2.91778
3.228398
0.903786
json = self.request('/domains/%s/destroy' % domain_id, method='GET') status = json.get('status') return status
def destroy_domain(self, domain_id)
This method deletes the specified domain. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain to destroy.
4.497999
6.467011
0.69553
json = self.request('/domains/%s/records' % domain_id, method='GET') status = json.get('status') if status == 'OK': records_json = json.get('records', []) records = [Record.from_json(record) for record in records_json] return records else: ...
def domain_records(self, domain_id)
This method returns all of your current domain records. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to retrieve records.
2.787452
3.048947
0.914234
params = dict(record_type=record_type, data=data) if name: params.update({'name': name}) if priority: params.update({'priority': priority}) if port: params.update({'port': port}) if weight: params.update({'weight': weight}...
def create_domain_record(self, domain_id, record_type, data, name=None, priority=None, port=None, weight=None)
This method creates a new domain name with an A record for the specified [ip_address]. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to create a record. record_type: Strin...
2.12855
2.236209
0.951857
json = self.request('/domains/%s/records/%s' % (domain_id, record_id), method='GET') status = json.get('status') if status == 'OK': domain_record_json = json.get('record') domain_record = Record.from_json(domain_record_json) ...
def show_domain_record(self, domain_id, record_id)
This method returns the specified domain record. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to retrieve a record. record_id: Integer, specifies the record_id to retrieve.
2.657225
2.843925
0.934351
json = self.request('/domains/%s/records/%s/destroy' % (domain_id, record_id), method='GET') status = json.get('status') return status
def destroy_domain_record(self, domain_id, record_id)
This method deletes the specified domain record. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to destroy a record. record_id: Integer, specifies the record_id to destroy.
3.44204
4.409967
0.780514
json = self.request('/events/%s' % event_id, method='GET') status = json.get('status') if status == 'OK': event_json = json.get('event') event = Event.from_json(event_json) return event else: message = json.get('message') ...
def events(self, event_id)
This method is primarily used to report on the progress of an event by providing the percentage of completion. Required parameters event_id: Numeric, this is the id of the event you would like more information about
2.932123
3.399388
0.862544
retour = {} for (key, value) in request.headers: if key.startswith('X-Plugit-'): key = key[9:] retour[key] = value return retour
def get_ebuio_headers(request)
Return a dict with ebuio headers
4.87705
4.545461
1.07295
def ioctl_GWINSZ(fd): # These two imports are only present on POSIX systems, so they must be # guarded by a try block. import fcntl import termios return struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234")) # try stdin, stdout, stderr for fd in (0, 1...
def getTerminalSize()
returns (lines:int, cols:int)
2.526175
2.59582
0.97317
from time import sleep maxProgress = 1000 with ProgressBar(max=maxProgress) as progressbar: for i in range(-100, maxProgress): sleep(0.01) progressbar.update(i) progressbar2 = ProgressBar(max=maxProgress) for s in progressbar2.iterate(range(maxProgress)): ...
def demo()
Demonstrate progress bar.
2.970362
2.737051
1.085242
# If iterable has a definite length, then set the maximum value of the # progress bar. Else, set the maximum value to -1 so that the progress # bar displays indeterminate progress (scrolling dots). try: length = len(iterable) except TypeError: se...
def iterate(self, iterable, format="%s")
Use as a target of a for-loop to issue a progress update for every iteration. For example: progress = ProgressBar() for text in progress.iterate(["foo", "bar", "bat"]): ...
4.352508
4.458754
0.976171
if len(self.text) > self.textwidth: label = self.text[0:self.textwidth] else: label = self.text.rjust(self.textwidth) terminalSize = getTerminalSize() if terminalSize is None: terminalSize = 80 else: terminalSize = termin...
def show(self)
Redraw the text progress bar.
3.607917
3.511123
1.027568
redraw = False if text is not None: redraw = text != self.text self.text = text if value is not None: redraw |= self.max == 0 or round(value/(0.0003*self.max)) != \ round(self.value/(0.0003*self.max)) self.value = value ...
def update(self, value=None, text=None)
Redraw the progress bar, optionally changing the value and text and return the (possibly new) value. For I/O performance, the progress bar might not be written to the terminal if the text does not change and the value changes by too little. Use .show() to force a redraw.
3.672791
3.038208
1.208867
return self.update(value=min(self.max, self.value + delta), text=text)
def increment(self, delta=1, text=None)
Redraw the progress bar, incrementing the value by delta (default=1) and optionally changing the text. Returns the ProgressBar's new value. See also .update().
4.87808
4.619433
1.055991
dst_w = float(dst_w) dst_h = float(dst_h) img_w = float(img_w) img_h = float(img_h) dst_ratio = float(dst_w) / dst_h img_ratio = float(img_w) / img_h if dst_ratio > img_ratio: # image is narrower, use height y = 0 h = dst_h w = h * img_ratio x ...
def adjust_fit(dst_w, dst_h, img_w, img_h)
given a x and y of dest, determine the ratio and return an (x,y,w,h) for a fitted image (note x or y could be neg). >>> adjust_fit(4,3,5,5) (0.5, 0, 3.0, 3.0) >>> adjust_fit(8,6,5,5) (1.0, 0, 6.0, 6.0) >>> adjust_fit(4,3,5,2) (0, 0.69999999999999996, 4.0, 1.6000000000000001) >>> adjust_f...
1.828546
1.949364
0.938022
# get image size image = Image.open(self.path) width, height = image.size if mode == FIT: return adjust_crop(dst_x, dst_y, width, height)
def adjust_size(self, dst_x, dst_y, mode=FIT)
given a x and y of dest, determine the ratio and return an (x,y,w,h) for a output image.
3.181952
3.386178
0.939688
P = np.asarray(P) assert np.all(P >= 0) assert P.ndim == 2 assert P.shape[0] == P.shape[1] N = P.shape[0] max_thresh = 1 + self._epsilon min_thresh = 1 - self._epsilon # Initialize r and c, the diagonals of D1 and D2 # and warn if the ma...
def fit(self, P)
Fit the diagonal matrices in Sinkhorn Knopp's algorithm Parameters ---------- P : 2d array-like Must be a square non-negative 2d array-like object, that is convertible to a numpy array. The matrix must not be equal to 0 and it must have total support for the algorithm ...
2.443781
2.364311
1.033612
# set debug to 1 to see all HTTP(s) traffic debug = int(debug) # need an instance of HTTPS handler to do HTTPS httpsHandler = urllib2.HTTPSHandler(debuglevel = debug) # use a cookie jar to store session cookies jar = cookielib.LWPCookieJar() # if a cookier jar exists open it and read...
def request_ligodotorg(url, debug=False)
Request the given URL using LIGO.ORG SAML authentication. This requires an active Kerberos ticket for the user, to get one: $ kinit albert.einstein@LIGO.ORG Parameters ---------- url : `str` URL path for request debug : `bool`, optional Query in verbose debuggin mode, default ...
4.249388
4.453418
0.954186
req_str = "/"+str( kwargs['id'] )+"/"+cat+'?' #/id/category? del kwargs['id'] kwargs['access_token'] = token #add access token to kwwargs res = wiring.send_request(method, con, req_str, kwargs) return res
def publish_cat1(method, con, token, cat, kwargs)
Constructs a "POST" and "DELETE" URL. The function is used by the publish and delete method First category of "POST" and "DELETE" url construction. Caling it first category because for publishing photos or more complex stuffs, newer fucntions might be added to deal with "POST".
9.933362
8.812148
1.127235
req_str = "/"+kwargs['id']+"?" #/id? req_str += "access_token="+token #/id?@acces_token=...... del kwargs['id'] key = settings.get_object_cat1_param[cat] #get the param name for the category(single, multiple) req_str += "&"+key+"=" ...
def get_object_cat1(con, token, cat, kwargs)
Constructs the "GET" URL. The functions is used by the get_object method First Category of "GET" URL construction. Again calling it first category because more complex functions maybe added later.
5.251238
5.200567
1.009743
if not rhs_graph: return {}, {}, {} self.matching_code_container.add_graph_to_namespace(lhs_graph) self.matching_code_container.add_graph_to_namespace(rhs_graph) return self.__collect_variables_that_match_graph(lhs_graph, rhs_graph)
def get_variables_substitution_dictionaries(self, lhs_graph, rhs_graph)
Looks for sub-isomorphisms of rhs into lhs :param lhs_graph: The graph to look sub-isomorphisms into (the bigger graph) :param rhs_graph: The smaller graph :return: The list of matching names
4.590152
5.059278
0.907274
self.set_src_path(src_folder) if not os.path.isdir(self.get_src_path()): raise ArdyNoFileError("File {} not exist".format(self.get_src_path())) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = 'dis...
def run(self, src_folder, requirements="requirements.txt", local_package=None)
Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well...
3.675151
3.626843
1.01332
def _filter_blacklist(package): blacklist = ["-i", "#", "Python==", "ardy=="] return all(package.startswith(entry.encode()) is False for entry in blacklist) filtered_packages = filter(_filter_blacklist, packages) # print([package for package in filtered_package...
def _install_packages(self, path, packages)
Install all packages listed to the target directory. Ignores any package that includes Python itself and python-lambda as well since its only needed for deploying and not running the code :param str path: Path to copy installed pip packages to. :param list packages: ...
4.744792
4.341014
1.093015
packages = [] if not requirements: logger.debug('Gathering pip packages') # packages.extend(pip.operations.freeze.freeze()) pass else: requirements_path = os.path.join(self.get_src_path(), requirements) logger.debug('Gathering ...
def pip_install_to_target(self, path, requirements="", local_package=None)
For a given active virtualenv, gather all installed pip packages then copy (re-install) them to the path provided. :param str path: Path to copy installed pip packages to. :param str requirements: If set, only the packages in the requirements.txt file are installed. ...
2.697758
2.747645
0.981844
rowNames = [] columnNames = [] matrix = [] first = True for line in f.readlines(): line = line.rstrip() if len(line) == 0: continue row = line.split(separator) if first: columnNames = row[1:] first = False else: ...
def readTableFromDelimited(f, separator="\t")
Reads a table object from given plain delimited file.
2.045901
2.026965
1.009342
rowNames = [] columnNames = [] matrix = [] first = True for row in csv.reader(f, dialect): if first: columnNames = row[1:] first = False else: rowNames.append(row[0]) matrix.append([float(c) for c in row[1:]]) return Table(ro...
def readTableFromCSV(f, dialect="excel")
Reads a table object from given CSV file.
2.225341
2.204887
1.009277
return self.matrix[self.rowIndices[rowName], self.columnIndices[columnName]]
def cell(self, rowName, columnName)
Returns the value of the cell on the given row and column.
4.442177
4.530667
0.980469
rows = [] for rowName in self.rowNames: row = {columnName: self[rowName, columnName] for columnName in self.columnNames} row["_"] = rowName rows.append(row) return rows
def rows(self)
Returns a list of dicts.
3.62612
3.112011
1.165201
db.drop_all() db.configure_mappers() db.create_all() db.session.commit()
def init_db()
Drops and re-creates the SQL schema
2.868742
2.758194
1.04008
from gunicorn.app.base import Application class FlaskApplication(Application): def init(self, parser, opts, args): return {'bind': '{0}:{1}'.format(host, port), 'workers': workers} def load(self): return app application = FlaskApplication() return applicat...
def gunicorn(host, port, workers)
use gunicorn
1.928923
1.921741
1.003738
# try to add as zipfile zin = zipfile.ZipFile(path) for zinfo in zin.infolist(): name = zinfo.filename if name.endswith("/"): self.mkdir(name) else: content = zin.read(name) self.touch(name, content)
def load_zipfile(self, path)
import contents of a zipfile
3.172752
3.122607
1.016059
def visit_path(arg, dirname, names): for name in names: fpath = os.path.join(dirname, name) new_path = fpath[len(path):] if os.path.isfile(fpath): content = open(fpath, "rb").read() self.touch(new_path,...
def load_dir(self, path)
import contents of a directory
2.767646
2.684092
1.031129
basepath = basepath or self.src_dir return path[len(basepath) + 1:]
def _rel_path(self, path, basepath=None)
trim off basepath
4.177432
3.760637
1.110831
if not os.path.exists(directory): os.makedirs(directory) shutil.copytree(self.src_dir, directory)
def unzip(self, directory)
Write contents of zipfile to directory
3.080188
3.220462
0.956443
if not repeat_n_times: repeat_n_times = self.__determine_how_many_times_to_repeat_query(string) lines = self.__get_command_lines(string) return_list = [] for line in lines: lst = self.__query_n_times(line, repeat_n_times) if lst and lst[0]: ...
def query(self, string, repeat_n_times=None)
This method performs the operations onto self.g :param string: The list of operations to perform. The sequences of commands should be separated by a semicolon An example might be CREATE {'tag': 'PERSON', 'text': 'joseph'}(v1), {'relation': 'LIVES_AT'}(v1,v2), ...
3.143396
2.631147
1.194686
action_graph_pairs = self.__get_action_graph_pairs_from_query(string) for action, graph_str in action_graph_pairs: if action == 'RETURN' or action == '': return self.__return(graph_str, builder) try: self.action_dict[action](graph_str, bui...
def __query_with_builder(self, string, builder)
Uses the builder in the argument to modify the graph, according to the commands in the string :param string: The single query to the database :return: The result of the RETURN operation
5.559112
5.10723
1.088479
import re query = convert_special_characters_to_spaces(query) graph_list = re.split('|'.join(self.action_list), query) query_list_positions = [query.find(graph) for graph in graph_list] query_list_positions = query_list_positions query_list_positions = query_lis...
def __get_action_graph_pairs_from_query(self, query)
Splits the query into command/argument pairs, for example [("MATCH","{}(_a))", ("RETURN","_a")] :param query: The string with the list of commands :return: the command/argument pairs
3.078305
3.225148
0.954469
to_sign = '-!'.join(args) + '$$'.join(kwargs.values()) key = settings.SECRET_FOR_SIGNS hashed = hmac.new(key, to_sign, sha1) return re.sub(r'[\W_]+', '', binascii.b2a_base64(hashed.digest()))
def create_secret(*args, **kwargs)
Return a secure key generated from the user and the object. As we load elements fron any class from user imput, this prevent the user to specify arbitrary class
5.7388
6.152555
0.932751
''' inptStr may be a string of the following forms: * 'meme: text0 | text1' * 'gif: search_keywords' If not, it returns an appropriate error message, stating an improperly formatted <magic> tag. Fails gracefully when it can't find or generate a meme or a gif, by returning an appro...
def processString(inptStr)
inptStr may be a string of the following forms: * 'meme: text0 | text1' * 'gif: search_keywords' If not, it returns an appropriate error message, stating an improperly formatted <magic> tag. Fails gracefully when it can't find or generate a meme or a gif, by returning an appropriate image ...
6.040237
2.062824
2.92814
'''i am winston wolfe, i solve problems''' arguments = docopt(__doc__, version=__version__) if arguments['on']: print 'Mr. Wolfe is at your service' print 'If any of your programs run into an error' print 'use wolfe $l' print 'To undo the changes made by mr wolfe in your bashrc, do wolfe off' ...
def main()
i am winston wolfe, i solve problems
11.053793
7.878808
1.402978
_form = mechanize.HTMLForm(self.SEARCH_MEMBERS_URL, method="POST") _form.new_control('text', 'username', {'value': account}) _form.new_control('text', '_', {'value': ''}) try: r = self.post_url(self.SEARCH_MEMBERS_URL, form=_form) except AuthRequiredExceptio...
def get_account_details(self, account)
This method can be used in a number of scenarios: 1. When it is necessary to very account information 2. When there's a need to filter transactions by an account id 3. When account details (e.g. name of account) are needed
5.861566
6.024621
0.972935
kw_map = { 'to_date': 'query(period).end', 'from_account_id': 'query(member)', 'from_date': 'query(period).begin', 'txn_ref': 'query(transactionNumber)'} if not self.TRANSACTIONS_FORM: try: self.get_url(self.TRANSACTIO...
def get_transactions(self, **kwargs)
This method optionally takes the following extra keyword arguments: to_date: a datetime object representing the date the filter should end with from_date: a datetime object representing the date the filter should start from txn_ref: the transaction reference of a particular transaction ...
3.217127
3.048901
1.055176
self.br.open(self.MOBILE_WEB_URL % {'accountno': self.account}) try: # Search for the existence of the Register link - indicating a new account # Payments cannot be made from an account that isn't registered - obviously. self.br.find_link(text='Register') ...
def make_payment(self, recipient, amount, description=None)
make_payment allows for automated payments. A use case includes the ability to trigger a payment to a customer who requires a refund for example. You only need to provide the recipient and the amount to be transfered. It supports transfers in Kobo as well, just add the necessary decimals...
4.098804
4.064747
1.008379
self.br.open(self.MOBILE_WEB_URL % {'accountno': self.account}) try: # Search for the existence of the Register link - indicating a new account self.br.find_link(text='Register') raise InvalidAccountException except mechanize.LinkNotFoundError: ...
def get_balance(self)
Retrieves the balance for the configured account
4.66355
4.516646
1.032525
_r = self.br.open(url) # check that we've not been redirected to the login page if self.br.geturl().startswith(self.AUTH_URL): raise AuthRequiredException elif self.br.geturl().startswith(self.ERROR_URL): raise RequestErrorException else: ...
def get_url(self, url)
Internally used to retrieve the contents of a URL
4.284086
4.268158
1.003732
_r = self.br.open(url, form.click_request_data()[1]) # check that we've not been redirected to the login page or an error occured if self.br.geturl().startswith(self.AUTH_URL): raise AuthRequiredException elif self.br.geturl().startswith(self.ERROR_URL): ...
def post_url(self, url, form)
Internally used to retrieve the contents of a URL using the POST request method. The `form` parameter is a mechanize.HTMLForm object This method will use a POST request type regardless of the method used in the `form`.
5.651384
5.36185
1.053999
transactions = list() if response: f = StringIO(response) reader = csv.DictReader(f) for line in reader: txn = {} txn['date'] = datetime.strptime(line['Date'], '%d/%m/%Y %H:%M:%S') txn['description'] = line['D...
def _parse_transactions(self, response)
This method parses the CSV output in `get_transactions` to generate a usable list of transactions that use native python data types
3.300611
3.209104
1.028515
from hprojects.models import HostedProject try: hproject = HostedProject.objects.get(pk=hproPk) except (HostedProject.DoesNotExist, ValueError): try: hproject = HostedProject.objects.get(plugItCustomUrlKey=hproPk) except HostedProject.DoesNotExist: rais...
def getPlugItObject(hproPk)
Return the plugit object and the baseURI to use if not in standalone mode
3.300081
3.094664
1.066378
user = None if mode == 'log' or pk == "-1": user = DUser(pk=-1, username='Logged', first_name='Logged', last_name='Hector', email='logeedin@plugit-standalone.ebuio') user.gravatar = 'https://www.gravatar.com/avatar/ebuio1?d=retro' user.ebuio_member = False user.ebuio_admin...
def generate_user(mode=None, pk=None)
Return a false user for standalone mode
2.444687
2.374225
1.029678
return HttpResponseNotFound( render_to_response('plugIt/404.html', {'context': { 'reason': reason, 'ebuio_baseUrl': baseURI, 'ebuio_userMode': request.session.get('plugit-standalone-usermode', 'ano'), }, 'project': proj...
def gen404(request, baseURI, reason, project=None)
Return a 404 error
7.169083
7.331464
0.977852
return HttpResponseServerError( render_to_response('plugIt/500.html', { 'context': { 'ebuio_baseUrl': baseURI, 'ebuio_userMode': request.session.get('plugit-standalone-usermode', 'ano'), }, 'project': project }, context_instanc...
def gen500(request, baseURI, project=None)
Return a 500 error
6.80162
6.835699
0.995015
orgas = None public_ask = False if not settings.PIAPI_STANDALONE: from organizations.models import Organization if project and project.plugItLimitOrgaJoinable: orgas = project.plugItOrgaJoinable.order_by('name').all() else: orgas = Organization.objects....
def gen403(request, baseURI, reason, project=None)
Return a 403 error
4.824991
4.819277
1.001186
# Caching cacheKey = None if 'cache_time' in meta: if meta['cache_time'] > 0: # by default, no cache by user useUser = False # If a logged user in needed, cache the result by user if ('only_logged_user' in meta and meta['only_logged_user']) or...
def get_cache_key(request, meta, orgaMode, currentOrga)
Return the cache key to use
3.044682
3.079062
0.988834
# User must be logged ? if ('only_logged_user' in meta and meta['only_logged_user']): if not request.user.is_authenticated(): return gen403(request, baseURI, 'only_logged_user', project) # User must be member of the project ? if ('only_member_user' in meta and meta['only_member...
def check_rights_and_access(request, meta, project=None)
Check if the user can access the page
1.840182
1.835636
1.002476
from ipware.ip import get_real_ip, get_ip # Get the real IP, i.e. no reverse proxy, no nginx ip = get_real_ip(request) if not ip: ip = get_ip(request) if not ip: return False # For all networks for network in networks: if is_address_in_network(ip, netwo...
def is_requestaddress_in_networks(request, networks)
Helper method to check if the remote real ip of a request is in a network
3.07594
3.021554
1.017999
# http://stackoverflow.com/questions/819355/how-can-i-check-if-an-ip-is-in-a-network-in-python import socket import struct ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0] netaddr, bits = net.split('/') if int(bits) == 0: return True net = struct.unpack('=L', socket.inet_at...
def is_address_in_network(ip, net)
Is an address in a network
2.617528
2.523541
1.037244
# If we have to use cache, we try to find the result in cache if cacheKey: data = cache.get('plugit-cache-' + cacheKey, None) # We found a result, we can return it if data: return (data['result'], data['menu'], data['context']) return (None, None, None)
def find_in_cache(cacheKey)
Check if the content exists in cache and return it
6.841824
7.497959
0.912492
getParameters = {} postParameters = {} files = {} # Copy GET parameters, excluding ebuio_* for v in request.GET: if v[:6] != 'ebuio_': val = request.GET.getlist(v) if len(val) == 1: getParameters[v] = val[0] else: ge...
def build_base_parameters(request)
Build the list of parameters to forward from the post and get parameters
2.367268
2.289288
1.034063
postParameters = {} getParameters = {} files = {} # Add parameters requested by the server if 'user_info' in meta: for prop in meta['user_info']: # Test if the value exist, otherwise return None value = None if hasattr(request.user, prop) and prop ...
def build_user_requested_parameters(request, meta)
Build the list of parameters requested by the plugit server
5.106761
4.939251
1.033914
postParameters = {} getParameters = {} files = {} def update_parameters(data): tmp_getParameters, tmp_postParameters, tmp_files = data getParameters.update(tmp_getParameters) postParameters.update(tmp_postParameters) files.update(tmp_files) update_parameters(...
def build_parameters(request, meta, orgaMode, currentOrga)
Return the list of get, post and file parameters to send
2.725069
2.441344
1.116217
things_to_add = {} # If in proxymode, add needed infos to headers if proxyMode: # User for prop in settings.PIAPI_USERDATA: if hasattr(request.user, prop): things_to_add['user_' + prop] = getattr(request.user, prop) # Orga if orgaMode: ...
def build_extra_headers(request, proxyMode, orgaMode, currentOrga)
Build the list of extra headers
2.756642
2.750905
1.002085
if request.method == 'OPTIONS': r = HttpResponse('') return r if data is None: return gen404(request, baseURI, 'data') if data.__class__.__name__ == 'PlugIt500': return gen500(request, baseURI) if data.__class__.__name__ == 'PlugItSpecialCode': r = HttpRe...
def handle_special_cases(request, data, baseURI, meta)
Handle sepcial cases for returned values by the doAction function
3.080106
3.058917
1.006927
if 'no_template' in meta and meta['no_template']: # Just send the json back return HttpResponse(result) # TODO this breaks pages not using new template # Add sidebar toggler if plugit did not add by itself # if not "sidebar-toggler" in result: # result = "<div class=\"menubar\"><...
def build_final_response(request, meta, result, menu, hproject, proxyMode, context)
Build the final response to send back to the browser
4.362999
4.306834
1.013041
''' taken originally from http://stackoverflow.com/questions/2687173/django-how-can-i-get-a-block-from-a-template ''' for node in template: if isinstance(node, BlockNode) and node.name == name: return node.nodelist.render(context) elif isinstance(node, ExtendsNode): ...
def _get_node(template, context, name)
taken originally from http://stackoverflow.com/questions/2687173/django-how-can-i-get-a-block-from-a-template
3.323498
2.065969
1.608687
if proxyMode: # Update csrf_tokens csrf = unicode(context['csrf_token']) tag = u'{~__PLUGIT_CSRF_TOKEN__~}' rendered_data = unicode(rendered_data, 'utf-8').replace(tag, csrf) result = rendered_data # Render in proxy mode menu = None # Proxy mode plugit do not...
def render_data(context, templateContent, proxyMode, rendered_data, menukey='menubar')
Render the template
7.067021
7.101225
0.995183
if cacheKey: # This will be a method in django 1.7 flat_context = {} for d in context.dicts: flat_context.update(d) del flat_context['csrf_token'] data = {'result': result, 'menu': menu, 'context': flat_context} cache.set('plugit-cache-' + cacheK...
def cache_if_needed(cacheKey, result, menu, context, meta)
Cache the result, if needed
5.398625
5.386097
1.002326
templateContent = None if not proxyMode: templateContent = plugIt.getTemplate(query, meta) if not templateContent: return (None, gen404(request, baseURI, 'template')) return (templateContent, None)
def get_template(request, query, meta, proxyMode)
Return (if needed) the template to use
6.891127
6.948889
0.991688
# If nothing available return 404 if len(availableOrga) == 0: raise Http404 # Find the current orga currentOrgaId = request.session.get('plugit-orgapk-' + str(hproject.pk), None) # If we don't have a current one select the first available if currentOrgaId is None: (tmpOrg...
def get_current_orga(request, hproject, availableOrga)
Return the current orga to use
2.938469
2.980644
0.985851
for key, value in session_to_set.items(): request.session['plugit_' + str(hproPk) + '_' + key] = value
def update_session(request, session_to_set, hproPk)
Update the session with users-realted values
4.000567
4.120729
0.97084
retour = {} base_key = 'plugit_' + str(hproPk) + '_' for key, value in request.session.iteritems(): if key.startswith(base_key): retour[key[len(base_key):]] = value return retour
def get_current_session(request, hproPk)
Get the current session value
3.656655
3.578419
1.021863
if not settings.PIAPI_STANDALONE: (plugIt, baseURI, _) = getPlugItObject(hproPk) else: global plugIt, baseURI try: (media, contentType, cache_control) = plugIt.getMedia(path) except Exception as e: report_backend_error(request, e, 'meta', hproPk) return gen...
def media(request, path, hproPk=None)
Ask the server for a media and return it to the client browser. Forward cache headers
4.55042
4.621881
0.984539
if not settings.PIAPI_STANDALONE or settings.PIAPI_REALUSERS: raise Http404 request.session['plugit-standalone-usermode'] = request.GET.get('mode') return HttpResponse('')
def setUser(request)
In standalone mode, change the current user
11.614317
10.4626
1.110079
if settings.PIAPI_STANDALONE: request.session['plugit-standalone-organame'] = request.GET.get('name') request.session['plugit-standalone-orgapk'] = request.GET.get('pk') else: (_, _, hproject) = getPlugItObject(hproPk) from organizations.models import Organization ...
def setOrga(request, hproPk=None)
Change the current orga
4.350682
4.292925
1.013454
if settings.PIAPI_STANDALONE: return True (_, _, hproject) = getPlugItObject(hproPk) if not hproject: return False if hproject.plugItApiKey is None or hproject.plugItApiKey == '': return False return hproject.plugItApiKey == key
def check_api_key(request, key, hproPk)
Check if an API key is valid
6.291482
6.178392
1.018304
if settings.PIAPI_STANDALONE: return main(request, '', hproPk) (plugIt, baseURI, hproject) = getPlugItObject(hproPk) if hproject.runURI: return HttpResponseRedirect(hproject.runURI) else: # Check if a custom url key is used if hasattr(hproject, 'plugItCustomUrlKey'...
def home(request, hproPk)
Route the request to runURI if defined otherwise go to plugIt
5.630435
4.374449
1.287118
if not check_api_key(request, key, hproPk): return HttpResponseForbidden return render_to_response('plugIt/api.html', {}, context_instance=RequestContext(request))
def api_home(request, key=None, hproPk=None)
Show the home page for the API with all methods
4.39108
4.610903
0.952326
if not check_api_key(request, key, hproPk): return HttpResponseForbidden if settings.PIAPI_STANDALONE: if not settings.PIAPI_REALUSERS: user = generate_user(pk=userPk) if user is None: return HttpResponseNotFound() else: user = g...
def api_user(request, userPk, key=None, hproPk=None)
Return information about an user
4.27604
4.233154
1.010131
if not check_api_key(request, key, hproPk): return HttpResponseForbidden # From UUID to Pk from users.models import TechUser user = get_object_or_404(TechUser, uuid=userUuid) (_, _, hproject) = getPlugItObject(hproPk) user.ebuio_member = hproject.isMemberRead(user) user.ebu...
def api_user_uuid(request, userUuid, key=None, hproPk=None)
Return information about an user based on uuid
5.547445
5.66873
0.978605
if not check_api_key(request, key, hproPk): return HttpResponseForbidden # From UUID to Pk from users.models import TechUser user = get_object_or_404(TechUser, pk=userPk) (_, _, hproject) = getPlugItObject(hproPk) retour = user.getActiveSubscriptionLabels(hproject) return ...
def api_subscriptions(request, userPk, key=None, hproPk=None)
Return information about an user based on uuid
6.468181
6.41182
1.00879
if not check_api_key(request, key, hproPk): return HttpResponseForbidden retour = {} if settings.PIAPI_STANDALONE: retour['pk'] = orgaPk if orgaPk == "-1": retour['name'] = 'EBU' retour['codops'] = 'zzebu' if orgaPk == "-2": retour[...
def api_orga(request, orgaPk, key=None, hproPk=None)
Return information about an organization
2.859855
2.860677
0.999713
if not check_api_key(request, key, hproPk): return HttpResponseForbidden if settings.PIAPI_STANDALONE: if not settings.PIAPI_REALUSERS: users = [generate_user(pk="-1"), generate_user(pk="-2"), generate_user(pk="-3")] else: users = DUser.object.all() els...
def api_get_project_members(request, key=None, hproPk=True)
Return the list of project members
4.739438
4.726064
1.00283
if not check_api_key(request, key, hproPk): return HttpResponseForbidden from users.models import TechGroup retour = [{ 'uuid': t.uuid, 'uid': t.uid, 'name': t.name, } for t in TechGroup.objects.filter(is_enabled=True)] return HttpResponse(json.dumps(retour),...
def api_techgroup_list(request, key, hproPk)
Return the list of techgroup
3.235031
3.249435
0.995567
if not check_api_key(request, key, hproPk): return HttpResponseForbidden # From UUID to Pk from users.models import TechUser user = get_object_or_404(TechUser, pk=userPk) retour = [t.uuid for t in user.techgroup_set.filter(is_enabled=True)] return HttpResponse(json.dumps(retour...
def api_user_techgroup_list(request, userPk, key, hproPk)
Return the list of techgroup of a user
3.808638
3.770152
1.010208
# If no EBUIO Mail settings have been set, then no e-mail shall be sent if settings.EBUIO_MAIL_SECRET_KEY and settings.EBUIO_MAIL_SECRET_HASH: headers = {} if key: from Crypto.Cipher import AES hash_key = hashlib.sha512(key + settings.EBUIO_MAIL_SECRET_HASH).hexdi...
def generic_send_mail(sender, dests, subject, message, key, origin='', html_message=False)
Generic mail sending function
3.758539
3.758812
0.999927
if not check_api_key(request, key, hproPk): return HttpResponseForbidden sender = request.POST.get('sender', settings.MAIL_SENDER) dests = request.POST.getlist('dests') subject = request.POST['subject'] message = request.POST['message'] html_message = request.POST.get('html_messag...
def api_send_mail(request, key=None, hproPk=None)
Send a email. Posts parameters are used
3.096747
3.140829
0.985965
if not check_api_key(request, key, hproPk): return HttpResponseForbidden list_orgas = [] if settings.PIAPI_STANDALONE: list_orgas = [{'id': -1, 'name': 'EBU', 'codops': 'ZZEBU'}, {'id': -2, 'name': 'RTS', 'codops': 'CHRTS'}, {'id': -3, 'nam...
def api_orgas(request, key=None, hproPk=None)
Return the list of organizations pk
3.93057
3.936598
0.998469
if not check_api_key(request, key, hproPk): return HttpResponseForbidden if settings.PIAPI_STANDALONE: return HttpResponse(json.dumps({'error': 'no-on-ebuio'}), content_type="application/json") (_, _, hproject) = getPlugItObject(hproPk) error = '' subject = request.POST.get...
def api_ebuio_forum(request, key=None, hproPk=None)
Create a topic on the forum of the ioproject. EBUIo only !
3.23913
3.121241
1.03777
# Check API key (in order to be sure that we have a valid one and that's correspond to the project if not check_api_key(request, key, hproPk): return HttpResponseForbidden if settings.PIAPI_STANDALONE: return HttpResponse(json.dumps({'error': 'no-on-ebuio'}), content_type="application...
def api_ebuio_forum_get_topics_by_tag_for_user(request, key=None, hproPk=None, tag=None, userPk=None)
Return the list of topics using the tag pk
5.277059
5.34351
0.987564
self._validate_state(state) params = {"term": term, "state": state, "postcode": postcode, "max_results": max_results or self.max_results} return self._make_request('/address/autoComplete', params)
def auto_complete(self, term, state=None, postcode=None, max_results=None)
Gets a list of addresses that begin with the given term.
3.412338
3.056962
1.116251
params = {"term": address_line} json = self._make_request('/address/getParsedAddress', params) if json is None: return None return Address.from_json(json)
def parse_address(self, address_line)
Parses the given address into it's individual address fields.
6.148277
5.202984
1.181683
params = {"term": address_line, "max_results": max_results or self.max_results} return self._make_request('/address/getSimilar', params)
def similar(self, address_line, max_results=None)
Gets a list of valid addresses that are similar to the given term, can be used to match invalid addresses to valid addresses.
4.077339
3.743573
1.089157
if self.connected: self.subscriber.on_connect_error( 'Already connected to "%s"' % self.address) return False self.address = address self.server_token = token self.ingame = False self.ws.settimeout(1) self.ws.connect('ws:...
def connect(self, address, token=None)
Connect the underlying websocket to the address, send a handshake and optionally a token packet. Returns `True` if connected, `False` if the connection failed. :param address: string, `IP:PORT` :param token: unique token, required by official servers, acquired thr...
3.438044
3.251871
1.057251