signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def get_mouse_button(window, button):
return _glfw.glfwGetMouseButton(window, button)<EOL>
Returns the last reported state of a mouse button for the specified window. Wrapper for: int glfwGetMouseButton(GLFWwindow* window, int button);
f3493:m51
def get_cursor_pos(window):
xpos_value = ctypes.c_double(<NUM_LIT:0.0>)<EOL>xpos = ctypes.pointer(xpos_value)<EOL>ypos_value = ctypes.c_double(<NUM_LIT:0.0>)<EOL>ypos = ctypes.pointer(ypos_value)<EOL>_glfw.glfwGetCursorPos(window, xpos, ypos)<EOL>return xpos_value.value, ypos_value.value<EOL>
Retrieves the last reported cursor position, relative to the client area of the window. Wrapper for: void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos);
f3493:m52
def set_cursor_pos(window, xpos, ypos):
_glfw.glfwSetCursorPos(window, xpos, ypos)<EOL>
Sets the position of the cursor, relative to the client area of the window. Wrapper for: void glfwSetCursorPos(GLFWwindow* window, double xpos, double ypos);
f3493:m53
def set_key_callback(window, cbfun):
window_addr = ctypes.cast(ctypes.pointer(window),<EOL>ctypes.POINTER(ctypes.c_long)).contents.value<EOL>if window_addr in _key_callback_repository:<EOL><INDENT>previous_callback = _key_callback_repository[window_addr]<EOL><DEDENT>else:<EOL><INDENT>previous_callback = None<EOL><DEDENT>if cbfun is None:<EOL><INDENT>cbfun...
Sets the key callback. Wrapper for: GLFWkeyfun glfwSetKeyCallback(GLFWwindow* window, GLFWkeyfun cbfun);
f3493:m54
def set_char_callback(window, cbfun):
window_addr = ctypes.cast(ctypes.pointer(window),<EOL>ctypes.POINTER(ctypes.c_long)).contents.value<EOL>if window_addr in _char_callback_repository:<EOL><INDENT>previous_callback = _char_callback_repository[window_addr]<EOL><DEDENT>else:<EOL><INDENT>previous_callback = None<EOL><DEDENT>if cbfun is None:<EOL><INDENT>cbf...
Sets the Unicode character callback. Wrapper for: GLFWcharfun glfwSetCharCallback(GLFWwindow* window, GLFWcharfun cbfun);
f3493:m55
def set_mouse_button_callback(window, cbfun):
window_addr = ctypes.cast(ctypes.pointer(window),<EOL>ctypes.POINTER(ctypes.c_long)).contents.value<EOL>if window_addr in _mouse_button_callback_repository:<EOL><INDENT>previous_callback = _mouse_button_callback_repository[window_addr]<EOL><DEDENT>else:<EOL><INDENT>previous_callback = None<EOL><DEDENT>if cbfun is None:...
Sets the mouse button callback. Wrapper for: GLFWmousebuttonfun glfwSetMouseButtonCallback(GLFWwindow* window, GLFWmousebuttonfun cbfun);
f3493:m56
def set_cursor_pos_callback(window, cbfun):
window_addr = ctypes.cast(ctypes.pointer(window),<EOL>ctypes.POINTER(ctypes.c_long)).contents.value<EOL>if window_addr in _cursor_pos_callback_repository:<EOL><INDENT>previous_callback = _cursor_pos_callback_repository[window_addr]<EOL><DEDENT>else:<EOL><INDENT>previous_callback = None<EOL><DEDENT>if cbfun is None:<EOL...
Sets the cursor position callback. Wrapper for: GLFWcursorposfun glfwSetCursorPosCallback(GLFWwindow* window, GLFWcursorposfun cbfun);
f3493:m57
def set_cursor_enter_callback(window, cbfun):
window_addr = ctypes.cast(ctypes.pointer(window),<EOL>ctypes.POINTER(ctypes.c_long)).contents.value<EOL>if window_addr in _cursor_enter_callback_repository:<EOL><INDENT>previous_callback = _cursor_enter_callback_repository[window_addr]<EOL><DEDENT>else:<EOL><INDENT>previous_callback = None<EOL><DEDENT>if cbfun is None:...
Sets the cursor enter/exit callback. Wrapper for: GLFWcursorenterfun glfwSetCursorEnterCallback(GLFWwindow* window, GLFWcursorenterfun cbfun);
f3493:m58
def set_scroll_callback(window, cbfun):
window_addr = ctypes.cast(ctypes.pointer(window),<EOL>ctypes.POINTER(ctypes.c_long)).contents.value<EOL>if window_addr in _scroll_callback_repository:<EOL><INDENT>previous_callback = _scroll_callback_repository[window_addr]<EOL><DEDENT>else:<EOL><INDENT>previous_callback = None<EOL><DEDENT>if cbfun is None:<EOL><INDENT...
Sets the scroll callback. Wrapper for: GLFWscrollfun glfwSetScrollCallback(GLFWwindow* window, GLFWscrollfun cbfun);
f3493:m59
def joystick_present(joy):
return _glfw.glfwJoystickPresent(joy)<EOL>
Returns whether the specified joystick is present. Wrapper for: int glfwJoystickPresent(int joy);
f3493:m60
def get_joystick_axes(joy):
count_value = ctypes.c_int(<NUM_LIT:0>)<EOL>count = ctypes.pointer(count_value)<EOL>result = _glfw.glfwGetJoystickAxes(joy, count)<EOL>return result, count_value.value<EOL>
Returns the values of all axes of the specified joystick. Wrapper for: const float* glfwGetJoystickAxes(int joy, int* count);
f3493:m61
def get_joystick_buttons(joy):
count_value = ctypes.c_int(<NUM_LIT:0>)<EOL>count = ctypes.pointer(count_value)<EOL>result = _glfw.glfwGetJoystickButtons(joy, count)<EOL>return result, count_value.value<EOL>
Returns the state of all buttons of the specified joystick. Wrapper for: const unsigned char* glfwGetJoystickButtons(int joy, int* count);
f3493:m62
def get_joystick_name(joy):
return _glfw.glfwGetJoystickName(joy)<EOL>
Returns the name of the specified joystick. Wrapper for: const char* glfwGetJoystickName(int joy);
f3493:m63
def set_clipboard_string(window, string):
_glfw.glfwSetClipboardString(window, _to_char_p(string))<EOL>
Sets the clipboard to the specified string. Wrapper for: void glfwSetClipboardString(GLFWwindow* window, const char* string);
f3493:m64
def get_clipboard_string(window):
return _glfw.glfwGetClipboardString(window)<EOL>
Retrieves the contents of the clipboard as a string. Wrapper for: const char* glfwGetClipboardString(GLFWwindow* window);
f3493:m65
def get_time():
return _glfw.glfwGetTime()<EOL>
Returns the value of the GLFW timer. Wrapper for: double glfwGetTime(void);
f3493:m66
def set_time(time):
_glfw.glfwSetTime(time)<EOL>
Sets the GLFW timer. Wrapper for: void glfwSetTime(double time);
f3493:m67
def make_context_current(window):
_glfw.glfwMakeContextCurrent(window)<EOL>
Makes the context of the specified window current for the calling thread. Wrapper for: void glfwMakeContextCurrent(GLFWwindow* window);
f3493:m68
def get_current_context():
return _glfw.glfwGetCurrentContext()<EOL>
Returns the window whose context is current on the calling thread. Wrapper for: GLFWwindow* glfwGetCurrentContext(void);
f3493:m69
def swap_buffers(window):
_glfw.glfwSwapBuffers(window)<EOL>
Swaps the front and back buffers of the specified window. Wrapper for: void glfwSwapBuffers(GLFWwindow* window);
f3493:m70
def swap_interval(interval):
_glfw.glfwSwapInterval(interval)<EOL>
Sets the swap interval for the current context. Wrapper for: void glfwSwapInterval(int interval);
f3493:m71
def extension_supported(extension):
return _glfw.glfwExtensionSupported(_to_char_p(extension))<EOL>
Returns whether the specified extension is available. Wrapper for: int glfwExtensionSupported(const char* extension);
f3493:m72
def get_proc_address(procname):
return _glfw.glfwGetProcAddress(_to_char_p(procname))<EOL>
Returns the address of the specified function for the current context. Wrapper for: GLFWglproc glfwGetProcAddress(const char* procname);
f3493:m73
def wrap(self, video_mode):
size, bits, self.refresh_rate = video_mode<EOL>self.width, self.height = size<EOL>self.red_bits, self.green_bits, self.blue_bits = bits<EOL>
Wraps a nested python sequence.
f3493:c2:m1
def unwrap(self):
size = self.width, self.height<EOL>bits = self.red_bits, self.green_bits, self.blue_bits<EOL>return size, bits, self.refresh_rate<EOL>
Returns a nested python sequence.
f3493:c2:m2
def wrap(self, gammaramp):
red, green, blue = gammaramp<EOL>size = min(len(red), len(green), len(blue))<EOL>array_type = ctypes.c_ushort*size<EOL>self.size = ctypes.c_uint(size)<EOL>self.red_array = array_type()<EOL>self.green_array = array_type()<EOL>self.blue_array = array_type()<EOL>for i in range(self.size):<EOL><INDENT>self.red_array[i] = i...
Wraps a nested python sequence.
f3493:c3:m1
def unwrap(self):
red = [self.red[i]/<NUM_LIT> for i in range(self.size)]<EOL>green = [self.green[i]/<NUM_LIT> for i in range(self.size)]<EOL>blue = [self.blue[i]/<NUM_LIT> for i in range(self.size)]<EOL>return red, green, blue<EOL>
Returns a nested python sequence.
f3493:c3:m2
def __init__(self, data, xmin=None, xmax=None, bins=<NUM_LIT:100>,<EOL>distributions=None, verbose=True, timeout=<NUM_LIT:30>):
self.timeout = timeout<EOL>self._data = None<EOL>self.distributions = distributions<EOL>if self.distributions == None:<EOL><INDENT>self.load_all_distributions()<EOL><DEDENT>self.bins = bins<EOL>self.verbose = verbose<EOL>self._alldata = np.array(data)<EOL>if xmin == None:<EOL><INDENT>self._xmin = self._alldata.min()<EO...
.. rubric:: Constructor :param list data: a numpy array or a list :param float xmin: if None, use the data minimum value, otherwise histogram and fits will be cut :param float xmax: if None, use the data maximum value, otherwise histogram and fits will be cut :pa...
f3507:c0:m0
def load_all_distributions(self):
distributions = []<EOL>for this in dir(scipy.stats):<EOL><INDENT>if "<STR_LIT>" in eval("<STR_LIT>" + this +"<STR_LIT:)>"):<EOL><INDENT>distributions.append(this)<EOL><DEDENT><DEDENT>self.distributions = distributions[:]<EOL>
Replace the :attr:`distributions` attribute with all scipy distributions
f3507:c0:m8
def hist(self):
_ = pylab.hist(self._data, bins=self.bins, density=True)<EOL>pylab.grid(True)<EOL>
Draw normed histogram of the data using :attr:`bins` .. plot:: >>> from scipy import stats >>> data = stats.gamma.rvs(2, loc=1.5, scale=2, size=20000) >>> # We then create the Fitter object >>> import fitter >>> fitter.Fitter(data).hist()
f3507:c0:m9
def fit(self):
for distribution in self.distributions:<EOL><INDENT>try:<EOL><INDENT>dist = eval("<STR_LIT>" + distribution)<EOL>param = self._timed_run(dist.fit, distribution, args=self._data)<EOL>pdf_fitted = dist.pdf(self.x, *param) <EOL>self.fitted_param[distribution] = param[:]<EOL>self.fitted_pdf[distribution] = pdf_fitted<EOL>s...
r"""Loop over distributions and find best parameter to fit the data for each When a distribution is fitted onto the data, we populate a set of dataframes: - :attr:`df_errors` :sum of the square errors between the data and the fitted distribution i.e., :math:`\sum_i \left( Y_...
f3507:c0:m10
def plot_pdf(self, names=None, Nbest=<NUM_LIT:5>, lw=<NUM_LIT:2>):
assert Nbest > <NUM_LIT:0><EOL>if Nbest > len(self.distributions):<EOL><INDENT>Nbest = len(self.distributions)<EOL><DEDENT>if isinstance(names, list):<EOL><INDENT>for name in names:<EOL><INDENT>pylab.plot(self.x, self.fitted_pdf[name], lw=lw, label=name)<EOL><DEDENT><DEDENT>elif names:<EOL><INDENT>pylab.plot(self.x, se...
Plots Probability density functions of the distributions :param str,list names: names can be a single distribution name, or a list of distribution names, or kept as None, in which case, the first Nbest distribution will be taken (default to best 5)
f3507:c0:m11
def get_best(self):
<EOL>name = self.df_errors.sort_values('<STR_LIT>').iloc[<NUM_LIT:0>].name<EOL>params = self.fitted_param[name]<EOL>return {name: params}<EOL>
Return best fitted distribution and its parameters a dictionary with one key (the distribution name) and its parameters
f3507:c0:m12
def summary(self, Nbest=<NUM_LIT:5>, lw=<NUM_LIT:2>, plot=True):
if plot:<EOL><INDENT>pylab.clf()<EOL>self.hist()<EOL>self.plot_pdf(Nbest=Nbest, lw=lw)<EOL>pylab.grid(True)<EOL><DEDENT>Nbest = min(Nbest, len(self.distributions))<EOL>try:<EOL><INDENT>names = self.df_errors.sort_values(<EOL>by="<STR_LIT>").index[<NUM_LIT:0>:Nbest]<EOL><DEDENT>except:<EOL><INDENT>names = self.df_errors...
Plots the distribution of the data and Nbest distribution
f3507:c0:m13
def _timed_run(self, func, distribution, args=(), kwargs={}, default=None):
class InterruptableThread(threading.Thread):<EOL><INDENT>def __init__(self):<EOL><INDENT>threading.Thread.__init__(self)<EOL>self.result = default<EOL>self.exc_info = (None, None, None)<EOL><DEDENT>def run(self):<EOL><INDENT>try:<EOL><INDENT>self.result = func(args, **kwargs)<EOL><DEDENT>except Exception as err:<EOL><I...
This function will spawn a thread and run the given function using the args, kwargs and return the given default value if the timeout is exceeded. http://stackoverflow.com/questions/492519/timeout-on-a-python-function-call
f3507:c0:m14
def lower_dict(d):
_d = {}<EOL>for k, v in d.items():<EOL><INDENT>try:<EOL><INDENT>_d[k.lower()] = v<EOL><DEDENT>except AttributeError:<EOL><INDENT>_d[k] = v<EOL><DEDENT><DEDENT>return _d<EOL>
Lower cases string keys in given dict.
f3510:m0
def urlparse(d, keys=None):
d = d.copy()<EOL>if keys is None:<EOL><INDENT>keys = d.keys()<EOL><DEDENT>for key in keys:<EOL><INDENT>d[key] = _urlparse(d[key])<EOL><DEDENT>return d<EOL>
Returns a copy of the given dictionary with url values parsed.
f3510:m1
def prefix(prefix):
d = {}<EOL>e = lower_dict(environ.copy())<EOL>prefix = prefix.lower()<EOL>for k, v in e.items():<EOL><INDENT>try:<EOL><INDENT>if k.startswith(prefix):<EOL><INDENT>k = k[len(prefix):]<EOL>d[k] = v<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return d<EOL>
Returns a dictionary of all environment variables starting with the given prefix, lower cased and stripped.
f3510:m2
def map(**kwargs):
d = {}<EOL>e = lower_dict(environ.copy())<EOL>for k, v in kwargs.items():<EOL><INDENT>d[k] = e.get(v.lower())<EOL><DEDENT>return d<EOL>
Returns a dictionary of the given keyword arguments mapped to their values from the environment, with input keys lower cased.
f3510:m3
@valid_path<EOL>def parse_tree_from_dict(node, locs):
d = dict()<EOL>for n, l in locs.items():<EOL><INDENT>try:<EOL><INDENT>if l[<NUM_LIT:1>] == '<STR_LIT:text>':<EOL><INDENT>d[n] = node.find(l[<NUM_LIT:0>]).text<EOL><DEDENT>elif l[<NUM_LIT:1>] == '<STR_LIT>':<EOL><INDENT>child = node.find(l[<NUM_LIT:0>]).getchildren()<EOL>if len(child) > <NUM_LIT:1>:<EOL><INDENT>raise Am...
Processes key locations. Parameters ---------- node: xml.etree.ElementTree.ElementTree.element Current node. locs: dict A dictionary mapping key to a tuple. The tuple can either be 2 or 3 elements long. The first element maps to the location in the current node. The seco...
f3521:m1
def xml_to_root(xml: Union[str, IO]) -> ElementTree.Element:
if isinstance(xml, str):<EOL><INDENT>if '<STR_LIT:<>' in xml:<EOL><INDENT>return ElementTree.fromstring(xml)<EOL><DEDENT>else:<EOL><INDENT>with open(xml) as fh:<EOL><INDENT>xml_to_root(fh)<EOL><DEDENT><DEDENT><DEDENT>tree = ElementTree.parse(xml)<EOL>return tree.getroot()<EOL>
Parse XML into an ElemeTree object. Parameters ---------- xml : str or file-like object A filename, file object or string version of xml can be passed. Returns ------- Elementree.Element
f3521:m2
def arguments():
DESCRIPTION = """<STR_LIT>"""<EOL>parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=Raw)<EOL>parser.add_argument("<STR_LIT>", dest="<STR_LIT:email>", action='<STR_LIT:store>', required=False, default=False,<EOL>help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", dest="<STR_LIT>", action='<STR...
Pulls in command line arguments.
f3522:m0
def take(n, iterable):
return list(islice(iterable, n))<EOL>
Return first *n* items of the iterable as a list. >>> take(3, range(10)) [0, 1, 2] >>> take(5, range(3)) [0, 1, 2] Effectively a short replacement for ``next`` based iterator consumption when you want more than one item, but less than the whole iterator. Copied from more-ite...
f3524:m0
def chunked(iterable, n):
return iter(partial(take, n, iter(iterable)), [])<EOL>
Break *iterable* into lists of length *n*: >>> list(chunked([1, 2, 3, 4, 5, 6], 3)) [[1, 2, 3], [4, 5, 6]] If the length of *iterable* is not evenly divisible by *n*, the last returned list will be shorter: >>> list(chunked([1, 2, 3, 4, 5, 6, 7, 8], 3)) [[1, 2, 3], [4, 5, 6], [7,...
f3524:m1
def esearch(database, query, userhistory=True, webenv=False, query_key=False, retstart=False, retmax=False,<EOL>api_key=False, email=False, **kwargs) -> Optional[EsearchResult]:
cleaned_query = urllib.parse.quote_plus(query, safe='<STR_LIT>')<EOL>url = BASE_URL + f'<STR_LIT>'<EOL>url = check_userhistory(userhistory, url)<EOL>url = check_webenv(webenv, url)<EOL>url = check_query_key(query_key, url)<EOL>url = check_retstart(retstart, url)<EOL>url = check_retmax(retmax, url)<EOL>url = check_api_k...
Search for a query using the Entrez ESearch API. Parameters ---------- database : str Entez database to search. query : str Query string userhistory : bool Tells API to return a WebEnV and query_key. webenv : str An Entrez WebEnv to use saved history. query_k...
f3525:m0
def epost(database, ids: List[str], webenv=False, api_key=False, email=False, **kwargs) -> Optional[EpostResult]:
url = BASE_URL + f'<STR_LIT>'<EOL>id = '<STR_LIT:U+002C>'.join(ids)<EOL>url_params = f'<STR_LIT>'<EOL>url_params = check_webenv(webenv, url_params)<EOL>url_params = check_api_key(api_key, url_params)<EOL>url_params = check_email(email, url_params)<EOL>resp = entrez_try_put_multiple_times(url, url_params, num_tries=<NUM...
Post IDs using the Entrez ESearch API. Parameters ---------- database : str Entez database to search. ids : list List of IDs to submit to the server. webenv : str An Entrez WebEnv to post ids to. api_key : str A users API key which allows more requests per second...
f3525:m1
def elink(db: str, dbfrom: str, ids=False, webenv=False, query_key=False, api_key=False, email=False,<EOL>**kwargs) -> Optional[ElinkResult]:
url = BASE_URL + f'<STR_LIT>'<EOL>url = check_webenv(webenv, url)<EOL>url = check_query_key(query_key, url)<EOL>url = check_api_key(api_key, url)<EOL>url = check_email(email, url)<EOL>if ids:<EOL><INDENT>if isinstance(ids, str):<EOL><INDENT>id = ids<EOL><DEDENT>else:<EOL><INDENT>id = '<STR_LIT:U+002C>'.join(ids)<EOL><D...
Get document summaries using the Entrez ESearch API. Parameters ---------- db : str Entez database to get ids from. dbfrom : str Entez database the provided ids are from. ids : list or str List of IDs to submit to the server. webenv : str An Entrez WebEnv to use ...
f3525:m2
def esummary(database: str, ids=False, webenv=False, query_key=False, count=False, retstart=False, retmax=False,<EOL>api_key=False, email=False, **kwargs) -> Optional[List[EsummaryResult]]:
url = BASE_URL + f'<STR_LIT>'<EOL>url = check_webenv(webenv, url)<EOL>url = check_query_key(query_key, url)<EOL>url = check_api_key(api_key, url)<EOL>url = check_email(email, url)<EOL>if ids:<EOL><INDENT>if isinstance(ids, str):<EOL><INDENT>id = ids<EOL><DEDENT>else:<EOL><INDENT>id = '<STR_LIT:U+002C>'.join(ids)<EOL><D...
Get document summaries using the Entrez ESearch API. Parameters ---------- database : str Entez database to search. ids : list or str List of IDs to submit to the server. webenv : str An Entrez WebEnv to use saved history. query_key : str An Entrez query_key to u...
f3525:m3
def efetch(database, ids=False, webenv=False, query_key=False, count=False, retstart=False, retmax=False,<EOL>rettype='<STR_LIT>', retmode='<STR_LIT>', api_key=False, email=False, **kwargs) -> str:
url = BASE_URL + f'<STR_LIT>'<EOL>url = check_webenv(webenv, url)<EOL>url = check_query_key(query_key, url)<EOL>url = check_api_key(api_key, url)<EOL>url = check_email(email, url)<EOL>if ids:<EOL><INDENT>if isinstance(ids, str):<EOL><INDENT>id = ids<EOL><DEDENT>else:<EOL><INDENT>id = '<STR_LIT:U+002C>'.join(ids)<EOL><D...
Get documents using the Entrez ESearch API.gg Parameters ---------- database : str Entez database to search. ids : list or str List of IDs to submit to the server. webenv : str An Entrez WebEnv to use saved history. query_key : str An Entrez query_key to use save...
f3525:m4
def entrez_sets_of_results(url, retstart=False, retmax=False, count=False) -> Optional[List[requests.Response]]:
if not retstart:<EOL><INDENT>retstart = <NUM_LIT:0><EOL><DEDENT>if not retmax:<EOL><INDENT>retmax = <NUM_LIT><EOL><DEDENT>if not count:<EOL><INDENT>count = retmax<EOL><DEDENT>retmax = <NUM_LIT> <EOL>while retstart < count:<EOL><INDENT>diff = count - retstart<EOL>if diff < <NUM_LIT>:<EOL><INDENT>retmax = diff<EOL><DEDE...
Gets sets of results back from Entrez. Entrez can only return 500 results at a time. This creates a generator that gets results by incrementing retstart and retmax. Parameters ---------- url : str The Entrez API url to use. retstart : int Return values starting at this index. ...
f3525:m14
def abspath(*args):
return os.path.join(PROJECT_ROOT, *args)<EOL>
convert relative paths to absolute paths relative to PROJECT_ROOT
f3532:m0
@task()<EOL>def ingest_csv(csv_data, message_set):
records = csv.DictReader(csv_data)<EOL>for line in records:<EOL><INDENT>for key in line:<EOL><INDENT>if key not in ["<STR_LIT>", "<STR_LIT>"] and line[key] != "<STR_LIT>":<EOL><INDENT>try:<EOL><INDENT>with transaction.atomic():<EOL><INDENT>message = Message()<EOL>message.message_set = message_set<EOL>message.sequence_n...
Expecting data in the following format: message_id,en,safe,af,safe,zu,safe,xh,safe,ve,safe,tn,safe,ts,safe,ss,safe,st,safe,nso,safe,nr,safe
f3540:m0
@task()<EOL>def ensure_one_subscription():
cursor = connection.cursor()<EOL>cursor.execute("<STR_LIT>")<EOL>affected = cursor.rowcount<EOL>vumi_fire_metric.delay(<EOL>metric="<STR_LIT>", value=affected, agg="<STR_LIT>")<EOL>return affected<EOL>
Fixes issues caused by upstream failures that lead to users having multiple active subscriptions Runs daily
f3540:m1
def _parse_args():
import argparse<EOL>parser = argparse.ArgumentParser(description='<STR_LIT>')<EOL>arg = parser.add_argument<EOL>arg('<STR_LIT>', '<STR_LIT>', type=float, help='<STR_LIT>')<EOL>arg('<STR_LIT>', '<STR_LIT>', choices=['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'])<EOL>arg('<STR_LIT>', '<STR_LIT>')<EOL>arg('<STR_LIT>', '<STR_LIT>...
Parse command line arguments.
f3546:m0
def _only_shifts(self, modifiers):
if not modifiers or len(modifiers) > <NUM_LIT:2>:<EOL><INDENT>return False<EOL><DEDENT>if len(modifiers) == <NUM_LIT:2>:<EOL><INDENT>return '<STR_LIT>' in modifiers and '<STR_LIT>' in modifiers<EOL><DEDENT>if len(modifiers) == <NUM_LIT:1>:<EOL><INDENT>return '<STR_LIT>' in modifiers or '<STR_LIT>' in modifiers<EOL><DED...
Check if modifiers pressed are only shifts
f3546:c0:m1
def _only_right_alt(self, modifiers):
if not modifiers or len(modifiers) > <NUM_LIT:1>:<EOL><INDENT>return False<EOL><DEDENT>return '<STR_LIT>' in modifiers<EOL>
Check if the only modifier pressed is right alt
f3546:c0:m2
def transform(self, keys):
key = keys['<STR_LIT>'][<NUM_LIT:0>]<EOL>modifiers = keys['<STR_LIT>']<EOL>try:<EOL><INDENT>if not modifiers:<EOL><INDENT>if key in self._letters or key in self._digits:<EOL><INDENT>res = key<EOL><DEDENT>elif key in self._command_keys:<EOL><INDENT>res = '<STR_LIT:<>' + key + '<STR_LIT:>>'<EOL><DEDENT>else:<EOL><INDENT>...
Apply Spanish layout to the pressed keys
f3546:c1:m1
def transform(self, keys):
key = keys['<STR_LIT>'][<NUM_LIT:0>]<EOL>modifiers = keys['<STR_LIT>']<EOL>try:<EOL><INDENT>if not modifiers:<EOL><INDENT>if key in self._letters or key in self._digits:<EOL><INDENT>res = key<EOL><DEDENT>elif key in self._command_keys:<EOL><INDENT>res = '<STR_LIT:<>' + key + '<STR_LIT:>>'<EOL><DEDENT>else:<EOL><INDENT>...
Apply brazilian br-abnt2 layout to the pressed keys
f3546:c2:m1
def transform(self, keys):
key = keys['<STR_LIT>'][<NUM_LIT:0>]<EOL>modifiers = keys['<STR_LIT>']<EOL>try:<EOL><INDENT>if not modifiers:<EOL><INDENT>if (key in self._letters<EOL>or key in self._digits<EOL>or key in self._layout['<STR_LIT>']):<EOL><INDENT>res = key<EOL><DEDENT>elif key in self._command_keys:<EOL><INDENT>res = '<STR_LIT:<>' + key ...
Apply English USA layout to the pressed keys
f3546:c3:m1
def get_keymap(self):
self._x11.XQueryKeymap(self._display, self._raw_keymap)<EOL>try:<EOL><INDENT>keyboard = [ord(byte) for byte in self._raw_keymap]<EOL><DEDENT>except TypeError:<EOL><INDENT>return None<EOL><DEDENT>return keyboard<EOL>
Returns X11 Keymap as a list of integers
f3546:c6:m1
def get_keys(self, keymap):
keys = dict(modifiers=[], regular=[])<EOL>for keymap_index, keymap_byte in enumerate(keymap):<EOL><INDENT>try:<EOL><INDENT>keymap_values = self._keymap_values_dict[keymap_index]<EOL><DEDENT>except KeyError:<EOL><INDENT>continue<EOL><DEDENT>for key, value in keymap_values.items():<EOL><INDENT>if not keymap_byte & key:<E...
Extract keys pressed from transformed keymap
f3546:c6:m2
def run(self):
while True:<EOL><INDENT>keymap = self._okeymap.get_keymap()<EOL>if keymap == self._last_keymap or not keymap:<EOL><INDENT>sleep(self._sleep_time)<EOL>continue<EOL><DEDENT>keys = self._okeymap.get_keys(keymap)<EOL>if (keys['<STR_LIT>']<EOL>and keys['<STR_LIT>'] != self._last_keys['<STR_LIT>']):<EOL><INDENT>if self._tran...
Main loop
f3546:c7:m1
def chk_col_numbers(line_num, num_cols, tax_id_col, id_col, symbol_col):
bad_col = '<STR_LIT>'<EOL>if tax_id_col >= num_cols:<EOL><INDENT>bad_col = '<STR_LIT>'<EOL><DEDENT>elif id_col >= num_cols:<EOL><INDENT>bad_col = '<STR_LIT>'<EOL><DEDENT>elif symbol_col >= num_cols:<EOL><INDENT>bad_col = '<STR_LIT>'<EOL><DEDENT>if bad_col:<EOL><INDENT>raise Exception(<EOL>'<STR_LIT>' %<EOL>(line_num, b...
Check that none of the input column numbers is out of range. (Instead of defining this function, we could depend on Python's built-in IndexError exception for this issue, but the IndexError exception wouldn't include line number information, which is helpful for users to find exactly which line is the culprit.)
f3552:m0
def import_gene_history(file_handle, tax_id, tax_id_col, id_col, symbol_col):
<EOL>if not tax_id or tax_id.isspace():<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>organism = Organism.objects.get(taxonomy_id=tax_id)<EOL><DEDENT>except Organism.DoesNotExist:<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>'<STR_LIT>' % tax_id)<EOL><DEDENT>if tax_id_col < <NUM_LIT:0> or id_col ...
Read input gene history file into the database. Note that the arguments tax_id_col, id_col and symbol_col have been converted into 0-based column indexes.
f3552:m1
def translate_genes(id_list=None, from_id=None, to_id=None, organism=None):
ids = set(id_list)<EOL>not_found = set()<EOL>from_ids = None <EOL>if organism is not None:<EOL><INDENT>gene_objects_manager = Gene.objects.filter(<EOL>organism__scientific_name=organism)<EOL><DEDENT>else:<EOL><INDENT>gene_objects_manager = Gene.objects<EOL><DEDENT>if (from_id == '<STR_LIT>'):<EOL><INDENT>int_list = []...
Pass a list of identifiers (id_list), the name of the database ('Entrez', 'Symbol', 'Standard name', 'Systematic name' or a loaded crossreference database) that you wish to translate from, and the name of the database that you wish to translate to.
f3557:m0
def wall_of_name(self):
names = []<EOL>if self.standard_name:<EOL><INDENT>names.append(self.standard_name)<EOL><DEDENT>if self.systematic_name:<EOL><INDENT>names.append(self.systematic_name)<EOL><DEDENT>names.extend([xref.xrid for xref in self.crossref_set.all()])<EOL>for i in range(len(names)):<EOL><INDENT>names[i] = re.sub(nonalpha, '<STR_L...
Appends identifiers for the different databases (such as Entrez id's) and returns them. Uses the CrossRef class below.
f3558:c0:m1
def save(self, *args, **kwargs):
empty_std_name = False<EOL>if not self.standard_name or self.standard_name.isspace():<EOL><INDENT>empty_std_name = True<EOL><DEDENT>empty_sys_name = False<EOL>if not self.systematic_name or self.systematic_name.isspace():<EOL><INDENT>empty_sys_name = True<EOL><DEDENT>if empty_std_name and empty_sys_name:<EOL><INDENT>ra...
Override save() method to make sure that standard_name and systematic_name won't be null or empty, or consist of only space characters (such as space, tab, new line, etc).
f3558:c0:m2
def save(self, *args, **kwargs):
if self.name == '<STR_LIT>':<EOL><INDENT>raise FieldError<EOL><DEDENT>else:<EOL><INDENT>return super(CrossRefDB, self).save(*args, **kwargs)<EOL><DEDENT>
Extends save() method of Django models to check that the database name is not left blank. Note: 'blank=False' is only checked at a form-validation-stage. A test using Fixtureless that tries to randomly create a CrossRefDB with an empty string name would unintentionally break the test.
f3558:c1:m0
def get_api_name(self):
if not ROOT_URLCONF:<EOL><INDENT>return None<EOL><DEDENT>proj_urls = __import__(ROOT_URLCONF)<EOL>url_members = inspect.getmembers(proj_urls.urls)<EOL>api_name = None<EOL>for k, v in url_members:<EOL><INDENT>if isinstance(v, Api):<EOL><INDENT>api_name = v.api_name<EOL><DEDENT><DEDENT>return api_name<EOL>
Utility function to get the name of the tastypie REST API in whatever Django project is using django-genes.
f3559:c4:m0
def create_many_genes(self, organism, num_genes):
<EOL>for i in range(num_genes):<EOL><INDENT>Gene.objects.create(entrezid=(i + <NUM_LIT:1>),<EOL>systematic_name="<STR_LIT>" + str(i + <NUM_LIT:1>),<EOL>standard_name="<STR_LIT>" + str(i + <NUM_LIT:1>),<EOL>organism=organism)<EOL><DEDENT>
Helper function to generate a large number of genes
f3559:c4:m1
def post_list(self, request, **kwargs):
<EOL>request.method = '<STR_LIT:GET>' <EOL>dispatch_request = convert_post_to_VERB(request, '<STR_LIT:GET>')<EOL>return self.dispatch('<STR_LIT:list>', dispatch_request, **kwargs)<EOL>
(Copied from implementation in https://github.com/greenelab/adage-server/blob/master/adage/analyze/api.py) Handle an incoming POST as a GET to work around URI length limitations
f3560:c0:m4
def __init__(self, asa_dir, loading_wait=<NUM_LIT:1>, encoding='<STR_LIT:utf-8>'):
self.jar = os.path.join(asa_dir, '<STR_LIT>' % ASA_VERSION)<EOL>os.chdir(asa_dir)<EOL>self.encoding = encoding<EOL>self.tempfile = tempfile.mkstemp()[<NUM_LIT:1>]<EOL>command = '<STR_LIT>' % (self.jar, self.tempfile)<EOL>self.asa = Popen(command, shell=True, stdin=PIPE, stdout=PIPE)<EOL>time.sleep(loading_wait)<EOL>
Params: asa_dir (str) : directory path of ASA's jar loading_wait (float) : time of initial loading (default 1.0) encoding (str) : character encoding (default utf-8)
f3563:c0:m0
def parse(self, sentence):
self.asa.stdin.write(sentence.encode(self.encoding) + b'<STR_LIT:\n>')<EOL>self.asa.stdin.flush()<EOL>result = []<EOL>while not result:<EOL><INDENT>with open(self.tempfile, '<STR_LIT:r>', encoding=self.encoding) as out:<EOL><INDENT>asa_return = out.read()<EOL><DEDENT>if asa_return and asa_return.splitlines()[-<NUM_LIT:...
Parse the sentence Param: sentence (str) Return: result (list of dict)
f3563:c0:m3
def create_oauth_client(app, name, **kwargs):
blueprint = Blueprint('<STR_LIT>', __name__, template_folder='<STR_LIT>')<EOL>default = dict(<EOL>consumer_key='<STR_LIT>',<EOL>consumer_secret='<STR_LIT>',<EOL>request_token_params={'<STR_LIT>': '<STR_LIT>'},<EOL>request_token_url=None,<EOL>access_token_method='<STR_LIT:POST>',<EOL>access_token_url='<STR_LIT>',<EOL>au...
Helper function to create a OAuth2 client to test an OAuth2 provider.
f3572:m3
def _(x):
return x<EOL>
Identity.
f3583:m0
def __init__(self, scope, *args, **kwargs):
super(ScopeDoesNotExists, self).__init__(*args, **kwargs)<EOL>self.scope = scope<EOL>
Initialize exception by storing invalid scope.
f3584:c1:m0
def __init__(self, errors=None, **kwargs):
super(JWTExtendedException, self).__init__(**kwargs)<EOL>if errors is not None:<EOL><INDENT>self.errors = errors<EOL><DEDENT>
Initialize JWTExtendedException.
f3584:c2:m0
def get_errors(self):
return [e.to_dict() for e in self.errors] if self.errors else None<EOL>
Get errors. :returns: A list containing a dictionary representing the errors.
f3584:c2:m1
def get_body(self, environ=None):
body = dict(<EOL>status=self.code,<EOL>message=self.description,<EOL>)<EOL>errors = self.get_errors()<EOL>if self.errors:<EOL><INDENT>body['<STR_LIT>'] = errors<EOL><DEDENT>return json.dumps(body)<EOL>
Get the request body.
f3584:c2:m2
def get_headers(self, environ=None):
return [('<STR_LIT:Content-Type>', '<STR_LIT:application/json>')]<EOL>
Get a list of headers.
f3584:c2:m3
def validate_redirect_uri(value):
sch, netloc, path, par, query, fra = urlparse(value)<EOL>if not (sch and netloc):<EOL><INDENT>raise InvalidRedirectURIError()<EOL><DEDENT>if sch != '<STR_LIT>':<EOL><INDENT>if '<STR_LIT::>' in netloc:<EOL><INDENT>netloc, port = netloc.split('<STR_LIT::>', <NUM_LIT:1>)<EOL><DEDENT>if not (netloc in ('<STR_LIT:localhost>...
Validate a redirect URI. Redirect URIs must be a valid URL and use https unless the host is localhost for which http is accepted. :param value: The redirect URI.
f3585:m0
def validate_scopes(value_list):
for value in value_list:<EOL><INDENT>if value not in current_oauth2server.scopes:<EOL><INDENT>raise ScopeDoesNotExists(value)<EOL><DEDENT><DEDENT>return True<EOL>
Validate if each element in a list is a registered scope. :param value_list: The list of scopes. :raises invenio_oauth2server.errors.ScopeDoesNotExists: The exception is raised if a scope is not registered. :returns: ``True`` if it's successfully validated.
f3585:m1
def __call__(self, form, field):
parsed = urlparse(field.data)<EOL>if current_app.debug and parsed.hostname == '<STR_LIT:localhost>':<EOL><INDENT>return<EOL><DEDENT>super(URLValidator, self).__call__(form=form, field=field)<EOL>
Check URL.
f3585:c0:m0
@oauth2.usergetter<EOL>def get_user(email, password, *args, **kwargs):
user = datastore.find_user(email=email)<EOL>if user and user.active and verify_password(password, user.password):<EOL><INDENT>return user<EOL><DEDENT>
Get user for grant type password. Needed for grant type 'password'. Note, grant type password is by default disabled. :param email: User email. :param password: Password. :returns: The user instance or ``None``.
f3586:m0
@oauth2.tokengetter<EOL>def get_token(access_token=None, refresh_token=None):
if access_token:<EOL><INDENT>t = Token.query.filter_by(access_token=access_token).first()<EOL>if t and t.is_personal and t.user.active:<EOL><INDENT>t.expires = datetime.utcnow() + timedelta(<EOL>seconds=int(current_app.config.get(<EOL>'<STR_LIT>'<EOL>))<EOL>)<EOL><DEDENT><DEDENT>elif refresh_token:<EOL><INDENT>t = Toke...
Load an access token. Add support for personal access tokens compared to flask-oauthlib. If the access token is ``None``, it looks for the refresh token. :param access_token: The access token. (Default: ``None``) :param refresh_token: The refresh token. (Default: ``None``) :returns: The token inst...
f3586:m1
@oauth2.clientgetter<EOL>def get_client(client_id):
client = Client.query.get(client_id)<EOL>if client and client.user.active:<EOL><INDENT>return client<EOL><DEDENT>
Load the client. Needed for grant_type client_credentials. Add support for OAuth client_credentials access type, with user inactivation support. :param client_id: The client ID. :returns: The client instance or ``None``.
f3586:m2
@oauth2.tokensetter<EOL>def save_token(token, request, *args, **kwargs):
<EOL>user = request.user if request.user else current_user<EOL>token.update(user={'<STR_LIT:id>': user.get_id()})<EOL>if email_scope.id in token.scopes:<EOL><INDENT>token['<STR_LIT:user>'].update(<EOL>email=user.email,<EOL>email_verified=user.confirmed_at is not None,<EOL>)<EOL><DEDENT>tokens = Token.query.filter_by(<E...
Token persistence. :param token: A dictionary with the token data. :param request: The request instance. :returns: A :class:`invenio_oauth2server.models.Token` instance.
f3586:m3
@oauth2.after_request<EOL>def login_oauth2_user(valid, oauth):
if valid:<EOL><INDENT>oauth.user.login_via_oauth2 = True<EOL>_request_ctx_stack.top.user = oauth.user<EOL>identity_changed.send(current_app._get_current_object(),<EOL>identity=Identity(oauth.user.id))<EOL><DEDENT>return valid, oauth<EOL>
Log in a user after having been verified.
f3586:m4
def lazy_result(f):
@wraps(f)<EOL>def decorated(ctx, param, value):<EOL><INDENT>return LocalProxy(lambda: f(ctx, param, value))<EOL><DEDENT>return decorated<EOL>
Decorate function to return LazyProxy.
f3587:m0
@lazy_result<EOL>def process_user(ctx, param, value):
if value:<EOL><INDENT>if value.isdigit():<EOL><INDENT>user = User.query.get(str(value))<EOL><DEDENT>else:<EOL><INDENT>user = User.query.filter(User.email == value).one_or_none()<EOL><DEDENT>return user<EOL><DEDENT>
Return a user if exists.
f3587:m1
@lazy_result<EOL>def process_scopes(ctx, param, values):
validate_scopes(values)<EOL>return values<EOL>
Return a user if exists.
f3587:m2
@click.group()<EOL>def tokens():
OAuth2 server token commands.
f3587:m3
@tokens.command('<STR_LIT>')<EOL>@click.option('<STR_LIT>', '<STR_LIT>', required=True)<EOL>@click.option(<EOL>'<STR_LIT>', '<STR_LIT>', required=True, callback=process_user,<EOL>help='<STR_LIT>')<EOL>@click.option(<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', multiple=True, callback=process_scopes)<EOL>@click.option('<S...
token = Token.create_personal(<EOL>name, user.id, scopes=scopes, is_internal=internal)<EOL>db.session.commit()<EOL>click.secho(token.access_token, fg='<STR_LIT>')<EOL>
Create a personal OAuth token.
f3587:m4
@tokens.command('<STR_LIT>')<EOL>@click.option('<STR_LIT>', '<STR_LIT>')<EOL>@click.option('<STR_LIT>', '<STR_LIT>', callback=process_user, help='<STR_LIT>')<EOL>@click.option('<STR_LIT>', '<STR_LIT>', is_flag=True)<EOL>@click.option('<STR_LIT>', is_flag=True)<EOL>@with_appcontext<EOL>def tokens_delete(name=None, user=...
if not (name or user) and not read_access_token:<EOL><INDENT>click.get_current_context().fail(<EOL>'<STR_LIT>')<EOL><DEDENT>if name and user:<EOL><INDENT>client = Client.query.filter(<EOL>Client.user_id == user.id,<EOL>Client.name == name,<EOL>Client.is_internal.is_(True)).one()<EOL>token = Token.query.filter(<EOL>Toke...
Delete a personal OAuth token.
f3587:m5
def verify_oauth_token_and_set_current_user():
for func in oauth2._before_request_funcs:<EOL><INDENT>func()<EOL><DEDENT>if not hasattr(request, '<STR_LIT>') or not request.oauth:<EOL><INDENT>scopes = []<EOL>try:<EOL><INDENT>valid, req = oauth2.verify_request(scopes)<EOL><DEDENT>except ValueError:<EOL><INDENT>abort(<NUM_LIT>, '<STR_LIT>')<EOL><DEDENT>for func in oau...
Verify OAuth token and set current user on request stack. This function should be used **only** on REST application. .. code-block:: python app.before_request(verify_oauth_token_and_set_current_user)
f3588:m0
def __init__(self, app, entry_point_group=None):
self.app = app<EOL>self.scopes = {}<EOL>oauth2.init_app(app)<EOL>if app.config['<STR_LIT>'] == '<STR_LIT>' and app.config.get(<EOL>'<STR_LIT>'):<EOL><INDENT>from redis import from_url as redis_from_url<EOL>app.config.setdefault(<EOL>'<STR_LIT>',<EOL>redis_from_url(app.config['<STR_LIT>'])<EOL>)<EOL><DEDENT>bind_cache_g...
Initialize state.
f3588:c0:m0
def scope_choices(self, exclude_internal=True):
return [<EOL>(k, scope) for k, scope in sorted(self.scopes.items())<EOL>if not exclude_internal or not scope.is_internal<EOL>]<EOL>
Return list of scope choices. :param exclude_internal: Exclude internal scopes or not. (Default: ``True``) :returns: A list of tuples (id, scope).
f3588:c0:m1
def register_scope(self, scope):
if not isinstance(scope, Scope):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>assert scope.id not in self.scopes<EOL>self.scopes[scope.id] = scope<EOL>
Register a scope. :param scope: A :class:`invenio_oauth2server.models.Scope` instance.
f3588:c0:m2
def load_entry_point_group(self, entry_point_group):
for ep in pkg_resources.iter_entry_points(group=entry_point_group):<EOL><INDENT>self.register_scope(ep.load())<EOL><DEDENT>
Load actions from an entry point group. :param entry_point_group: The entrypoint group name to load plugins.
f3588:c0:m3
def load_obj_or_import_string(self, value):
imp = self.app.config.get(value)<EOL>if isinstance(imp, six.string_types):<EOL><INDENT>return import_string(imp)<EOL><DEDENT>elif imp:<EOL><INDENT>return imp<EOL><DEDENT>
Import string or return object. :params value: Import path or class object to instantiate. :params default: Default object to return if the import fails. :returns: The imported object.
f3588:c0:m4