repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
bdcht/grandalf
grandalf/layouts.py
Layer._meanvalueattr
python
def _meanvalueattr(self,v): sug = self.layout if not self.prevlayer(): return sug.grx[v].bar bars = [sug.grx[x].bar for x in self._neighbors(v)] return sug.grx[v].bar if len(bars)==0 else float(sum(bars))/len(bars)
find new position of vertex v according to adjacency in prevlayer. position is given by the mean value of adjacent positions. experiments show that meanvalue heuristic performs better than median.
train
https://github.com/bdcht/grandalf/blob/b0a604afa79e5201eebe5feb56ae5ec7afc07b95/grandalf/layouts.py#L211-L220
[ "def prevlayer(self):\n return self.lower if self.layout.dirv==+1 else self.upper\n" ]
class Layer(list): """ Layer is where Sugiyama layout organises vertices in hierarchical lists. The placement of a vertex is done by the Sugiyama class, but it highly relies on the *ordering* of vertices in each layer to reduce crossings. This ordering depends on the neighbors found in the upper or ...
bdcht/grandalf
grandalf/layouts.py
Layer._medianindex
python
def _medianindex(self,v): assert self.prevlayer()!=None N = self._neighbors(v) g=self.layout.grx pos = [g[x].pos for x in N] lp = len(pos) if lp==0: return [] pos.sort() pos = pos[::self.layout.dirh] i,j = divmod(lp-1,2) return [pos[i]] if ...
find new position of vertex v according to adjacency in layer l+dir. position is given by the median value of adjacent positions. median heuristic is proven to achieve at most 3 times the minimum of crossings (while barycenter achieve in theory the order of |V|)
train
https://github.com/bdcht/grandalf/blob/b0a604afa79e5201eebe5feb56ae5ec7afc07b95/grandalf/layouts.py#L222-L238
null
class Layer(list): """ Layer is where Sugiyama layout organises vertices in hierarchical lists. The placement of a vertex is done by the Sugiyama class, but it highly relies on the *ordering* of vertices in each layer to reduce crossings. This ordering depends on the neighbors found in the upper or ...
bdcht/grandalf
grandalf/layouts.py
Layer._neighbors
python
def _neighbors(self,v): assert self.layout.dag dirv = self.layout.dirv grxv = self.layout.grx[v] try: #(cache) return grxv.nvs[dirv] except AttributeError: grxv.nvs={-1:v.N(-1),+1:v.N(+1)} if grxv.dummy: return grxv.nvs[dirv] # v is...
neighbors refer to upper/lower adjacent nodes. Note that v.N() provides neighbors of v in the graph, while this method provides the Vertex and DummyVertex adjacent to v in the upper or lower layer (depending on layout.dirv state).
train
https://github.com/bdcht/grandalf/blob/b0a604afa79e5201eebe5feb56ae5ec7afc07b95/grandalf/layouts.py#L240-L263
null
class Layer(list): """ Layer is where Sugiyama layout organises vertices in hierarchical lists. The placement of a vertex is done by the Sugiyama class, but it highly relies on the *ordering* of vertices in each layer to reduce crossings. This ordering depends on the neighbors found in the upper or ...
bdcht/grandalf
grandalf/layouts.py
Layer._crossings
python
def _crossings(self): g=self.layout.grx P=[] for v in self: P.append([g[x].pos for x in self._neighbors(v)]) for i,p in enumerate(P): candidates = sum(P[i+1:],[]) for j,e in enumerate(p): p[j] = len(filter((lambda nx:nx<e), candidates))...
counts (inefficently but at least accurately) the number of crossing edges between layer l and l+dirv. P[i][j] counts the number of crossings from j-th edge of vertex i. The total count of crossings is the sum of flattened P: x = sum(sum(P,[]))
train
https://github.com/bdcht/grandalf/blob/b0a604afa79e5201eebe5feb56ae5ec7afc07b95/grandalf/layouts.py#L265-L282
null
class Layer(list): """ Layer is where Sugiyama layout organises vertices in hierarchical lists. The placement of a vertex is done by the Sugiyama class, but it highly relies on the *ordering* of vertices in each layer to reduce crossings. This ordering depends on the neighbors found in the upper or ...
bdcht/grandalf
grandalf/layouts.py
Layer._cc
python
def _cc(self): g=self.layout.grx P=[] for v in self: P.extend(sorted([g[x].pos for x in self._neighbors(v)])) # count inversions in P: s = [] count = 0 for i,p in enumerate(P): j = bisect(s,p) if j<i: count += (i-j) ...
implementation of the efficient bilayer cross counting by insert-sort (see Barth & Mutzel paper "Simple and Efficient Bilayer Cross Counting")
train
https://github.com/bdcht/grandalf/blob/b0a604afa79e5201eebe5feb56ae5ec7afc07b95/grandalf/layouts.py#L284-L300
[ "def _neighbors(self,v):\n \"\"\"\n neighbors refer to upper/lower adjacent nodes.\n Note that v.N() provides neighbors of v in the graph, while\n this method provides the Vertex and DummyVertex adjacent to v in the\n upper or lower layer (depending on layout.dirv state).\n \"\"\"\n assert self...
class Layer(list): """ Layer is where Sugiyama layout organises vertices in hierarchical lists. The placement of a vertex is done by the Sugiyama class, but it highly relies on the *ordering* of vertices in each layer to reduce crossings. This ordering depends on the neighbors found in the upper or ...
bdcht/grandalf
grandalf/layouts.py
SugiyamaLayout.init_all
python
def init_all(self,roots=None,inverted_edges=None,optimize=False): if self.initdone: return # For layered sugiyama algorithm, the input graph must be acyclic, # so we must provide a list of root nodes and a list of inverted edges. if roots==None: roots = [v for v in self.g.sV ...
initializes the layout algorithm by computing roots (unless provided), inverted edges (unless provided), vertices ranks and creates all dummy vertices and layers. Parameters: roots (list[Vertex]): set *root* vertices (layer 0) inverted_ed...
train
https://github.com/bdcht/grandalf/blob/b0a604afa79e5201eebe5feb56ae5ec7afc07b95/grandalf/layouts.py#L378-L404
[ "def E(self,cond=None):\n E = self.sE\n if cond is None: cond=(lambda x:True)\n for e in E:\n if cond(e):\n yield e\n", "def get_scs_with_feedback(self,roots=None):\n from sys import getrecursionlimit,setrecursionlimit\n limit=getrecursionlimit()\n N=self.norm()+10\n if N>l...
class SugiyamaLayout(object): """ The Sugiyama layout is the traditional "layered" graph layout called *dot* in graphviz. This layout is quite efficient but heavily relies on drawing heuristics. Adaptive drawing is limited to extending the leaves only, but since the algorithm is quite fast red...
bdcht/grandalf
grandalf/layouts.py
SugiyamaLayout.draw
python
def draw(self,N=1.5): while N>0.5: for (l,mvmt) in self.ordering_step(): pass N = N-1 if N>0: for (l,mvmt) in self.ordering_step(oneway=True): pass self.setxy() self.draw_edges()
compute every node coordinates after converging to optimal ordering by N rounds, and finally perform the edge routing.
train
https://github.com/bdcht/grandalf/blob/b0a604afa79e5201eebe5feb56ae5ec7afc07b95/grandalf/layouts.py#L406-L418
[ "def ordering_step(self,oneway=False):\n \"\"\"iterator that computes all vertices ordering in their layers\n (one layer after the other from top to bottom, to top again unless\n oneway is True).\n \"\"\"\n self.dirv=-1\n crossings = 0\n for l in self.layers:\n mvmt = l.order()\n ...
class SugiyamaLayout(object): """ The Sugiyama layout is the traditional "layered" graph layout called *dot* in graphviz. This layout is quite efficient but heavily relies on drawing heuristics. Adaptive drawing is limited to extending the leaves only, but since the algorithm is quite fast red...
bdcht/grandalf
grandalf/layouts.py
SugiyamaLayout.rank_all
python
def rank_all(self,roots,optimize=False): self._edge_inverter() r = [x for x in self.g.sV if (len(x.e_in())==0 and x not in roots)] self._rank_init(roots+r) if optimize: self._rank_optimize() self._edge_inverter()
Computes rank of all vertices. add provided roots to rank 0 vertices, otherwise update ranking from provided roots. The initial rank is based on precedence relationships, optimal ranking may be derived from network flow (simplex).
train
https://github.com/bdcht/grandalf/blob/b0a604afa79e5201eebe5feb56ae5ec7afc07b95/grandalf/layouts.py#L461-L472
[ "def _edge_inverter(self):\n for e in self.alt_e:\n x,y = e.v\n e.v = (y,x)\n self.dag = not self.dag\n if self.dag:\n for e in self.g.degenerated_edges:\n e.detach()\n self.g.sE.remove(e)\n else:\n for e in self.g.degenerated_edges:\n self.g....
class SugiyamaLayout(object): """ The Sugiyama layout is the traditional "layered" graph layout called *dot* in graphviz. This layout is quite efficient but heavily relies on drawing heuristics. Adaptive drawing is limited to extending the leaves only, but since the algorithm is quite fast red...
bdcht/grandalf
grandalf/layouts.py
SugiyamaLayout._rank_init
python
def _rank_init(self,unranked): assert self.dag scan = {} # set rank of unranked based on its in-edges vertices ranks: while len(unranked)>0: l = [] for v in unranked: self.setrank(v) # mark out-edges has scan-able: f...
Computes rank of provided unranked list of vertices and all their children. A vertex will be asign a rank when all its inward edges have been *scanned*. When a vertex is asigned a rank, its outward edges are marked *scanned*.
train
https://github.com/bdcht/grandalf/blob/b0a604afa79e5201eebe5feb56ae5ec7afc07b95/grandalf/layouts.py#L474-L493
[ "def setrank(self,v):\n \"\"\"set rank value for vertex v and add it to the corresponding layer.\n The Layer is created if it is the first vertex with this rank.\n \"\"\"\n assert self.dag\n r=max([self.grx[x].rank for x in v.N(-1)]+[-1])+1\n self.grx[v].rank=r\n # add it to its layer:\n ...
class SugiyamaLayout(object): """ The Sugiyama layout is the traditional "layered" graph layout called *dot* in graphviz. This layout is quite efficient but heavily relies on drawing heuristics. Adaptive drawing is limited to extending the leaves only, but since the algorithm is quite fast red...
bdcht/grandalf
grandalf/layouts.py
SugiyamaLayout._rank_optimize
python
def _rank_optimize(self): assert self.dag for l in reversed(self.layers): for v in l: gv = self.grx[v] for x in v.N(-1): if all((self.grx[y].rank>=gv.rank for y in x.N(+1))): gx = self.grx[x] s...
optimize ranking by pushing long edges toward lower layers as much as possible. see other interersting network flow solver to minimize total edge length (http://jgaa.info/accepted/2005/EiglspergerSiebenhallerKaufmann2005.9.3.pdf)
train
https://github.com/bdcht/grandalf/blob/b0a604afa79e5201eebe5feb56ae5ec7afc07b95/grandalf/layouts.py#L495-L509
null
class SugiyamaLayout(object): """ The Sugiyama layout is the traditional "layered" graph layout called *dot* in graphviz. This layout is quite efficient but heavily relies on drawing heuristics. Adaptive drawing is limited to extending the leaves only, but since the algorithm is quite fast red...
bdcht/grandalf
grandalf/layouts.py
SugiyamaLayout.setrank
python
def setrank(self,v): assert self.dag r=max([self.grx[x].rank for x in v.N(-1)]+[-1])+1 self.grx[v].rank=r # add it to its layer: try: self.layers[r].append(v) except IndexError: assert r==len(self.layers) self.layers.append(Layer([v]))
set rank value for vertex v and add it to the corresponding layer. The Layer is created if it is the first vertex with this rank.
train
https://github.com/bdcht/grandalf/blob/b0a604afa79e5201eebe5feb56ae5ec7afc07b95/grandalf/layouts.py#L512-L524
null
class SugiyamaLayout(object): """ The Sugiyama layout is the traditional "layered" graph layout called *dot* in graphviz. This layout is quite efficient but heavily relies on drawing heuristics. Adaptive drawing is limited to extending the leaves only, but since the algorithm is quite fast red...
bdcht/grandalf
grandalf/layouts.py
SugiyamaLayout.dummyctrl
python
def dummyctrl(self,r,ctrl): dv = DummyVertex(r) dv.view.w,dv.view.h=self.dw,self.dh self.grx[dv] = dv dv.ctrl = ctrl ctrl[r] = dv self.layers[r].append(dv) return dv
creates a DummyVertex at rank r inserted in the ctrl dict of the associated edge and layer. Arguments: r (int): rank value ctrl (dict): the edge's control vertices Returns: DummyVertex : the created DummyVertex.
train
https://github.com/bdcht/grandalf/blob/b0a604afa79e5201eebe5feb56ae5ec7afc07b95/grandalf/layouts.py#L526-L543
null
class SugiyamaLayout(object): """ The Sugiyama layout is the traditional "layered" graph layout called *dot* in graphviz. This layout is quite efficient but heavily relies on drawing heuristics. Adaptive drawing is limited to extending the leaves only, but since the algorithm is quite fast red...
bdcht/grandalf
grandalf/layouts.py
SugiyamaLayout.setdummies
python
def setdummies(self,e): v0,v1 = e.v r0,r1 = self.grx[v0].rank,self.grx[v1].rank if r0>r1: assert e in self.alt_e v0,v1 = v1,v0 r0,r1 = r1,r0 if (r1-r0)>1: # "dummy vertices" are stored in the edge ctrl dict, # keyed by their ran...
creates and defines all needed dummy vertices for edge e.
train
https://github.com/bdcht/grandalf/blob/b0a604afa79e5201eebe5feb56ae5ec7afc07b95/grandalf/layouts.py#L545-L561
[ "def dummyctrl(self,r,ctrl):\n \"\"\"creates a DummyVertex at rank r inserted in the ctrl dict\n of the associated edge and layer.\n\n Arguments:\n r (int): rank value\n ctrl (dict): the edge's control vertices\n\n Returns:\n DummyVertex : the created DummyVertex.\n ...
class SugiyamaLayout(object): """ The Sugiyama layout is the traditional "layered" graph layout called *dot* in graphviz. This layout is quite efficient but heavily relies on drawing heuristics. Adaptive drawing is limited to extending the leaves only, but since the algorithm is quite fast red...
bdcht/grandalf
grandalf/layouts.py
SugiyamaLayout.draw_step
python
def draw_step(self): ostep = self.ordering_step() for s in ostep: self.setxy() self.draw_edges() yield s
iterator that computes all vertices coordinates and edge routing after just one step (one layer after the other from top to bottom to top). Purely inefficient ! Use it only for "animation" or debugging purpose.
train
https://github.com/bdcht/grandalf/blob/b0a604afa79e5201eebe5feb56ae5ec7afc07b95/grandalf/layouts.py#L563-L572
[ "def ordering_step(self,oneway=False):\n \"\"\"iterator that computes all vertices ordering in their layers\n (one layer after the other from top to bottom, to top again unless\n oneway is True).\n \"\"\"\n self.dirv=-1\n crossings = 0\n for l in self.layers:\n mvmt = l.order()\n ...
class SugiyamaLayout(object): """ The Sugiyama layout is the traditional "layered" graph layout called *dot* in graphviz. This layout is quite efficient but heavily relies on drawing heuristics. Adaptive drawing is limited to extending the leaves only, but since the algorithm is quite fast red...
bdcht/grandalf
grandalf/layouts.py
SugiyamaLayout.ordering_step
python
def ordering_step(self,oneway=False): self.dirv=-1 crossings = 0 for l in self.layers: mvmt = l.order() crossings += mvmt yield (l,mvmt) if oneway or (crossings == 0): return self.dirv=+1 while l: mvmt = l.order(...
iterator that computes all vertices ordering in their layers (one layer after the other from top to bottom, to top again unless oneway is True).
train
https://github.com/bdcht/grandalf/blob/b0a604afa79e5201eebe5feb56ae5ec7afc07b95/grandalf/layouts.py#L574-L591
null
class SugiyamaLayout(object): """ The Sugiyama layout is the traditional "layered" graph layout called *dot* in graphviz. This layout is quite efficient but heavily relies on drawing heuristics. Adaptive drawing is limited to extending the leaves only, but since the algorithm is quite fast red...
bdcht/grandalf
grandalf/layouts.py
SugiyamaLayout.setxy
python
def setxy(self): self._edge_inverter() self._detect_alignment_conflicts() inf = float('infinity') # initialize vertex coordinates attributes: for l in self.layers: for v in l: self.grx[v].root = v self.grx[v].align = v ...
computes all vertex coordinates (x,y) using an algorithm by Brandes & Kopf.
train
https://github.com/bdcht/grandalf/blob/b0a604afa79e5201eebe5feb56ae5ec7afc07b95/grandalf/layouts.py#L593-L626
[ "def _edge_inverter(self):\n for e in self.alt_e:\n x,y = e.v\n e.v = (y,x)\n self.dag = not self.dag\n if self.dag:\n for e in self.g.degenerated_edges:\n e.detach()\n self.g.sE.remove(e)\n else:\n for e in self.g.degenerated_edges:\n self.g....
class SugiyamaLayout(object): """ The Sugiyama layout is the traditional "layered" graph layout called *dot* in graphviz. This layout is quite efficient but heavily relies on drawing heuristics. Adaptive drawing is limited to extending the leaves only, but since the algorithm is quite fast red...
bdcht/grandalf
grandalf/layouts.py
SugiyamaLayout._detect_alignment_conflicts
python
def _detect_alignment_conflicts(self): curvh = self.dirvh # save current dirvh value self.dirvh=0 self.conflicts = [] for L in self.layers: last = len(L)-1 prev = L.prevlayer() if not prev: continue k0=0 k1_init=len(prev)-1 ...
mark conflicts between edges: inner edges are edges between dummy nodes type 0 is regular crossing regular (or sharing vertex) type 1 is inner crossing regular (targeted crossings) type 2 is inner crossing inner (avoided by reduce_crossings phase)
train
https://github.com/bdcht/grandalf/blob/b0a604afa79e5201eebe5feb56ae5ec7afc07b95/grandalf/layouts.py#L628-L658
null
class SugiyamaLayout(object): """ The Sugiyama layout is the traditional "layered" graph layout called *dot* in graphviz. This layout is quite efficient but heavily relies on drawing heuristics. Adaptive drawing is limited to extending the leaves only, but since the algorithm is quite fast red...
bdcht/grandalf
grandalf/layouts.py
SugiyamaLayout._coord_vertical_alignment
python
def _coord_vertical_alignment(self): dirh,dirv = self.dirh,self.dirv g = self.grx for l in self.layers[::-dirv]: if not l.prevlayer(): continue r=None for vk in l[::dirh]: for m in l._medianindex(vk): # take the median node ...
performs vertical alignment according to current dirvh internal state.
train
https://github.com/bdcht/grandalf/blob/b0a604afa79e5201eebe5feb56ae5ec7afc07b95/grandalf/layouts.py#L660-L682
null
class SugiyamaLayout(object): """ The Sugiyama layout is the traditional "layered" graph layout called *dot* in graphviz. This layout is quite efficient but heavily relies on drawing heuristics. Adaptive drawing is limited to extending the leaves only, but since the algorithm is quite fast red...
bdcht/grandalf
grandalf/layouts.py
SugiyamaLayout.draw_edges
python
def draw_edges(self): for e in self.g.E(): if hasattr(e,'view'): l=[] r0,r1 = None,None if e in self.ctrls: D = self.ctrls[e] r0,r1 = self.grx[e.v[0]].rank,self.grx[e.v[1]].rank if r0<r1: ...
Basic edge routing applied only for edges with dummy points. Enhanced edge routing can be performed by using the apropriate *route_with_xxx* functions from :ref:routing_ in the edges' view.
train
https://github.com/bdcht/grandalf/blob/b0a604afa79e5201eebe5feb56ae5ec7afc07b95/grandalf/layouts.py#L755-L778
[ "def E(self,cond=None):\n E = self.sE\n if cond is None: cond=(lambda x:True)\n for e in E:\n if cond(e):\n yield e\n" ]
class SugiyamaLayout(object): """ The Sugiyama layout is the traditional "layered" graph layout called *dot* in graphviz. This layout is quite efficient but heavily relies on drawing heuristics. Adaptive drawing is limited to extending the leaves only, but since the algorithm is quite fast red...
Morrolan/surrealism
surrealism.py
show_faults
python
def show_faults(): cursor = CONN.cursor() query = "select fau_id, fault from surfaults where fau_is_valid = 'y' order by fau_id asc" cursor.execute(query) result = cursor.fetchall() return result
Return all valid/active faults ordered by ID to allow the user to pick and choose. :return: List of Tuples where the Tuple elements are: (fault id, fault template)
train
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L71-L82
null
#!/usr/bin/env python ############################################################################# # surrealism.py - Surreal sentence and error message generator # Copyright (C) 2014 Ian Havelock # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene...
Morrolan/surrealism
surrealism.py
show_sentences
python
def show_sentences(): cursor = CONN.cursor() query = "select sen_id, sentence from sursentences where sen_is_valid = 'y' order by sen_id asc" cursor.execute(query) result = cursor.fetchall() response_dict = {} for row in result: response_dict[row[0]] = row[1] return response_dict
Return all valid/active sentences ordered by ID to allow the user to pick and choose. :return: Dict containing the sentence ID as the key and the sentence structure as the value.
train
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L94-L111
null
#!/usr/bin/env python ############################################################################# # surrealism.py - Surreal sentence and error message generator # Copyright (C) 2014 Ian Havelock # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene...
Morrolan/surrealism
surrealism.py
get_fault
python
def get_fault(fault_id=None): counts = __get_table_limits() result = None id_ = 0 try: if isinstance(fault_id, int): id_ = fault_id elif isinstance(fault_id, float): print("""ValueError: Floating point number detected. Rounding number to 0 dec...
Retrieve a randomly-generated error message as a unicode string. :param fault_id: Allows you to optionally specify an integer representing the fault_id from the database table. This allows you to retrieve a specific fault each time, albeit with different keywords.
train
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L185-L229
[ "def __get_table_limits():\n \"\"\"Here we simply take a count of each of the database tables so we know our\n upper limits for our random number calls then return a dictionary of them \n to the calling function...\"\"\"\n\n table_counts = {\n 'max_adjectives': None,\n 'max_names': None,\n...
#!/usr/bin/env python ############################################################################# # surrealism.py - Surreal sentence and error message generator # Copyright (C) 2014 Ian Havelock # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene...
Morrolan/surrealism
surrealism.py
get_sentence
python
def get_sentence(sentence_id=None): counts = __get_table_limits() result = None id_ = 0 try: if isinstance(sentence_id, int): id_ = sentence_id elif isinstance(sentence_id, float): print("""ValueError: Floating point number detected. Rounding ...
Retrieve a randomly-generated sentence as a unicode string. :param sentence_id: Allows you to optionally specify an integer representing the sentence_id from the database table. This allows you to retrieve a specific sentence each time, albeit with different keywords.
train
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L237-L282
[ "def __get_table_limits():\n \"\"\"Here we simply take a count of each of the database tables so we know our\n upper limits for our random number calls then return a dictionary of them \n to the calling function...\"\"\"\n\n table_counts = {\n 'max_adjectives': None,\n 'max_names': None,\n...
#!/usr/bin/env python ############################################################################# # surrealism.py - Surreal sentence and error message generator # Copyright (C) 2014 Ian Havelock # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene...
Morrolan/surrealism
surrealism.py
__get_sentence
python
def __get_sentence(counts, sentence_id=None): # First of all we need a cursor and a query to retrieve our ID's cursor = CONN.cursor() check_query = "select sen_id from sursentences" # Now we fetch the result of the query and save it into check_result cursor.execute(check_query) check_result = ...
Let's fetch a random sentence that we then need to substitute bits of... @ :param counts: :param sentence_id:
train
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L327-L364
null
#!/usr/bin/env python ############################################################################# # surrealism.py - Surreal sentence and error message generator # Copyright (C) 2014 Ian Havelock # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene...
Morrolan/surrealism
surrealism.py
__get_verb
python
def __get_verb(counts): cursor = CONN.cursor() check_query = "select verb_id from surverbs" cursor.execute(check_query) check_result = cursor.fetchall() id_list = [] for row in check_result: id_list.append(row[0]) rand = random.randint(1, counts['max_verb']) while rand not i...
Let's fetch a VERB :param counts:
train
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L367-L392
null
#!/usr/bin/env python ############################################################################# # surrealism.py - Surreal sentence and error message generator # Copyright (C) 2014 Ian Havelock # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene...
Morrolan/surrealism
surrealism.py
__get_table_limits
python
def __get_table_limits(): table_counts = { 'max_adjectives': None, 'max_names': None, 'max_nouns': None, 'max_sentences': None, 'max_faults': None, 'max_verbs': None } cursor = CONN.cursor() cursor.execute('SELECT count(*) FROM suradjs') table_count...
Here we simply take a count of each of the database tables so we know our upper limits for our random number calls then return a dictionary of them to the calling function...
train
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L478-L518
null
#!/usr/bin/env python ############################################################################# # surrealism.py - Surreal sentence and error message generator # Copyright (C) 2014 Ian Havelock # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene...
Morrolan/surrealism
surrealism.py
__process_sentence
python
def __process_sentence(sentence_tuple, counts): sentence = sentence_tuple[2] # now we start replacing words one type at a time... sentence = __replace_verbs(sentence, counts) sentence = __replace_nouns(sentence, counts) sentence = ___replace_adjective_maybe(sentence, counts) sentence = __re...
pull the actual sentence from the tuple (tuple contains additional data such as ID) :param _sentence_tuple: :param counts:
train
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L521-L559
[ "def __replace_verbs(sentence, counts):\n \"\"\"Lets find and replace all instances of #VERB\n :param _sentence:\n :param counts:\n \"\"\"\n\n if sentence is not None:\n while sentence.find('#VERB') != -1:\n sentence = sentence.replace('#VERB', str(__get_verb(counts)), 1)\n\n ...
#!/usr/bin/env python ############################################################################# # surrealism.py - Surreal sentence and error message generator # Copyright (C) 2014 Ian Havelock # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene...
Morrolan/surrealism
surrealism.py
__replace_verbs
python
def __replace_verbs(sentence, counts): if sentence is not None: while sentence.find('#VERB') != -1: sentence = sentence.replace('#VERB', str(__get_verb(counts)), 1) if sentence.find('#VERB') == -1: return sentence return sentence else: return sen...
Lets find and replace all instances of #VERB :param _sentence: :param counts:
train
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L562-L576
null
#!/usr/bin/env python ############################################################################# # surrealism.py - Surreal sentence and error message generator # Copyright (C) 2014 Ian Havelock # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene...
Morrolan/surrealism
surrealism.py
__replace_nouns
python
def __replace_nouns(sentence, counts): if sentence is not None: while sentence.find('#NOUN') != -1: sentence = sentence.replace('#NOUN', str(__get_noun(counts)), 1) if sentence.find('#NOUN') == -1: return sentence return sentence else: return se...
Lets find and replace all instances of #NOUN :param _sentence: :param counts:
train
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L579-L594
null
#!/usr/bin/env python ############################################################################# # surrealism.py - Surreal sentence and error message generator # Copyright (C) 2014 Ian Havelock # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene...
Morrolan/surrealism
surrealism.py
___replace_adjective_maybe
python
def ___replace_adjective_maybe(sentence, counts): random_decision = random.randint(0, 1) if sentence is not None: while sentence.find('#ADJECTIVE_MAYBE') != -1: if random_decision % 2 == 0: sentence = sentence.replace('#ADJECTIVE_MAYBE', ...
Lets find and replace all instances of #ADJECTIVE_MAYBE :param _sentence: :param counts:
train
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L597-L619
null
#!/usr/bin/env python ############################################################################# # surrealism.py - Surreal sentence and error message generator # Copyright (C) 2014 Ian Havelock # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene...
Morrolan/surrealism
surrealism.py
__replace_adjective
python
def __replace_adjective(sentence, counts): if sentence is not None: while sentence.find('#ADJECTIVE') != -1: sentence = sentence.replace('#ADJECTIVE', str(__get_adjective(counts)), 1) if sentence.find('#ADJECTIVE') == -1: r...
Lets find and replace all instances of #ADJECTIVE :param _sentence: :param counts:
train
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L622-L638
null
#!/usr/bin/env python ############################################################################# # surrealism.py - Surreal sentence and error message generator # Copyright (C) 2014 Ian Havelock # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene...
Morrolan/surrealism
surrealism.py
__replace_names
python
def __replace_names(sentence, counts): if sentence is not None: while sentence.find('#NAME') != -1: sentence = sentence.replace('#NAME', str(__get_name(counts)), 1) if sentence.find('#NAME') == -1: return sentence return sentence else: return se...
Lets find and replace all instances of #NAME :param _sentence: :param counts:
train
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L641-L656
null
#!/usr/bin/env python ############################################################################# # surrealism.py - Surreal sentence and error message generator # Copyright (C) 2014 Ian Havelock # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene...
Morrolan/surrealism
surrealism.py
__replace_an
python
def __replace_an(sentence): if sentence is not None: while sentence.find('#AN') != -1: an_index = sentence.find('#AN') if an_index > -1: an_index += 4 if sentence[an_index] in 'aeiouAEIOU': sentence = sentence.replace('#AN', str(...
Lets find and replace all instances of #AN This is a little different, as this depends on whether the next word starts with a vowel or a consonant. :param _sentence:
train
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L659-L683
null
#!/usr/bin/env python ############################################################################# # surrealism.py - Surreal sentence and error message generator # Copyright (C) 2014 Ian Havelock # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene...
Morrolan/surrealism
surrealism.py
__replace_random
python
def __replace_random(sentence): sub_list = None choice = None if sentence is not None: while sentence.find('#RANDOM') != -1: random_index = sentence.find('#RANDOM') start_index = sentence.find('#RANDOM') + 8 end_index = sentence.find(']') if sente...
Lets find and replace all instances of #RANDOM :param _sentence:
train
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L686-L716
null
#!/usr/bin/env python ############################################################################# # surrealism.py - Surreal sentence and error message generator # Copyright (C) 2014 Ian Havelock # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene...
Morrolan/surrealism
surrealism.py
__replace_repeat
python
def __replace_repeat(sentence): ######### USE SENTENCE_ID 47 for testing! repeat_dict = {} if sentence is not None: while sentence.find('#DEFINE_REPEAT') != -1: begin_index = sentence.find('#DEFINE_REPEAT') start_index = begin_index + 15 end_index = sentence.f...
Allows the use of repeating random-elements such as in the 'Ten green bottles' type sentences. :param sentence:
train
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L719-L760
null
#!/usr/bin/env python ############################################################################# # surrealism.py - Surreal sentence and error message generator # Copyright (C) 2014 Ian Havelock # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene...
Morrolan/surrealism
surrealism.py
__replace_capitalise
python
def __replace_capitalise(sentence): if sentence is not None: while sentence.find('#CAPITALISE') != -1: cap_index = _sentence.find('#CAPITALISE') part1 = sentence[:cap_index] part2 = sentence[cap_index + 12:cap_index + 13] part3 = sentence[cap_index + 13:] ...
here we replace all instances of #CAPITALISE and cap the next word. ############ #NOTE: Buggy as hell, as it doesn't account for words that are already #capitalized ############ :param _sentence:
train
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L763-L790
null
#!/usr/bin/env python ############################################################################# # surrealism.py - Surreal sentence and error message generator # Copyright (C) 2014 Ian Havelock # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene...
Morrolan/surrealism
surrealism.py
__replace_capall
python
def __replace_capall(sentence): # print "\nReplacing CAPITALISE: " if sentence is not None: while sentence.find('#CAPALL') != -1: # _cap_index = _sentence.find('#CAPALL') sentence = sentence.upper() sentence = sentence.replace('#CAPALL ', '', 1) if sentenc...
here we replace all instances of #CAPALL and cap the entire sentence. Don't believe that CAPALL is buggy anymore as it forces all uppercase OK? :param _sentence:
train
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L793-L811
null
#!/usr/bin/env python ############################################################################# # surrealism.py - Surreal sentence and error message generator # Copyright (C) 2014 Ian Havelock # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene...
Morrolan/surrealism
surrealism.py
__check_spaces
python
def __check_spaces(sentence): # We have to run the process multiple times: # Once to search for all spaces, and check if there are adjoining spaces; # The second time to check for 2 spaces after sentence-ending characters such as . and ! and ? if sentence is not None: words = sentence.spli...
Here we check to see that we have the correct number of spaces in the correct locations. :param _sentence: :return:
train
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L814-L841
null
#!/usr/bin/env python ############################################################################# # surrealism.py - Surreal sentence and error message generator # Copyright (C) 2014 Ian Havelock # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene...
jonbretman/jinja-to-js
jinja_to_js/__init__.py
option
python
def option(current_kwargs, **kwargs): tmp_kwargs = dict((key, current_kwargs.get(key)) for key, value in kwargs.items()) current_kwargs.update(kwargs) yield current_kwargs.update(tmp_kwargs)
Context manager for temporarily setting a keyword argument and then restoring it to whatever it was before.
train
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L105-L114
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals import contextlib import json import re import os from os import path from jinja2 import Environment, FileSystemLoader, nodes import six OPERANDS = { 'eq': '===', 'ne': '!==', 'lt': ' < ', 'gt': ' > ', 'lteq': ' <= ', 'gteq': '...
jonbretman/jinja-to-js
jinja_to_js/__init__.py
is_method_call
python
def is_method_call(node, method_name): if not isinstance(node, nodes.Call): return False if isinstance(node.node, nodes.Getattr): # e.g. foo.bar() method = node.node.attr elif isinstance(node.node, nodes.Name): # e.g. bar() method = node.node.name elif isinsta...
Returns True if `node` is a method call for `method_name`. `method_name` can be either a string or an iterable of strings.
train
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L117-L144
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals import contextlib import json import re import os from os import path from jinja2 import Environment, FileSystemLoader, nodes import six OPERANDS = { 'eq': '===', 'ne': '!==', 'lt': ' < ', 'gt': ' > ', 'lteq': ' <= ', 'gteq': '...
jonbretman/jinja-to-js
jinja_to_js/__init__.py
is_loop_helper
python
def is_loop_helper(node): return hasattr(node, 'node') and isinstance(node.node, nodes.Name) and node.node.name == 'loop'
Returns True is node is a loop helper e.g. {{ loop.index }} or {{ loop.first }}
train
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L147-L151
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals import contextlib import json import re import os from os import path from jinja2 import Environment, FileSystemLoader, nodes import six OPERANDS = { 'eq': '===', 'ne': '!==', 'lt': ' < ', 'gt': ' > ', 'lteq': ' <= ', 'gteq': '...
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS.get_output
python
def get_output(self): # generate the JS function string template_function = TEMPLATE_WRAPPER.format( function_name=self.js_function_name, template_code=self.output.getvalue() ).strip() # get the correct module format template module_format = JS_MODULE_FOR...
Returns the generated JavaScript code. Returns: str
train
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L251-L268
null
class JinjaToJS(object): def __init__(self, template_root, template_name, js_module_format=None, runtime_path='jinja-to-js', include_prefix='', include_ext='', child_blocks=None, ...
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._get_depencency_var_name
python
def _get_depencency_var_name(self, dependency): for dep_path, var_name in self.dependencies: if dep_path == dependency: return var_name
Returns the variable name assigned to the given dependency or None if the dependency has not yet been registered. Args: dependency (str): Thet dependency that needs to be imported. Returns: str or None
train
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L270-L283
null
class JinjaToJS(object): def __init__(self, template_root, template_name, js_module_format=None, runtime_path='jinja-to-js', include_prefix='', include_ext='', child_blocks=None, ...
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._add_dependency
python
def _add_dependency(self, dependency, var_name=None): if var_name is None: var_name = next(self.temp_var_names) # Don't add duplicate dependencies if (dependency, var_name) not in self.dependencies: self.dependencies.append((dependency, var_name)) return var_name
Adds the given dependency and returns the variable name to use to access it. If `var_name` is not given then a random one will be created. Args: dependency (str): var_name (str, optional): Returns: str
train
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L285-L302
null
class JinjaToJS(object): def __init__(self, template_root, template_name, js_module_format=None, runtime_path='jinja-to-js', include_prefix='', include_ext='', child_blocks=None, ...
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._process_extends
python
def _process_extends(self, node, **kwargs): # find all the blocks in this template for b in self.ast.find_all(nodes.Block): # if not already in `child_blocks` then this is the first time a # block with this name has been encountered. if b.name not in self.child_bloc...
Processes an extends block e.g. `{% extends "some/template.jinja" %}`
train
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L312-L347
null
class JinjaToJS(object): def __init__(self, template_root, template_name, js_module_format=None, runtime_path='jinja-to-js', include_prefix='', include_ext='', child_blocks=None, ...
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._process_block
python
def _process_block(self, node, **kwargs): # check if this node already has a 'super_block' attribute if not hasattr(node, 'super_block'): # since it doesn't it must be the last block in the inheritance chain node.super_block = None # see if there has been a child b...
Processes a block e.g. `{% block my_block %}{% endblock %}`
train
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L349-L381
null
class JinjaToJS(object): def __init__(self, template_root, template_name, js_module_format=None, runtime_path='jinja-to-js', include_prefix='', include_ext='', child_blocks=None, ...
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._process_output
python
def _process_output(self, node, **kwargs): for n in node.nodes: self._process_node(n, **kwargs)
Processes an output node, which will contain things like `Name` and `TemplateData` nodes.
train
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L383-L388
null
class JinjaToJS(object): def __init__(self, template_root, template_name, js_module_format=None, runtime_path='jinja-to-js', include_prefix='', include_ext='', child_blocks=None, ...
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._process_templatedata
python
def _process_templatedata(self, node, **_): # escape double quotes value = re.sub('"', r'\\"', node.data) # escape new lines value = re.sub('\n', r'\\n', value) # append value to the result self.output.write('__result += "' + value + '";')
Processes a `TemplateData` node, this is just a bit of as-is text to be written to the output.
train
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L390-L403
null
class JinjaToJS(object): def __init__(self, template_root, template_name, js_module_format=None, runtime_path='jinja-to-js', include_prefix='', include_ext='', child_blocks=None, ...
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._process_name
python
def _process_name(self, node, **kwargs): with self._interpolation(): with self._python_bool_wrapper(**kwargs): if node.name not in self.stored_names and node.ctx != 'store': self.output.write(self.context_name) self.output.write('.') ...
Processes a `Name` node. Some examples of `Name` nodes: {{ foo }} -> 'foo' is a Name {% if foo }} -> 'foo' is a Name
train
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L405-L422
null
class JinjaToJS(object): def __init__(self, template_root, template_name, js_module_format=None, runtime_path='jinja-to-js', include_prefix='', include_ext='', child_blocks=None, ...
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._process_getattr
python
def _process_getattr(self, node, **kwargs): with self._interpolation(): with self._python_bool_wrapper(**kwargs) as new_kwargs: if is_loop_helper(node): self._process_loop_helper(node, **new_kwargs) else: self._process_node(nod...
Processes a `GetAttr` node. e.g. {{ foo.bar }}
train
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L424-L436
null
class JinjaToJS(object): def __init__(self, template_root, template_name, js_module_format=None, runtime_path='jinja-to-js', include_prefix='', include_ext='', child_blocks=None, ...
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._process_getitem
python
def _process_getitem(self, node, **kwargs): with self._interpolation(): with self._python_bool_wrapper(**kwargs) as new_kwargs: self._process_node(node.node, **new_kwargs) if isinstance(node.arg, nodes.Slice): self.output.write('.slice(') ...
Processes a `GetItem` node e.g. {{ foo["bar"] }}
train
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L438-L467
null
class JinjaToJS(object): def __init__(self, template_root, template_name, js_module_format=None, runtime_path='jinja-to-js', include_prefix='', include_ext='', child_blocks=None, ...
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._process_for
python
def _process_for(self, node, **kwargs): # since a for loop can introduce new names into the context # we need to remember the ones that existed outside the loop previous_stored_names = self.stored_names.copy() with self._execution(): self.output.write('__runtime.each(') ...
Processes a for loop. e.g. {% for number in numbers %} {{ number }} {% endfor %} {% for key, value in somemap.items() %} {{ key }} -> {{ value }} {% %}
train
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L469-L531
null
class JinjaToJS(object): def __init__(self, template_root, template_name, js_module_format=None, runtime_path='jinja-to-js', include_prefix='', include_ext='', child_blocks=None, ...
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._process_if
python
def _process_if(self, node, execute_end=None, **kwargs): with self._execution(): self.output.write('if') self.output.write('(') with option(kwargs, use_python_bool_wrapper=True): self._process_node(node.test, **kwargs) self.output.write(')') ...
Processes an if block e.g. `{% if foo %} do something {% endif %}`
train
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L533-L586
null
class JinjaToJS(object): def __init__(self, template_root, template_name, js_module_format=None, runtime_path='jinja-to-js', include_prefix='', include_ext='', child_blocks=None, ...
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._process_math
python
def _process_math(self, node, math_operator=None, function=None, **kwargs): with self._interpolation(): if function: self.output.write(function) self.output.write('(') self._process_node(node.left, **kwargs) self.output.write(math_operator) ...
Processes a math node e.g. `Div`, `Sub`, `Add`, `Mul` etc... If `function` is provided the expression is wrapped in a call to that function.
train
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L1010-L1026
null
class JinjaToJS(object): def __init__(self, template_root, template_name, js_module_format=None, runtime_path='jinja-to-js', include_prefix='', include_ext='', child_blocks=None, ...
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._process_loop_helper
python
def _process_loop_helper(self, node, **kwargs): if node.attr == LOOP_HELPER_INDEX: self.output.write('(arguments[1] + 1)') elif node.attr == LOOP_HELPER_INDEX_0: self.output.write('arguments[1]') elif node.attr == LOOP_HELPER_FIRST: self.output.write('(argume...
Processes a loop helper e.g. {{ loop.first }} or {{ loop.index }}
train
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L1028-L1042
null
class JinjaToJS(object): def __init__(self, template_root, template_name, js_module_format=None, runtime_path='jinja-to-js', include_prefix='', include_ext='', child_blocks=None, ...
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._execution
python
def _execution(self): did_start_executing = False if self.state == STATE_DEFAULT: did_start_executing = True self.state = STATE_EXECUTING def close(): if did_start_executing and self.state == STATE_EXECUTING: self.state = STATE_DEFAULT ...
Context manager for executing some JavaScript inside a template.
train
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L1054-L1070
null
class JinjaToJS(object): def __init__(self, template_root, template_name, js_module_format=None, runtime_path='jinja-to-js', include_prefix='', include_ext='', child_blocks=None, ...
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._scoped_variables
python
def _scoped_variables(self, nodes_list, **kwargs): tmp_vars = [] for node in nodes_list: is_assign_node = isinstance(node, nodes.Assign) name = node.target.name if is_assign_node else node.name # create a temp variable name tmp_var = next(self.temp_var_...
Context manager for creating scoped variables defined by the nodes in `nodes_list`. These variables will be added to the context, and when the context manager exits the context object will be restored to it's previous state.
train
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L1094-L1133
null
class JinjaToJS(object): def __init__(self, template_root, template_name, js_module_format=None, runtime_path='jinja-to-js', include_prefix='', include_ext='', child_blocks=None, ...
michaelbrooks/twitter-monitor
twitter_monitor/listener.py
JsonStreamListener.on_status_withheld
python
def on_status_withheld(self, status_id, user_id, countries): logger.info('Status %s withheld for user %s', status_id, user_id) return True
Called when a status is withheld
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/listener.py#L91-L94
null
class JsonStreamListener(StreamListener): """ This extends the Tweepy StreamListener to avoid closing the streaming connection when certain bad events occur. Also skips construction of Tweepy's "Status" object since you might use your own class anyway. Just leaves it a parsed JSON object. Ext...
michaelbrooks/twitter-monitor
twitter_monitor/listener.py
JsonStreamListener.on_disconnect
python
def on_disconnect(self, code, stream_name, reason): logger.error('Disconnect message: %s %s %s', code, stream_name, reason) return True
Called when a disconnect is received
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/listener.py#L101-L104
null
class JsonStreamListener(StreamListener): """ This extends the Tweepy StreamListener to avoid closing the streaming connection when certain bad events occur. Also skips construction of Tweepy's "Status" object since you might use your own class anyway. Just leaves it a parsed JSON object. Ext...
michaelbrooks/twitter-monitor
twitter_monitor/listener.py
JsonStreamListener.on_error
python
def on_error(self, status_code): logger.error('Twitter returned error code %s', status_code) self.error = status_code return False
Called when a non-200 status code is returned
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/listener.py#L110-L114
null
class JsonStreamListener(StreamListener): """ This extends the Tweepy StreamListener to avoid closing the streaming connection when certain bad events occur. Also skips construction of Tweepy's "Status" object since you might use your own class anyway. Just leaves it a parsed JSON object. Ext...
michaelbrooks/twitter-monitor
twitter_monitor/listener.py
JsonStreamListener.on_exception
python
def on_exception(self, exception): logger.error('Exception from stream!', exc_info=True) self.streaming_exception = exception
An exception occurred in the streaming thread
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/listener.py#L121-L124
null
class JsonStreamListener(StreamListener): """ This extends the Tweepy StreamListener to avoid closing the streaming connection when certain bad events occur. Also skips construction of Tweepy's "Status" object since you might use your own class anyway. Just leaves it a parsed JSON object. Ext...
michaelbrooks/twitter-monitor
twitter_monitor/checker.py
TermChecker.check
python
def check(self): new_tracking_terms = self.update_tracking_terms() terms_changed = False # any deleted terms? if self._tracking_terms_set > new_tracking_terms: logging.debug("Some tracking terms removed") terms_changed = True # any added terms? ...
Checks if the list of tracked terms has changed. Returns True if changed, otherwise False.
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/checker.py#L33-L57
[ "def update_tracking_terms(self):\n \"\"\"\n Retrieve the current set of tracked terms from wherever it is stored.\n Subclasses may check in files, databases, etc...\n\n Should return a set of strings.\n \"\"\"\n return set(['#afakehashtag'])\n" ]
class TermChecker(object): """ Responsible for managing the current set of tracked terms and checking for updates. This is intended to be extended. """ def __init__(self): self._tracking_terms_set = set() def update_tracking_terms(self): """ Retrieve the current s...
michaelbrooks/twitter-monitor
twitter_monitor/checker.py
FileTermChecker.update_tracking_terms
python
def update_tracking_terms(self): import codecs with codecs.open(self.filename,"r", encoding='utf8') as input: # read all the lines lines = input.readlines() # build a set of terms new_terms = set() for line in lines: line = lin...
Terms must be one-per-line. Blank lines will be skipped.
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/checker.py#L75-L92
null
class FileTermChecker(TermChecker): """ Checks for tracked terms in a file. """ def __init__(self, filename): super(FileTermChecker, self).__init__() self.filename = filename
michaelbrooks/twitter-monitor
twitter_monitor/basic_stream.py
launch_debugger
python
def launch_debugger(frame, stream=None): d = {'_frame': frame} # Allow access to frame object. d.update(frame.f_globals) # Unless shadowed by global d.update(frame.f_locals) import code, traceback i = code.InteractiveConsole(d) message = "Signal received : entering python shell.\nTraceback:...
Interrupt running process, and provide a python prompt for interactive debugging.
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L75-L90
null
""" A simple streaming helper that takes minimal configuration as arguments and starts a stream to stdout. """ import os import signal import logging import time import json import tweepy from .listener import JsonStreamListener from .checker import FileTermChecker from .stream import DynamicTwitterStream logger = l...
michaelbrooks/twitter-monitor
twitter_monitor/basic_stream.py
set_debug_listener
python
def set_debug_listener(stream): def debugger(sig, frame): launch_debugger(frame, stream) if hasattr(signal, 'SIGUSR1'): signal.signal(signal.SIGUSR1, debugger) else: logger.warn("Cannot set SIGUSR1 signal for debug mode.")
Break into a debugger if receives the SIGUSR1 signal
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L93-L102
null
""" A simple streaming helper that takes minimal configuration as arguments and starts a stream to stdout. """ import os import signal import logging import time import json import tweepy from .listener import JsonStreamListener from .checker import FileTermChecker from .stream import DynamicTwitterStream logger = l...
michaelbrooks/twitter-monitor
twitter_monitor/basic_stream.py
set_terminate_listeners
python
def set_terminate_listeners(stream): def stop(signum, frame): terminate(stream.listener) # Installs signal handlers for handling SIGINT and SIGTERM # gracefully. signal.signal(signal.SIGINT, stop) signal.signal(signal.SIGTERM, stop)
Die on SIGTERM or SIGINT
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L115-L124
null
""" A simple streaming helper that takes minimal configuration as arguments and starts a stream to stdout. """ import os import signal import logging import time import json import tweepy from .listener import JsonStreamListener from .checker import FileTermChecker from .stream import DynamicTwitterStream logger = l...
michaelbrooks/twitter-monitor
twitter_monitor/basic_stream.py
get_tweepy_auth
python
def get_tweepy_auth(twitter_api_key, twitter_api_secret, twitter_access_token, twitter_access_token_secret): auth = tweepy.OAuthHandler(twitter_api_key, twitter_api_secret) auth.set_access_token(twitter_access_token, twitter_access_token_secret) re...
Make a tweepy auth object
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L127-L134
null
""" A simple streaming helper that takes minimal configuration as arguments and starts a stream to stdout. """ import os import signal import logging import time import json import tweepy from .listener import JsonStreamListener from .checker import FileTermChecker from .stream import DynamicTwitterStream logger = l...
michaelbrooks/twitter-monitor
twitter_monitor/basic_stream.py
construct_listener
python
def construct_listener(outfile=None): if outfile is not None: if os.path.exists(outfile): raise IOError("File %s already exists" % outfile) outfile = open(outfile, 'wb') return PrintingListener(out=outfile)
Create the listener that prints tweets
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L137-L145
null
""" A simple streaming helper that takes minimal configuration as arguments and starts a stream to stdout. """ import os import signal import logging import time import json import tweepy from .listener import JsonStreamListener from .checker import FileTermChecker from .stream import DynamicTwitterStream logger = l...
michaelbrooks/twitter-monitor
twitter_monitor/basic_stream.py
begin_stream_loop
python
def begin_stream_loop(stream, poll_interval): while should_continue(): try: stream.start_polling(poll_interval) except Exception as e: # Infinite restart logger.error("Exception while polling. Restarting in 1 second.", exc_info=True) time.sleep(1)
Start and maintain the streaming connection...
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L150-L158
[ "def should_continue():\n return True\n", "def start_polling(self, interval):\n \"\"\"\n Start polling for term updates and streaming.\n \"\"\"\n interval = float(interval)\n\n self.polling = True\n\n # clear the stored list of terms - we aren't tracking any\n self.term_checker.reset()\n\n...
""" A simple streaming helper that takes minimal configuration as arguments and starts a stream to stdout. """ import os import signal import logging import time import json import tweepy from .listener import JsonStreamListener from .checker import FileTermChecker from .stream import DynamicTwitterStream logger = l...
michaelbrooks/twitter-monitor
twitter_monitor/basic_stream.py
start
python
def start(track_file, twitter_api_key, twitter_api_secret, twitter_access_token, twitter_access_token_secret, poll_interval=15, unfiltered=False, languages=None, debug=False, outfile=None): listener = construct_listener(outfil...
Start the stream.
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L161-L186
[ "def set_debug_listener(stream):\n \"\"\"Break into a debugger if receives the SIGUSR1 signal\"\"\"\n\n def debugger(sig, frame):\n launch_debugger(frame, stream)\n\n if hasattr(signal, 'SIGUSR1'):\n signal.signal(signal.SIGUSR1, debugger)\n else:\n logger.warn(\"Cannot set SIGUSR1 ...
""" A simple streaming helper that takes minimal configuration as arguments and starts a stream to stdout. """ import os import signal import logging import time import json import tweepy from .listener import JsonStreamListener from .checker import FileTermChecker from .stream import DynamicTwitterStream logger = l...
michaelbrooks/twitter-monitor
twitter_monitor/basic_stream.py
PrintingListener.on_status
python
def on_status(self, status): self.out.write(json.dumps(status)) self.out.write(os.linesep) self.received += 1 return not self.terminate
Print out some tweets
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L38-L44
null
class PrintingListener(JsonStreamListener): """A listener that writes to a file or stdout""" def __init__(self, api=None, out=None): super(PrintingListener, self).__init__(api) if out is None: import sys out = sys.stdout self.out = out self.terminate = ...
michaelbrooks/twitter-monitor
twitter_monitor/basic_stream.py
PrintingListener.print_status
python
def print_status(self): tweets = self.received now = time.time() diff = now - self.since self.since = now self.received = 0 if diff > 0: logger.info("Receiving tweets at %s tps", tweets / diff)
Print out the current tweet rate and reset the counter
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L50-L58
null
class PrintingListener(JsonStreamListener): """A listener that writes to a file or stdout""" def __init__(self, api=None, out=None): super(PrintingListener, self).__init__(api) if out is None: import sys out = sys.stdout self.out = out self.terminate = ...
michaelbrooks/twitter-monitor
twitter_monitor/stream.py
DynamicTwitterStream.start_polling
python
def start_polling(self, interval): interval = float(interval) self.polling = True # clear the stored list of terms - we aren't tracking any self.term_checker.reset() logger.info("Starting polling for changes to the track list") while self.polling: loop_sta...
Start polling for term updates and streaming.
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/stream.py#L33-L56
[ "def update_stream(self):\n \"\"\"\n Restarts the stream with the current list of tracking terms.\n \"\"\"\n\n need_to_restart = False\n\n # If we think we are running, but something has gone wrong in the streaming thread\n # Restart it.\n if self.stream is not None and not self.stream.running:...
class DynamicTwitterStream(object): """ A wrapper around Tweepy's Stream class that causes streaming to be executed in a secondary thread. Meanwhile the primary thread sleeps for an interval between checking for term list updates. """ # Number of seconds to wait for the stream to stop ...
michaelbrooks/twitter-monitor
twitter_monitor/stream.py
DynamicTwitterStream.update_stream
python
def update_stream(self): need_to_restart = False # If we think we are running, but something has gone wrong in the streaming thread # Restart it. if self.stream is not None and not self.stream.running: logger.warning("Stream exists but isn't running") self.liste...
Restarts the stream with the current list of tracking terms.
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/stream.py#L65-L98
[ "def start_stream(self):\n \"\"\"Starts a stream with teh current tracking terms\"\"\"\n\n tracking_terms = self.term_checker.tracking_terms()\n\n if len(tracking_terms) > 0 or self.unfiltered:\n # we have terms to track, so build a new stream\n self.stream = tweepy.Stream(self.auth, self.lis...
class DynamicTwitterStream(object): """ A wrapper around Tweepy's Stream class that causes streaming to be executed in a secondary thread. Meanwhile the primary thread sleeps for an interval between checking for term list updates. """ # Number of seconds to wait for the stream to stop ...
michaelbrooks/twitter-monitor
twitter_monitor/stream.py
DynamicTwitterStream.start_stream
python
def start_stream(self): tracking_terms = self.term_checker.tracking_terms() if len(tracking_terms) > 0 or self.unfiltered: # we have terms to track, so build a new stream self.stream = tweepy.Stream(self.auth, self.listener, stall_warning...
Starts a stream with teh current tracking terms
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/stream.py#L100-L120
null
class DynamicTwitterStream(object): """ A wrapper around Tweepy's Stream class that causes streaming to be executed in a secondary thread. Meanwhile the primary thread sleeps for an interval between checking for term list updates. """ # Number of seconds to wait for the stream to stop ...
michaelbrooks/twitter-monitor
twitter_monitor/stream.py
DynamicTwitterStream.stop_stream
python
def stop_stream(self): if self.stream is not None: # There is a streaming thread logger.warning("Stopping twitter stream...") self.stream.disconnect() self.stream = None # wait a few seconds to allow the streaming to actually stop sleep...
Stops the current stream. Blocks until this is done.
train
https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/stream.py#L122-L136
null
class DynamicTwitterStream(object): """ A wrapper around Tweepy's Stream class that causes streaming to be executed in a secondary thread. Meanwhile the primary thread sleeps for an interval between checking for term list updates. """ # Number of seconds to wait for the stream to stop ...
ourway/auth
auth/CAS/authorization.py
Authorization.roles
python
def roles(self): result = AuthGroup.objects(creator=self.client).only('role') return json.loads(result.to_json())
gets user groups
train
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L25-L28
null
class Authorization(object): """ Main Authorization class """ def __init__(self, client): """Initialize Authorization with a client @type client: String """ self.client = client make_db_connection() @property def get_permissions(self, role): """gets pe...
ourway/auth
auth/CAS/authorization.py
Authorization.get_permissions
python
def get_permissions(self, role): target_role = AuthGroup.objects(role=role, creator=self.client).first() if not target_role: return '[]' targets = AuthPermission.objects(groups=target_role, creator=self.client).only('name') return json.loads(targets.to_json())
gets permissions of role
train
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L30-L36
null
class Authorization(object): """ Main Authorization class """ def __init__(self, client): """Initialize Authorization with a client @type client: String """ self.client = client make_db_connection() @property def roles(self): """gets user groups""" ...
ourway/auth
auth/CAS/authorization.py
Authorization.get_user_permissions
python
def get_user_permissions(self, user): memberShipRecords = AuthMembership.objects(creator=self.client, user=user).only('groups') results = [] for each in memberShipRecords: for group in each.groups: targetPermissionRecords = AuthPermission.objects(creator=self.client, ...
get permissions of a user
train
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L39-L50
null
class Authorization(object): """ Main Authorization class """ def __init__(self, client): """Initialize Authorization with a client @type client: String """ self.client = client make_db_connection() @property def roles(self): """gets user groups""" ...
ourway/auth
auth/CAS/authorization.py
Authorization.get_user_roles
python
def get_user_roles(self, user): memberShipRecords = AuthMembership.objects(creator=self.client, user=user).only('groups') results = [] for each in memberShipRecords: for group in each.groups: results.append({'role':group.role}) return results
get permissions of a user
train
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L52-L59
null
class Authorization(object): """ Main Authorization class """ def __init__(self, client): """Initialize Authorization with a client @type client: String """ self.client = client make_db_connection() @property def roles(self): """gets user groups""" ...
ourway/auth
auth/CAS/authorization.py
Authorization.get_role_members
python
def get_role_members(self, role): targetRoleDb = AuthGroup.objects(creator=self.client, role=role) members = AuthMembership.objects(groups__in=targetRoleDb).only('user') return json.loads(members.to_json())
get permissions of a user
train
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L62-L66
null
class Authorization(object): """ Main Authorization class """ def __init__(self, client): """Initialize Authorization with a client @type client: String """ self.client = client make_db_connection() @property def roles(self): """gets user groups""" ...
ourway/auth
auth/CAS/authorization.py
Authorization.which_roles_can
python
def which_roles_can(self, name): targetPermissionRecords = AuthPermission.objects(creator=self.client, name=name).first() return [{'role': group.role} for group in targetPermissionRecords.groups]
Which role can SendMail?
train
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L68-L71
null
class Authorization(object): """ Main Authorization class """ def __init__(self, client): """Initialize Authorization with a client @type client: String """ self.client = client make_db_connection() @property def roles(self): """gets user groups""" ...
ourway/auth
auth/CAS/authorization.py
Authorization.which_users_can
python
def which_users_can(self, name): _roles = self.which_roles_can(name) result = [self.get_role_members(i.get('role')) for i in _roles] return result
Which role can SendMail?
train
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L73-L77
[ "def which_roles_can(self, name):\n \"\"\"Which role can SendMail? \"\"\"\n targetPermissionRecords = AuthPermission.objects(creator=self.client, name=name).first()\n return [{'role': group.role} for group in targetPermissionRecords.groups]\n" ]
class Authorization(object): """ Main Authorization class """ def __init__(self, client): """Initialize Authorization with a client @type client: String """ self.client = client make_db_connection() @property def roles(self): """gets user groups""" ...
ourway/auth
auth/CAS/authorization.py
Authorization.get_role
python
def get_role(self, role): role = AuthGroup.objects(role=role, creator=self.client).first() return role
Returns a role object
train
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L79-L83
null
class Authorization(object): """ Main Authorization class """ def __init__(self, client): """Initialize Authorization with a client @type client: String """ self.client = client make_db_connection() @property def roles(self): """gets user groups""" ...
ourway/auth
auth/CAS/authorization.py
Authorization.add_role
python
def add_role(self, role, description=None): new_group = AuthGroup(role=role, creator=self.client) try: new_group.save() return True except NotUniqueError: return False
Creates a new group
train
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L85-L92
null
class Authorization(object): """ Main Authorization class """ def __init__(self, client): """Initialize Authorization with a client @type client: String """ self.client = client make_db_connection() @property def roles(self): """gets user groups""" ...
ourway/auth
auth/CAS/authorization.py
Authorization.del_role
python
def del_role(self, role): target = AuthGroup.objects(role=role, creator=self.client).first() if target: target.delete() return True else: return False
deletes a group
train
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L94-L101
null
class Authorization(object): """ Main Authorization class """ def __init__(self, client): """Initialize Authorization with a client @type client: String """ self.client = client make_db_connection() @property def roles(self): """gets user groups""" ...
ourway/auth
auth/CAS/authorization.py
Authorization.add_membership
python
def add_membership(self, user, role): targetGroup = AuthGroup.objects(role=role, creator=self.client).first() if not targetGroup: return False target = AuthMembership.objects(user=user, creator=self.client).first() if not target: target = AuthMembership(user=user...
make user a member of a group
train
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L103-L116
null
class Authorization(object): """ Main Authorization class """ def __init__(self, client): """Initialize Authorization with a client @type client: String """ self.client = client make_db_connection() @property def roles(self): """gets user groups""" ...
ourway/auth
auth/CAS/authorization.py
Authorization.del_membership
python
def del_membership(self, user, role): if not self.has_membership(user, role): return True targetRecord = AuthMembership.objects(creator=self.client, user=user).first() if not targetRecord: return True for group in targetRecord.groups: if group.role==ro...
dismember user from a group
train
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L119-L130
[ "def has_membership(self, user, role):\n \"\"\" checks if user is member of a group\"\"\"\n targetRecord = AuthMembership.objects(creator=self.client, user=user).first()\n if targetRecord:\n return role in [i.role for i in targetRecord.groups]\n return False\n" ]
class Authorization(object): """ Main Authorization class """ def __init__(self, client): """Initialize Authorization with a client @type client: String """ self.client = client make_db_connection() @property def roles(self): """gets user groups""" ...
ourway/auth
auth/CAS/authorization.py
Authorization.has_membership
python
def has_membership(self, user, role): targetRecord = AuthMembership.objects(creator=self.client, user=user).first() if targetRecord: return role in [i.role for i in targetRecord.groups] return False
checks if user is member of a group
train
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L132-L137
null
class Authorization(object): """ Main Authorization class """ def __init__(self, client): """Initialize Authorization with a client @type client: String """ self.client = client make_db_connection() @property def roles(self): """gets user groups""" ...
ourway/auth
auth/CAS/authorization.py
Authorization.add_permission
python
def add_permission(self, role, name): if self.has_permission(role, name): return True targetGroup = AuthGroup.objects(role=role, creator=self.client).first() if not targetGroup: return False # Create or update permission = AuthPermission.objects(name=name)...
authorize a group for something
train
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L140-L151
[ "def has_permission(self, role, name):\n \"\"\" verify groups authorization \"\"\"\n targetGroup = AuthGroup.objects(role=role, creator=self.client).first()\n if not targetGroup:\n return False\n target = AuthPermission.objects(groups=targetGroup, name=name, creator=self.client).first()\n if t...
class Authorization(object): """ Main Authorization class """ def __init__(self, client): """Initialize Authorization with a client @type client: String """ self.client = client make_db_connection() @property def roles(self): """gets user groups""" ...
ourway/auth
auth/CAS/authorization.py
Authorization.del_permission
python
def del_permission(self, role, name): if not self.has_permission(role, name): return True targetGroup = AuthGroup.objects(role=role, creator=self.client).first() target = AuthPermission.objects(groups=targetGroup, name=name, creator=self.client).first() if not target: ...
revoke authorization of a group
train
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L153-L162
[ "def has_permission(self, role, name):\n \"\"\" verify groups authorization \"\"\"\n targetGroup = AuthGroup.objects(role=role, creator=self.client).first()\n if not targetGroup:\n return False\n target = AuthPermission.objects(groups=targetGroup, name=name, creator=self.client).first()\n if t...
class Authorization(object): """ Main Authorization class """ def __init__(self, client): """Initialize Authorization with a client @type client: String """ self.client = client make_db_connection() @property def roles(self): """gets user groups""" ...
ourway/auth
auth/CAS/authorization.py
Authorization.user_has_permission
python
def user_has_permission(self, user, name): targetRecord = AuthMembership.objects(creator=self.client, user=user).first() if not targetRecord: return False for group in targetRecord.groups: if self.has_permission(group.role, name): return True retur...
verify user has permission
train
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L174-L182
null
class Authorization(object): """ Main Authorization class """ def __init__(self, client): """Initialize Authorization with a client @type client: String """ self.client = client make_db_connection() @property def roles(self): """gets user groups""" ...
ourway/auth
auth/CAS/models/db.py
handler
python
def handler(event): def decorator(fn): def apply(cls): event.connect(fn, sender=cls) return cls fn.apply = apply return fn return decorator
Signal decorator to allow use of callback functions as class decorators.
train
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/models/db.py#L47-L56
null
#!/usr/bin/env python """ Workflow: Creating permissions First we need some groups, so API user must crete some groups data = {role:'editors', creator:'my_secret'} POST /api/authorization/group data Then client can assign user: data = {group:'editors', user='rodmena', creator='my_sec...
ourway/auth
auth/CAS/REST/service.py
stringify
python
def stringify(req, resp): if isinstance(resp.body, dict): try: resp.body = json.dumps(resp.body) except(nameError): resp.status = falcon.HTTP_500
dumps all valid jsons This is the latest after hook
train
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/REST/service.py#L71-L80
null
#try: # import eventlet # eventlet.monkey_patch() #except: # pass import falcon import json try: import ujson as json except ImportError: pass from auth.CAS.authorization import Authorization class AuthComponent(object): def process_request(self, req, resp): """Process the request befo...
ourway/auth
auth/CAS/REST/service.py
AuthComponent.process_response
python
def process_response(self, req, resp, resource): if isinstance(resp.body, dict): try: resp.body = json.dumps(resp.body) except(nameError): resp.status = falcon.HTTP_500
Post-processing of the response (after routing). Args: req: Request object. resp: Response object. resource: Resource object to which the request was routed. May be None if no route was found for the request.
train
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/REST/service.py#L49-L63
null
class AuthComponent(object): def process_request(self, req, resp): """Process the request before routing it. Args: req: Request object that will eventually be routed to an on_* responder method. resp: Response object that will be routed to the...
storax/jinjaapidoc
src/jinjaapidoc/gendoc.py
prepare_dir
python
def prepare_dir(app, directory, delete=False): logger.info("Preparing output directories for jinjaapidoc.") if os.path.exists(directory): if delete: logger.debug("Deleting dir %s", directory) shutil.rmtree(directory) logger.debug("Creating dir %s", directory) ...
Create apidoc dir, delete contents if delete is True. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param directory: the apidoc directory. you can use relative paths here :type directory: str :param delete: if True, deletes the contents of apidoc. This acts like an overr...
train
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L38-L60
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """This is a modification of sphinx.apidoc by David.Zuber. It uses jinja templates to render the rst files. Parses a directory tree looking for Python modules and packages and creates ReST files appropriately to create code documentation with Sphinx. This is derived form ...
storax/jinjaapidoc
src/jinjaapidoc/gendoc.py
makename
python
def makename(package, module): # Both package and module can be None/empty. assert package or module, "Specify either package or module" if package: name = package if module: name += '.' + module else: name = module return name
Join package and module with a dot. Package or Module can be empty. :param package: the package name :type package: :class:`str` :param module: the module name :type module: :class:`str` :returns: the joined name :rtype: :class:`str` :raises: :class:`AssertionError`, if both package an...
train
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L87-L108
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """This is a modification of sphinx.apidoc by David.Zuber. It uses jinja templates to render the rst files. Parses a directory tree looking for Python modules and packages and creates ReST files appropriately to create code documentation with Sphinx. This is derived form ...
storax/jinjaapidoc
src/jinjaapidoc/gendoc.py
write_file
python
def write_file(app, name, text, dest, suffix, dryrun, force): fname = os.path.join(dest, '%s.%s' % (name, suffix)) if dryrun: logger.info('Would create file %s.' % fname) return if not force and os.path.isfile(fname): logger.info('File %s already exists, skipping.' % fname) else:...
Write the output file for module/package <name>. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param name: the file name without file extension :type name: :class:`str` :param text: the content of the file :type text: :class:`str` :param dest: the output director...
train
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L111-L149
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """This is a modification of sphinx.apidoc by David.Zuber. It uses jinja templates to render the rst files. Parses a directory tree looking for Python modules and packages and creates ReST files appropriately to create code documentation with Sphinx. This is derived form ...
storax/jinjaapidoc
src/jinjaapidoc/gendoc.py
import_name
python
def import_name(app, name): try: logger.debug('Importing %r', name) name, obj = autosummary.import_by_name(name)[:2] logger.debug('Imported %s', obj) return obj except ImportError as e: logger.warn("Jinjapidoc failed to import %r: %s", name, e)
Import the given name and return name, obj, parent, mod_name :param name: name to import :type name: str :returns: the imported object or None :rtype: object | None :raises: None
train
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L152-L167
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """This is a modification of sphinx.apidoc by David.Zuber. It uses jinja templates to render the rst files. Parses a directory tree looking for Python modules and packages and creates ReST files appropriately to create code documentation with Sphinx. This is derived form ...
storax/jinjaapidoc
src/jinjaapidoc/gendoc.py
get_members
python
def get_members(app, mod, typ, include_public=None): def include_here(x): """Return true if the member should be included in mod. A member will be included if it is declared in this module or package. If the `jinjaapidoc_include_from_all` option is `True` then the member can also be...
Return the members of mod of the given type :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param mod: the module with members :type mod: module :param typ: the typ, ``'class'``, ``'function'``, ``'exception'``, ``'data'``, ``'members'`` :type typ: str :param inclu...
train
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L170-L218
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """This is a modification of sphinx.apidoc by David.Zuber. It uses jinja templates to render the rst files. Parses a directory tree looking for Python modules and packages and creates ReST files appropriately to create code documentation with Sphinx. This is derived form ...