file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
51_N-Queens.py
class Solution(object): def solveNQueens(self, n): """ :type n: int :rtype: List[List[str]] """ def search(cur): if cur == n: add_answer() else: for i in range(n): ok = True rows[cur] = i for j in range(cur): if not is_valied(cur, j): ok = False break if ok: search(cur + 1) def is_valied(pre_row, cur_row): if rows[pre_row] == rows[cur_row] or \ pre_row - rows[pre_row] == cur_row - rows[cur_row] or \ pre_row + rows[pre_row] == cur_row + rows[cur_row]: return False else: return True def add_answer(): ans = [] for num in rows: res_str = "" for i in range(n):
ans.append(res_str) result.append(ans) result = [] rows = [0] * n search(0) return result print Solution().solveNQueens(4)
if i == num: res_str += "Q" else: res_str += "."
random_line_split
51_N-Queens.py
class Solution(object): def solveNQueens(self, n):
print Solution().solveNQueens(4)
""" :type n: int :rtype: List[List[str]] """ def search(cur): if cur == n: add_answer() else: for i in range(n): ok = True rows[cur] = i for j in range(cur): if not is_valied(cur, j): ok = False break if ok: search(cur + 1) def is_valied(pre_row, cur_row): if rows[pre_row] == rows[cur_row] or \ pre_row - rows[pre_row] == cur_row - rows[cur_row] or \ pre_row + rows[pre_row] == cur_row + rows[cur_row]: return False else: return True def add_answer(): ans = [] for num in rows: res_str = "" for i in range(n): if i == num: res_str += "Q" else: res_str += "." ans.append(res_str) result.append(ans) result = [] rows = [0] * n search(0) return result
identifier_body
issue-3038.rs
impl HTMLTableElement { fn func()
}
{ if number_of_row_elements == 0 { if let Some(last_tbody) = node .rev_children() .filter_map(DomRoot::downcast::<Element>) .find(|n| { n.is::<HTMLTableSectionElement>() && n.local_name() == &local_name!("tbody") }) { last_tbody .upcast::<Node>() .AppendChild(new_row.upcast::<Node>()) .expect("InsertRow failed to append first row."); } } if number_of_row_elements == 0 { if let Some(last_tbody) = node.find(|n| { n.is::<HTMLTableSectionElement>() && n.local_name() == &local_name!("tbody") }) { last_tbody .upcast::<Node>() .AppendChild(new_row.upcast::<Node>()) .expect("InsertRow failed to append first row."); } } }
identifier_body
issue-3038.rs
impl HTMLTableElement { fn func() { if number_of_row_elements == 0 { if let Some(last_tbody) = node .rev_children() .filter_map(DomRoot::downcast::<Element>) .find(|n| { n.is::<HTMLTableSectionElement>() && n.local_name() == &local_name!("tbody") }) { last_tbody .upcast::<Node>() .AppendChild(new_row.upcast::<Node>()) .expect("InsertRow failed to append first row."); } } if number_of_row_elements == 0 { if let Some(last_tbody) = node.find(|n| {
.expect("InsertRow failed to append first row."); } } } }
n.is::<HTMLTableSectionElement>() && n.local_name() == &local_name!("tbody") }) { last_tbody .upcast::<Node>() .AppendChild(new_row.upcast::<Node>())
random_line_split
issue-3038.rs
impl HTMLTableElement { fn
() { if number_of_row_elements == 0 { if let Some(last_tbody) = node .rev_children() .filter_map(DomRoot::downcast::<Element>) .find(|n| { n.is::<HTMLTableSectionElement>() && n.local_name() == &local_name!("tbody") }) { last_tbody .upcast::<Node>() .AppendChild(new_row.upcast::<Node>()) .expect("InsertRow failed to append first row."); } } if number_of_row_elements == 0 { if let Some(last_tbody) = node.find(|n| { n.is::<HTMLTableSectionElement>() && n.local_name() == &local_name!("tbody") }) { last_tbody .upcast::<Node>() .AppendChild(new_row.upcast::<Node>()) .expect("InsertRow failed to append first row."); } } } }
func
identifier_name
issue-3038.rs
impl HTMLTableElement { fn func() { if number_of_row_elements == 0 { if let Some(last_tbody) = node .rev_children() .filter_map(DomRoot::downcast::<Element>) .find(|n| { n.is::<HTMLTableSectionElement>() && n.local_name() == &local_name!("tbody") }) { last_tbody .upcast::<Node>() .AppendChild(new_row.upcast::<Node>()) .expect("InsertRow failed to append first row."); } } if number_of_row_elements == 0
} }
{ if let Some(last_tbody) = node.find(|n| { n.is::<HTMLTableSectionElement>() && n.local_name() == &local_name!("tbody") }) { last_tbody .upcast::<Node>() .AppendChild(new_row.upcast::<Node>()) .expect("InsertRow failed to append first row."); } }
conditional_block
optimize_grid.py
# Explore some possibilities for optimizing the grid. from __future__ import print_function from . import (paver,trigrid,orthomaker) from ..spatial import field import sys import numpy as np # from numpy import * from scipy.linalg import norm # from pylab import * import matplotlib.pyplot as plt class OptimizeGui(object): def __init__(self,og): self.og = og self.p = og.p def run(self): self.usage() self.fig = plt.figure() self.p.plot(boundary=True) plt.axis('equal') self.cid = self.fig.canvas.mpl_connect('key_press_event', self.onpress) self.cid_mouse = self.fig.canvas.mpl_connect('button_release_event',self.on_buttonrelease) def usage(self): print("t: flip edge") print("y: relax neighborhood") print("u: regrid at point") print("i: relax node") print("p: show bad cells") def flip_edge_at_point(self,pnt): """assumes an og instance is visible """ e = self.p.closest_edge(pnt) self.p.flip_edge(e) self.p.plot() def optimize_at_point(self,pnt): c = self.p.closest_cell(pnt) nbr = self.og.cell_neighborhood(c,2) self.og.relax_neighborhood(nbr) self.p.plot() last_node_relaxed = None def relax_node_at_point(self,pnt): v = self.p.closest_point(pnt) if v == self.last_node_relaxed: print("Allowing beta") self.p.safe_relax_one(v,use_beta=1) else: print("No beta") self.p.safe_relax_one(v) self.p.plot() self.last_node_relaxed = v def regrid_at_point(self,pnt): c = self.p.closest_cell(pnt) self.og.repave_neighborhood(c,scale_factor=0.8) self.p.plot() def show_bad_cells(self): bad = np.nonzero( self.og.cell_scores() <0.1 )[0] vc = self.p.vcenters() ax = plt.axis() plt.gca().texts = [] [plt.annotate(str(i),vc[i]) for i in bad] plt.axis(ax) def onpress(self,event): if event.inaxes is not None: print(event.xdata,event.ydata,event.key) pnt = np.array( [event.xdata,event.ydata] ) if event.key == 't': self.flip_edge_at_point(pnt) print("Returned from calcs") elif event.key == 'y': self.optimize_at_point(pnt) print("Returned from calcs") elif event.key == 'u': self.regrid_at_point(pnt) elif event.key == 'i': self.relax_node_at_point(pnt) elif event.key == 'p': self.show_bad_cells() return True last_axis = None def on_buttonrelease(self,event): if event.inaxes is not None: if plt.axis() != self.last_axis: print("Viewport has changed") self.last_axis = plt.axis() self.p.default_clip = self.last_axis # simple resolution-dependent plotting: if self.last_axis[1] - self.last_axis[0] > 3000: self.p.plot(boundary=True) else: self.p.plot(boundary=False) else: print("button release but axis is the same") class GridOptimizer(object): def __init__(self,p): self.p = p self.original_density = p.density # These are the values that, as needed, are used to construct a reduced scale # apollonius field. since right now ApolloniusField doesn't support insertion # and updates, we keep it as an array and recreate the field on demand. valid = np.isfinite(p.points[:,0]) xy_min = p.points[valid].min(axis=0) xy_max = p.points[valid].max(axis=0) self.scale_reductions = np.array( [ [xy_min[0],xy_min[1],1e6], [xy_min[0],xy_max[1],1e6], [xy_max[0],xy_max[1],1e6], [xy_max[0],xy_min[1],1e6]] ) apollo_rate = 1.1 def update_apollonius_field(self): """ create an apollonius graph using the points/scales in self.scale_reductions, and install it in self.p. """ if len(self.scale_reductions) == 0: self.apollo = None return self.apollo = field.ApolloniusField(self.scale_reductions[:,:2], self.scale_reductions[:,2], r=self.apollo_rate) self.p.density = field.BinopField( self.original_density, minimum, self.apollo ) # Explore a cost function based on voronoi-edge distance def cell_scores(self,cell_ids=None,use_original_density=True): """ Return scores for each cell, based on the minimum distance from the voronoi center to an edge, normalized by local scale invalid cells (i.e. have been deleted) get inf score use_original_density: defaults to evaluating local scale using the original density field. If set to false, use the current density field of the paver (which may be a reduced Apollonius Graph field) """ p=self.p if cell_ids is None:
valid = (p.cells[cell_ids,0]>=0) vc = p.vcenters()[cell_ids] local_scale = np.zeros( len(cell_ids), np.float64) if use_original_density: local_scale[valid] = self.original_density( vc[valid,:] ) else: local_scale[valid] = p.density( vc[valid,:] ) local_scale[~valid] = 1.0 # dummy # cell_scores = np.inf*np.ones( len(cell_ids) ) # 3 edge centers for every cell ec1 = 0.5*(p.points[p.cells[cell_ids,0]] + p.points[p.cells[cell_ids,1]]) ec2 = 0.5*(p.points[p.cells[cell_ids,1]] + p.points[p.cells[cell_ids,2]]) ec3 = 0.5*(p.points[p.cells[cell_ids,2]] + p.points[p.cells[cell_ids,0]]) d1 = ((vc - ec1)**2).sum(axis=1) d2 = ((vc - ec2)**2).sum(axis=1) d3 = ((vc - ec3)**2).sum(axis=1) # could be smarter and ignore boundary edges.. later. # this also has the downside that as we refine the scales, the scores # get worse. Maybe it would be better to compare the minimum ec value to # the mean or maximum, say (max(ec) - min(ec)) / med(ec) scores = np.sqrt(np.minimum(d1,d2,d3)) / local_scale scores[~valid] = np.inf return scores def relax_neighborhood(self,nodes): """ starting from the given set of nodes, relax in the area until the neighborhood score stops going down. """ cells = set() for n in nodes: cells = cells.union( self.p.pnt2cells(n) ) cells = np.array(list(cells)) starting_worst = self.cell_scores(cells).min() worst = starting_worst while 1: cp = self.p.checkpoint() for n in nodes: self.p.safe_relax_one(n) new_worst = self.cell_scores(cells).min() sys.stdout.write('.') ; sys.stdout.flush() if new_worst < worst: #print "That made it even worse." self.p.revert(cp) new_worst = worst break if new_worst < 1.01*worst: #print "Not getting any better. ===> %g"%new_worst break worst = new_worst print("Relax: %g => %g"%(starting_worst,new_worst)) self.p.commit() def cell_neighborhood_apollo(self,c): """ return the nodes near the given cell the apollo version means the termination condition is based on the expected radius of influence of a reduced scale at c """ vcs = self.p.vcenters() c_vc = self.p.vcenters()[c] orig_scale = self.original_density(c_vc) apollo_scale = self.apollo(c_vc) r = (orig_scale - apollo_scale) / (self.apollo.r - 1) print("Will clear out a radius of %f"%r) c_set = set() def dfs(cc): if cc in c_set: return if np.linalg.norm(vcs[cc] - c_vc) > r: return c_set.add(cc) for child in self.p.cell_neighbors(cc): dfs(child) dfs(c) cell_list = np.array(list(c_set)) return np.unique( self.p.cells[cell_list,:] ) def cell_neighborhood(self,c,nbr_count=2): """ return the nodes near the given cell if use_apollo is true, the termination condition is based on where the apollonius scale is larger than the original scale """ c_set = set() def dfs(cc,i): if cc in c_set: return c_set.add(cc) if i > 0: for child in self.p.cell_neighbors(cc): dfs(child,i-1) dfs(c,nbr_count) cell_list = np.array(list(c_set)) return np.unique( self.p.cells[cell_list,:] ) def relax_neighborhoods(self,score_threshold=0.1,count_threshold=5000, neighborhood_size=2): """ find the worst scores and try just relaxing in the general vicinity """ all_scores = self.cell_scores() ranking = np.argsort(all_scores) count = 0 while 1: c = ranking[count] score = all_scores[c] if score > score_threshold: break nbr = self.cell_neighborhood(c,neighborhood_size) self.relax_neighborhood(nbr) count += 1 if count >= count_threshold: break # if set, then scale reductions will be handled through an Apollonius Graph # otherwise, the density field is temporarily scaled down everywhere. use_apollo = False def repave_neighborhoods(self,score_threshold=0.1,count_threshold=5000, neighborhood_size=3, scale_factor=None): """ find the worst scores and try just repaving the general vicinity see repave_neighborhood for use of scale_factor. if use_apollo is true, neighborhood size is ignored and instead the neighborhood is defined by the telescoping ratio """ all_scores = self.cell_scores() ranking = np.argsort(all_scores) ## neighborhoods may overlap - and cells might get deleted. Keep a # record of cells that get deleted, and skip them later on. # this could get replaced by a priority queue, and we would just update # metrics as we go. expired_cells = {} def expire_cell(dc): expired_cells[dc] = 1 cb_id = self.p.listen('delete_cell',expire_cell) if self.use_apollo and scale_factor is not None and scale_factor < 1.0: # Add reduction points for all cells currently over the limit to_reduce = np.nonzero(all_scores<score_threshold)[0] centers = self.p.vcenters()[to_reduce] orig_scales = self.original_density( centers ) new_scales = scale_factor * orig_scales xyz = np.concatenate( [centers,new_scales[:,newaxis]], axis=1) self.scale_reductions = np.concatenate( [self.scale_reductions,xyz]) print( "Installing new Apollonius Field...") self.update_apollonius_field() print( "... Done") count = 0 while 1: c = ranking[count] print("Considering cell %d"%c) count += 1 # cell may have been deleted during other repaving if self.p.cells[c,0] < 0: print("It's been deleted") continue if expired_cells.has_key(c): print("It had been deleted, and some other cell has taken its place") continue # cell may have been updated during other repaving # note that it's possible that this cell was made a bit better, # but still needs to be repaved. For now, don't worry about that # because we probably want to relax the neighborhood before a second # round of repaving. if self.cell_scores(array([c]))[0] > all_scores[c]: continue score = all_scores[c] if score > score_threshold: break # also, this cell may have gotten updated by another repaving - # in which case we probably want print( "Repaving a neighborhood") self.repave_neighborhood(c,neighborhood_size=neighborhood_size,scale_factor=scale_factor) print( "Done") if count >= count_threshold: break self.p.unlisten(cb_id) # a more heavy-handed approach - # remove the neighborhood and repave def repave_neighborhood(self,c,neighborhood_size=3,scale_factor=None,nbr_nodes=None): """ c: The cell around which to repave n_s: how big the neighborhood is around the cell scale_factor: if specified, a factor to be applied to the density field during the repaving. nbr_nodes: if specified, exactly these nodes will be removed (with their edges and the cells belonging to those edges). otherwise, a neighborhood will be built up around c. """ print("Top of repave_neighborhood - c = %d"%c) starting_score = self.cell_scores(array([c])) p = self.p if nbr_nodes is None: if scale_factor is not None and self.use_apollo and scale_factor < 1.0: print( "dynamically defining neighborhood based on radius of Apollonius Graph influence") nbr_nodes = self.cell_neighborhood_apollo(c) else: nbr_nodes = self.cell_neighborhood(c,neighborhood_size) # delete all non boundary edges going to these nodes edges_to_kill = np.unique( np.concatenate( [p.pnt2edges(n) for n in nbr_nodes] ) ) # but don't remove boundary edges: # check both that it has cells on both sides, but also that it's not an # internal guide edge to_remove = (p.edges[edges_to_kill,4] >= 0) & (p.edge_data[edges_to_kill,1] < 0) edges_to_kill = edges_to_kill[ to_remove] for e in edges_to_kill: # print "Deleting edge e=%d"%e p.delete_edge(e,handle_unpaved=1) # the nodes that are not on the boundary get deleted: for n in nbr_nodes: # node_on_boundary includes internal_guides, so this should be okay. if p.node_on_boundary(n): # SLIDE nodes are reset to HINT so that we're free to resample # the boundary if p.node_data[n,paver.STAT] == paver.SLIDE: # print "Setting node n=%d to HINT"%n p.node_data[n,paver.STAT] = paver.HINT else: # print "Deleting node n=%d"%n p.delete_node(n) old_ncells = p.Ncells() saved_density = None if scale_factor is not None: if not ( self.use_apollo and scale_factor<1.0): saved_density = p.density p.density = p.density * scale_factor print("Repaving...") p.pave_all(n_steps=inf) # n_steps will keep it from renumbering afterwards if saved_density is not None: p.density = saved_density new_cells = np.arange(old_ncells,p.Ncells()) new_scores = self.cell_scores(new_cells) print("Repave: %g => %g"%(starting_score,new_scores.min())) def full(self): self.p.verbose = 0 self.relax_neighborhoods() self.repave_neighborhoods(neighborhood_size=2) self.relax_neighborhoods() self.repave_neighborhoods(neighborhood_size=2,scale_factor=0.9) self.repave_neighborhoods(neighborhood_size=2,scale_factor=0.8) self.repave_neighborhoods(neighborhood_size=3,scale_factor=0.8) self.repave_neighborhoods(neighborhood_size=3,scale_factor=0.75) self.relax_neighborhoods() for i in range(10): scores = self.cell_scores() print("iteration %d, %d bad cells"%(i, (scores<0.1).sum() )) self.p.write_complete('iter%02d.pav'%i) self.repave_neighborhoods(neighborhood_size=2,scale_factor=0.7) self.p.write_complete('iter%02d-repaved.pav'%i) self.relax_neighborhoods(neighborhood_size=5) self.stats() def stats(self): scores = self.cell_scores() print("Total cells with score below 0.1: %d"%( (scores<0.1).sum() )) def gui(self): """ A very simple gui for hand-optimizing. """ g = OptimizeGui(self) g.run() return g if __name__ == '__main__': p = paver.Paving.load_complete('/home/rusty/classes/research/suntans/grids/fullbay-0610/final.pav') p.clean_unpaved() opter = GridOptimizer(p) opter.stats() opter.full() opter.stats() # down to 25. ## Note on using the Apollonius graph for modifying the scale field: # The idea is that rather than temporarily scaling down the density # field to repave a subset of the grid, insert new AG points that will # blend the reduced scale back into the background scale. # This field would be persistent throughout the optimization.
cell_ids = np.arange(p.Ncells())
conditional_block
optimize_grid.py
# Explore some possibilities for optimizing the grid. from __future__ import print_function from . import (paver,trigrid,orthomaker) from ..spatial import field import sys import numpy as np # from numpy import * from scipy.linalg import norm # from pylab import * import matplotlib.pyplot as plt class OptimizeGui(object): def __init__(self,og): self.og = og self.p = og.p def run(self): self.usage() self.fig = plt.figure() self.p.plot(boundary=True) plt.axis('equal') self.cid = self.fig.canvas.mpl_connect('key_press_event', self.onpress) self.cid_mouse = self.fig.canvas.mpl_connect('button_release_event',self.on_buttonrelease) def usage(self): print("t: flip edge") print("y: relax neighborhood") print("u: regrid at point") print("i: relax node") print("p: show bad cells") def flip_edge_at_point(self,pnt): """assumes an og instance is visible """ e = self.p.closest_edge(pnt) self.p.flip_edge(e) self.p.plot() def optimize_at_point(self,pnt): c = self.p.closest_cell(pnt) nbr = self.og.cell_neighborhood(c,2) self.og.relax_neighborhood(nbr) self.p.plot() last_node_relaxed = None def relax_node_at_point(self,pnt): v = self.p.closest_point(pnt) if v == self.last_node_relaxed: print("Allowing beta") self.p.safe_relax_one(v,use_beta=1) else: print("No beta") self.p.safe_relax_one(v) self.p.plot() self.last_node_relaxed = v def regrid_at_point(self,pnt): c = self.p.closest_cell(pnt) self.og.repave_neighborhood(c,scale_factor=0.8) self.p.plot() def show_bad_cells(self): bad = np.nonzero( self.og.cell_scores() <0.1 )[0] vc = self.p.vcenters() ax = plt.axis() plt.gca().texts = [] [plt.annotate(str(i),vc[i]) for i in bad] plt.axis(ax) def onpress(self,event): if event.inaxes is not None: print(event.xdata,event.ydata,event.key) pnt = np.array( [event.xdata,event.ydata] ) if event.key == 't': self.flip_edge_at_point(pnt) print("Returned from calcs") elif event.key == 'y': self.optimize_at_point(pnt) print("Returned from calcs") elif event.key == 'u': self.regrid_at_point(pnt) elif event.key == 'i': self.relax_node_at_point(pnt) elif event.key == 'p': self.show_bad_cells() return True last_axis = None def on_buttonrelease(self,event): if event.inaxes is not None: if plt.axis() != self.last_axis: print("Viewport has changed") self.last_axis = plt.axis() self.p.default_clip = self.last_axis # simple resolution-dependent plotting: if self.last_axis[1] - self.last_axis[0] > 3000: self.p.plot(boundary=True) else: self.p.plot(boundary=False) else: print("button release but axis is the same")
class GridOptimizer(object): def __init__(self,p): self.p = p self.original_density = p.density # These are the values that, as needed, are used to construct a reduced scale # apollonius field. since right now ApolloniusField doesn't support insertion # and updates, we keep it as an array and recreate the field on demand. valid = np.isfinite(p.points[:,0]) xy_min = p.points[valid].min(axis=0) xy_max = p.points[valid].max(axis=0) self.scale_reductions = np.array( [ [xy_min[0],xy_min[1],1e6], [xy_min[0],xy_max[1],1e6], [xy_max[0],xy_max[1],1e6], [xy_max[0],xy_min[1],1e6]] ) apollo_rate = 1.1 def update_apollonius_field(self): """ create an apollonius graph using the points/scales in self.scale_reductions, and install it in self.p. """ if len(self.scale_reductions) == 0: self.apollo = None return self.apollo = field.ApolloniusField(self.scale_reductions[:,:2], self.scale_reductions[:,2], r=self.apollo_rate) self.p.density = field.BinopField( self.original_density, minimum, self.apollo ) # Explore a cost function based on voronoi-edge distance def cell_scores(self,cell_ids=None,use_original_density=True): """ Return scores for each cell, based on the minimum distance from the voronoi center to an edge, normalized by local scale invalid cells (i.e. have been deleted) get inf score use_original_density: defaults to evaluating local scale using the original density field. If set to false, use the current density field of the paver (which may be a reduced Apollonius Graph field) """ p=self.p if cell_ids is None: cell_ids = np.arange(p.Ncells()) valid = (p.cells[cell_ids,0]>=0) vc = p.vcenters()[cell_ids] local_scale = np.zeros( len(cell_ids), np.float64) if use_original_density: local_scale[valid] = self.original_density( vc[valid,:] ) else: local_scale[valid] = p.density( vc[valid,:] ) local_scale[~valid] = 1.0 # dummy # cell_scores = np.inf*np.ones( len(cell_ids) ) # 3 edge centers for every cell ec1 = 0.5*(p.points[p.cells[cell_ids,0]] + p.points[p.cells[cell_ids,1]]) ec2 = 0.5*(p.points[p.cells[cell_ids,1]] + p.points[p.cells[cell_ids,2]]) ec3 = 0.5*(p.points[p.cells[cell_ids,2]] + p.points[p.cells[cell_ids,0]]) d1 = ((vc - ec1)**2).sum(axis=1) d2 = ((vc - ec2)**2).sum(axis=1) d3 = ((vc - ec3)**2).sum(axis=1) # could be smarter and ignore boundary edges.. later. # this also has the downside that as we refine the scales, the scores # get worse. Maybe it would be better to compare the minimum ec value to # the mean or maximum, say (max(ec) - min(ec)) / med(ec) scores = np.sqrt(np.minimum(d1,d2,d3)) / local_scale scores[~valid] = np.inf return scores def relax_neighborhood(self,nodes): """ starting from the given set of nodes, relax in the area until the neighborhood score stops going down. """ cells = set() for n in nodes: cells = cells.union( self.p.pnt2cells(n) ) cells = np.array(list(cells)) starting_worst = self.cell_scores(cells).min() worst = starting_worst while 1: cp = self.p.checkpoint() for n in nodes: self.p.safe_relax_one(n) new_worst = self.cell_scores(cells).min() sys.stdout.write('.') ; sys.stdout.flush() if new_worst < worst: #print "That made it even worse." self.p.revert(cp) new_worst = worst break if new_worst < 1.01*worst: #print "Not getting any better. ===> %g"%new_worst break worst = new_worst print("Relax: %g => %g"%(starting_worst,new_worst)) self.p.commit() def cell_neighborhood_apollo(self,c): """ return the nodes near the given cell the apollo version means the termination condition is based on the expected radius of influence of a reduced scale at c """ vcs = self.p.vcenters() c_vc = self.p.vcenters()[c] orig_scale = self.original_density(c_vc) apollo_scale = self.apollo(c_vc) r = (orig_scale - apollo_scale) / (self.apollo.r - 1) print("Will clear out a radius of %f"%r) c_set = set() def dfs(cc): if cc in c_set: return if np.linalg.norm(vcs[cc] - c_vc) > r: return c_set.add(cc) for child in self.p.cell_neighbors(cc): dfs(child) dfs(c) cell_list = np.array(list(c_set)) return np.unique( self.p.cells[cell_list,:] ) def cell_neighborhood(self,c,nbr_count=2): """ return the nodes near the given cell if use_apollo is true, the termination condition is based on where the apollonius scale is larger than the original scale """ c_set = set() def dfs(cc,i): if cc in c_set: return c_set.add(cc) if i > 0: for child in self.p.cell_neighbors(cc): dfs(child,i-1) dfs(c,nbr_count) cell_list = np.array(list(c_set)) return np.unique( self.p.cells[cell_list,:] ) def relax_neighborhoods(self,score_threshold=0.1,count_threshold=5000, neighborhood_size=2): """ find the worst scores and try just relaxing in the general vicinity """ all_scores = self.cell_scores() ranking = np.argsort(all_scores) count = 0 while 1: c = ranking[count] score = all_scores[c] if score > score_threshold: break nbr = self.cell_neighborhood(c,neighborhood_size) self.relax_neighborhood(nbr) count += 1 if count >= count_threshold: break # if set, then scale reductions will be handled through an Apollonius Graph # otherwise, the density field is temporarily scaled down everywhere. use_apollo = False def repave_neighborhoods(self,score_threshold=0.1,count_threshold=5000, neighborhood_size=3, scale_factor=None): """ find the worst scores and try just repaving the general vicinity see repave_neighborhood for use of scale_factor. if use_apollo is true, neighborhood size is ignored and instead the neighborhood is defined by the telescoping ratio """ all_scores = self.cell_scores() ranking = np.argsort(all_scores) ## neighborhoods may overlap - and cells might get deleted. Keep a # record of cells that get deleted, and skip them later on. # this could get replaced by a priority queue, and we would just update # metrics as we go. expired_cells = {} def expire_cell(dc): expired_cells[dc] = 1 cb_id = self.p.listen('delete_cell',expire_cell) if self.use_apollo and scale_factor is not None and scale_factor < 1.0: # Add reduction points for all cells currently over the limit to_reduce = np.nonzero(all_scores<score_threshold)[0] centers = self.p.vcenters()[to_reduce] orig_scales = self.original_density( centers ) new_scales = scale_factor * orig_scales xyz = np.concatenate( [centers,new_scales[:,newaxis]], axis=1) self.scale_reductions = np.concatenate( [self.scale_reductions,xyz]) print( "Installing new Apollonius Field...") self.update_apollonius_field() print( "... Done") count = 0 while 1: c = ranking[count] print("Considering cell %d"%c) count += 1 # cell may have been deleted during other repaving if self.p.cells[c,0] < 0: print("It's been deleted") continue if expired_cells.has_key(c): print("It had been deleted, and some other cell has taken its place") continue # cell may have been updated during other repaving # note that it's possible that this cell was made a bit better, # but still needs to be repaved. For now, don't worry about that # because we probably want to relax the neighborhood before a second # round of repaving. if self.cell_scores(array([c]))[0] > all_scores[c]: continue score = all_scores[c] if score > score_threshold: break # also, this cell may have gotten updated by another repaving - # in which case we probably want print( "Repaving a neighborhood") self.repave_neighborhood(c,neighborhood_size=neighborhood_size,scale_factor=scale_factor) print( "Done") if count >= count_threshold: break self.p.unlisten(cb_id) # a more heavy-handed approach - # remove the neighborhood and repave def repave_neighborhood(self,c,neighborhood_size=3,scale_factor=None,nbr_nodes=None): """ c: The cell around which to repave n_s: how big the neighborhood is around the cell scale_factor: if specified, a factor to be applied to the density field during the repaving. nbr_nodes: if specified, exactly these nodes will be removed (with their edges and the cells belonging to those edges). otherwise, a neighborhood will be built up around c. """ print("Top of repave_neighborhood - c = %d"%c) starting_score = self.cell_scores(array([c])) p = self.p if nbr_nodes is None: if scale_factor is not None and self.use_apollo and scale_factor < 1.0: print( "dynamically defining neighborhood based on radius of Apollonius Graph influence") nbr_nodes = self.cell_neighborhood_apollo(c) else: nbr_nodes = self.cell_neighborhood(c,neighborhood_size) # delete all non boundary edges going to these nodes edges_to_kill = np.unique( np.concatenate( [p.pnt2edges(n) for n in nbr_nodes] ) ) # but don't remove boundary edges: # check both that it has cells on both sides, but also that it's not an # internal guide edge to_remove = (p.edges[edges_to_kill,4] >= 0) & (p.edge_data[edges_to_kill,1] < 0) edges_to_kill = edges_to_kill[ to_remove] for e in edges_to_kill: # print "Deleting edge e=%d"%e p.delete_edge(e,handle_unpaved=1) # the nodes that are not on the boundary get deleted: for n in nbr_nodes: # node_on_boundary includes internal_guides, so this should be okay. if p.node_on_boundary(n): # SLIDE nodes are reset to HINT so that we're free to resample # the boundary if p.node_data[n,paver.STAT] == paver.SLIDE: # print "Setting node n=%d to HINT"%n p.node_data[n,paver.STAT] = paver.HINT else: # print "Deleting node n=%d"%n p.delete_node(n) old_ncells = p.Ncells() saved_density = None if scale_factor is not None: if not ( self.use_apollo and scale_factor<1.0): saved_density = p.density p.density = p.density * scale_factor print("Repaving...") p.pave_all(n_steps=inf) # n_steps will keep it from renumbering afterwards if saved_density is not None: p.density = saved_density new_cells = np.arange(old_ncells,p.Ncells()) new_scores = self.cell_scores(new_cells) print("Repave: %g => %g"%(starting_score,new_scores.min())) def full(self): self.p.verbose = 0 self.relax_neighborhoods() self.repave_neighborhoods(neighborhood_size=2) self.relax_neighborhoods() self.repave_neighborhoods(neighborhood_size=2,scale_factor=0.9) self.repave_neighborhoods(neighborhood_size=2,scale_factor=0.8) self.repave_neighborhoods(neighborhood_size=3,scale_factor=0.8) self.repave_neighborhoods(neighborhood_size=3,scale_factor=0.75) self.relax_neighborhoods() for i in range(10): scores = self.cell_scores() print("iteration %d, %d bad cells"%(i, (scores<0.1).sum() )) self.p.write_complete('iter%02d.pav'%i) self.repave_neighborhoods(neighborhood_size=2,scale_factor=0.7) self.p.write_complete('iter%02d-repaved.pav'%i) self.relax_neighborhoods(neighborhood_size=5) self.stats() def stats(self): scores = self.cell_scores() print("Total cells with score below 0.1: %d"%( (scores<0.1).sum() )) def gui(self): """ A very simple gui for hand-optimizing. """ g = OptimizeGui(self) g.run() return g if __name__ == '__main__': p = paver.Paving.load_complete('/home/rusty/classes/research/suntans/grids/fullbay-0610/final.pav') p.clean_unpaved() opter = GridOptimizer(p) opter.stats() opter.full() opter.stats() # down to 25. ## Note on using the Apollonius graph for modifying the scale field: # The idea is that rather than temporarily scaling down the density # field to repave a subset of the grid, insert new AG points that will # blend the reduced scale back into the background scale. # This field would be persistent throughout the optimization.
random_line_split
optimize_grid.py
# Explore some possibilities for optimizing the grid. from __future__ import print_function from . import (paver,trigrid,orthomaker) from ..spatial import field import sys import numpy as np # from numpy import * from scipy.linalg import norm # from pylab import * import matplotlib.pyplot as plt class OptimizeGui(object): def __init__(self,og): self.og = og self.p = og.p def run(self): self.usage() self.fig = plt.figure() self.p.plot(boundary=True) plt.axis('equal') self.cid = self.fig.canvas.mpl_connect('key_press_event', self.onpress) self.cid_mouse = self.fig.canvas.mpl_connect('button_release_event',self.on_buttonrelease) def usage(self): print("t: flip edge") print("y: relax neighborhood") print("u: regrid at point") print("i: relax node") print("p: show bad cells") def flip_edge_at_point(self,pnt): """assumes an og instance is visible """ e = self.p.closest_edge(pnt) self.p.flip_edge(e) self.p.plot() def
(self,pnt): c = self.p.closest_cell(pnt) nbr = self.og.cell_neighborhood(c,2) self.og.relax_neighborhood(nbr) self.p.plot() last_node_relaxed = None def relax_node_at_point(self,pnt): v = self.p.closest_point(pnt) if v == self.last_node_relaxed: print("Allowing beta") self.p.safe_relax_one(v,use_beta=1) else: print("No beta") self.p.safe_relax_one(v) self.p.plot() self.last_node_relaxed = v def regrid_at_point(self,pnt): c = self.p.closest_cell(pnt) self.og.repave_neighborhood(c,scale_factor=0.8) self.p.plot() def show_bad_cells(self): bad = np.nonzero( self.og.cell_scores() <0.1 )[0] vc = self.p.vcenters() ax = plt.axis() plt.gca().texts = [] [plt.annotate(str(i),vc[i]) for i in bad] plt.axis(ax) def onpress(self,event): if event.inaxes is not None: print(event.xdata,event.ydata,event.key) pnt = np.array( [event.xdata,event.ydata] ) if event.key == 't': self.flip_edge_at_point(pnt) print("Returned from calcs") elif event.key == 'y': self.optimize_at_point(pnt) print("Returned from calcs") elif event.key == 'u': self.regrid_at_point(pnt) elif event.key == 'i': self.relax_node_at_point(pnt) elif event.key == 'p': self.show_bad_cells() return True last_axis = None def on_buttonrelease(self,event): if event.inaxes is not None: if plt.axis() != self.last_axis: print("Viewport has changed") self.last_axis = plt.axis() self.p.default_clip = self.last_axis # simple resolution-dependent plotting: if self.last_axis[1] - self.last_axis[0] > 3000: self.p.plot(boundary=True) else: self.p.plot(boundary=False) else: print("button release but axis is the same") class GridOptimizer(object): def __init__(self,p): self.p = p self.original_density = p.density # These are the values that, as needed, are used to construct a reduced scale # apollonius field. since right now ApolloniusField doesn't support insertion # and updates, we keep it as an array and recreate the field on demand. valid = np.isfinite(p.points[:,0]) xy_min = p.points[valid].min(axis=0) xy_max = p.points[valid].max(axis=0) self.scale_reductions = np.array( [ [xy_min[0],xy_min[1],1e6], [xy_min[0],xy_max[1],1e6], [xy_max[0],xy_max[1],1e6], [xy_max[0],xy_min[1],1e6]] ) apollo_rate = 1.1 def update_apollonius_field(self): """ create an apollonius graph using the points/scales in self.scale_reductions, and install it in self.p. """ if len(self.scale_reductions) == 0: self.apollo = None return self.apollo = field.ApolloniusField(self.scale_reductions[:,:2], self.scale_reductions[:,2], r=self.apollo_rate) self.p.density = field.BinopField( self.original_density, minimum, self.apollo ) # Explore a cost function based on voronoi-edge distance def cell_scores(self,cell_ids=None,use_original_density=True): """ Return scores for each cell, based on the minimum distance from the voronoi center to an edge, normalized by local scale invalid cells (i.e. have been deleted) get inf score use_original_density: defaults to evaluating local scale using the original density field. If set to false, use the current density field of the paver (which may be a reduced Apollonius Graph field) """ p=self.p if cell_ids is None: cell_ids = np.arange(p.Ncells()) valid = (p.cells[cell_ids,0]>=0) vc = p.vcenters()[cell_ids] local_scale = np.zeros( len(cell_ids), np.float64) if use_original_density: local_scale[valid] = self.original_density( vc[valid,:] ) else: local_scale[valid] = p.density( vc[valid,:] ) local_scale[~valid] = 1.0 # dummy # cell_scores = np.inf*np.ones( len(cell_ids) ) # 3 edge centers for every cell ec1 = 0.5*(p.points[p.cells[cell_ids,0]] + p.points[p.cells[cell_ids,1]]) ec2 = 0.5*(p.points[p.cells[cell_ids,1]] + p.points[p.cells[cell_ids,2]]) ec3 = 0.5*(p.points[p.cells[cell_ids,2]] + p.points[p.cells[cell_ids,0]]) d1 = ((vc - ec1)**2).sum(axis=1) d2 = ((vc - ec2)**2).sum(axis=1) d3 = ((vc - ec3)**2).sum(axis=1) # could be smarter and ignore boundary edges.. later. # this also has the downside that as we refine the scales, the scores # get worse. Maybe it would be better to compare the minimum ec value to # the mean or maximum, say (max(ec) - min(ec)) / med(ec) scores = np.sqrt(np.minimum(d1,d2,d3)) / local_scale scores[~valid] = np.inf return scores def relax_neighborhood(self,nodes): """ starting from the given set of nodes, relax in the area until the neighborhood score stops going down. """ cells = set() for n in nodes: cells = cells.union( self.p.pnt2cells(n) ) cells = np.array(list(cells)) starting_worst = self.cell_scores(cells).min() worst = starting_worst while 1: cp = self.p.checkpoint() for n in nodes: self.p.safe_relax_one(n) new_worst = self.cell_scores(cells).min() sys.stdout.write('.') ; sys.stdout.flush() if new_worst < worst: #print "That made it even worse." self.p.revert(cp) new_worst = worst break if new_worst < 1.01*worst: #print "Not getting any better. ===> %g"%new_worst break worst = new_worst print("Relax: %g => %g"%(starting_worst,new_worst)) self.p.commit() def cell_neighborhood_apollo(self,c): """ return the nodes near the given cell the apollo version means the termination condition is based on the expected radius of influence of a reduced scale at c """ vcs = self.p.vcenters() c_vc = self.p.vcenters()[c] orig_scale = self.original_density(c_vc) apollo_scale = self.apollo(c_vc) r = (orig_scale - apollo_scale) / (self.apollo.r - 1) print("Will clear out a radius of %f"%r) c_set = set() def dfs(cc): if cc in c_set: return if np.linalg.norm(vcs[cc] - c_vc) > r: return c_set.add(cc) for child in self.p.cell_neighbors(cc): dfs(child) dfs(c) cell_list = np.array(list(c_set)) return np.unique( self.p.cells[cell_list,:] ) def cell_neighborhood(self,c,nbr_count=2): """ return the nodes near the given cell if use_apollo is true, the termination condition is based on where the apollonius scale is larger than the original scale """ c_set = set() def dfs(cc,i): if cc in c_set: return c_set.add(cc) if i > 0: for child in self.p.cell_neighbors(cc): dfs(child,i-1) dfs(c,nbr_count) cell_list = np.array(list(c_set)) return np.unique( self.p.cells[cell_list,:] ) def relax_neighborhoods(self,score_threshold=0.1,count_threshold=5000, neighborhood_size=2): """ find the worst scores and try just relaxing in the general vicinity """ all_scores = self.cell_scores() ranking = np.argsort(all_scores) count = 0 while 1: c = ranking[count] score = all_scores[c] if score > score_threshold: break nbr = self.cell_neighborhood(c,neighborhood_size) self.relax_neighborhood(nbr) count += 1 if count >= count_threshold: break # if set, then scale reductions will be handled through an Apollonius Graph # otherwise, the density field is temporarily scaled down everywhere. use_apollo = False def repave_neighborhoods(self,score_threshold=0.1,count_threshold=5000, neighborhood_size=3, scale_factor=None): """ find the worst scores and try just repaving the general vicinity see repave_neighborhood for use of scale_factor. if use_apollo is true, neighborhood size is ignored and instead the neighborhood is defined by the telescoping ratio """ all_scores = self.cell_scores() ranking = np.argsort(all_scores) ## neighborhoods may overlap - and cells might get deleted. Keep a # record of cells that get deleted, and skip them later on. # this could get replaced by a priority queue, and we would just update # metrics as we go. expired_cells = {} def expire_cell(dc): expired_cells[dc] = 1 cb_id = self.p.listen('delete_cell',expire_cell) if self.use_apollo and scale_factor is not None and scale_factor < 1.0: # Add reduction points for all cells currently over the limit to_reduce = np.nonzero(all_scores<score_threshold)[0] centers = self.p.vcenters()[to_reduce] orig_scales = self.original_density( centers ) new_scales = scale_factor * orig_scales xyz = np.concatenate( [centers,new_scales[:,newaxis]], axis=1) self.scale_reductions = np.concatenate( [self.scale_reductions,xyz]) print( "Installing new Apollonius Field...") self.update_apollonius_field() print( "... Done") count = 0 while 1: c = ranking[count] print("Considering cell %d"%c) count += 1 # cell may have been deleted during other repaving if self.p.cells[c,0] < 0: print("It's been deleted") continue if expired_cells.has_key(c): print("It had been deleted, and some other cell has taken its place") continue # cell may have been updated during other repaving # note that it's possible that this cell was made a bit better, # but still needs to be repaved. For now, don't worry about that # because we probably want to relax the neighborhood before a second # round of repaving. if self.cell_scores(array([c]))[0] > all_scores[c]: continue score = all_scores[c] if score > score_threshold: break # also, this cell may have gotten updated by another repaving - # in which case we probably want print( "Repaving a neighborhood") self.repave_neighborhood(c,neighborhood_size=neighborhood_size,scale_factor=scale_factor) print( "Done") if count >= count_threshold: break self.p.unlisten(cb_id) # a more heavy-handed approach - # remove the neighborhood and repave def repave_neighborhood(self,c,neighborhood_size=3,scale_factor=None,nbr_nodes=None): """ c: The cell around which to repave n_s: how big the neighborhood is around the cell scale_factor: if specified, a factor to be applied to the density field during the repaving. nbr_nodes: if specified, exactly these nodes will be removed (with their edges and the cells belonging to those edges). otherwise, a neighborhood will be built up around c. """ print("Top of repave_neighborhood - c = %d"%c) starting_score = self.cell_scores(array([c])) p = self.p if nbr_nodes is None: if scale_factor is not None and self.use_apollo and scale_factor < 1.0: print( "dynamically defining neighborhood based on radius of Apollonius Graph influence") nbr_nodes = self.cell_neighborhood_apollo(c) else: nbr_nodes = self.cell_neighborhood(c,neighborhood_size) # delete all non boundary edges going to these nodes edges_to_kill = np.unique( np.concatenate( [p.pnt2edges(n) for n in nbr_nodes] ) ) # but don't remove boundary edges: # check both that it has cells on both sides, but also that it's not an # internal guide edge to_remove = (p.edges[edges_to_kill,4] >= 0) & (p.edge_data[edges_to_kill,1] < 0) edges_to_kill = edges_to_kill[ to_remove] for e in edges_to_kill: # print "Deleting edge e=%d"%e p.delete_edge(e,handle_unpaved=1) # the nodes that are not on the boundary get deleted: for n in nbr_nodes: # node_on_boundary includes internal_guides, so this should be okay. if p.node_on_boundary(n): # SLIDE nodes are reset to HINT so that we're free to resample # the boundary if p.node_data[n,paver.STAT] == paver.SLIDE: # print "Setting node n=%d to HINT"%n p.node_data[n,paver.STAT] = paver.HINT else: # print "Deleting node n=%d"%n p.delete_node(n) old_ncells = p.Ncells() saved_density = None if scale_factor is not None: if not ( self.use_apollo and scale_factor<1.0): saved_density = p.density p.density = p.density * scale_factor print("Repaving...") p.pave_all(n_steps=inf) # n_steps will keep it from renumbering afterwards if saved_density is not None: p.density = saved_density new_cells = np.arange(old_ncells,p.Ncells()) new_scores = self.cell_scores(new_cells) print("Repave: %g => %g"%(starting_score,new_scores.min())) def full(self): self.p.verbose = 0 self.relax_neighborhoods() self.repave_neighborhoods(neighborhood_size=2) self.relax_neighborhoods() self.repave_neighborhoods(neighborhood_size=2,scale_factor=0.9) self.repave_neighborhoods(neighborhood_size=2,scale_factor=0.8) self.repave_neighborhoods(neighborhood_size=3,scale_factor=0.8) self.repave_neighborhoods(neighborhood_size=3,scale_factor=0.75) self.relax_neighborhoods() for i in range(10): scores = self.cell_scores() print("iteration %d, %d bad cells"%(i, (scores<0.1).sum() )) self.p.write_complete('iter%02d.pav'%i) self.repave_neighborhoods(neighborhood_size=2,scale_factor=0.7) self.p.write_complete('iter%02d-repaved.pav'%i) self.relax_neighborhoods(neighborhood_size=5) self.stats() def stats(self): scores = self.cell_scores() print("Total cells with score below 0.1: %d"%( (scores<0.1).sum() )) def gui(self): """ A very simple gui for hand-optimizing. """ g = OptimizeGui(self) g.run() return g if __name__ == '__main__': p = paver.Paving.load_complete('/home/rusty/classes/research/suntans/grids/fullbay-0610/final.pav') p.clean_unpaved() opter = GridOptimizer(p) opter.stats() opter.full() opter.stats() # down to 25. ## Note on using the Apollonius graph for modifying the scale field: # The idea is that rather than temporarily scaling down the density # field to repave a subset of the grid, insert new AG points that will # blend the reduced scale back into the background scale. # This field would be persistent throughout the optimization.
optimize_at_point
identifier_name
optimize_grid.py
# Explore some possibilities for optimizing the grid. from __future__ import print_function from . import (paver,trigrid,orthomaker) from ..spatial import field import sys import numpy as np # from numpy import * from scipy.linalg import norm # from pylab import * import matplotlib.pyplot as plt class OptimizeGui(object): def __init__(self,og): self.og = og self.p = og.p def run(self): self.usage() self.fig = plt.figure() self.p.plot(boundary=True) plt.axis('equal') self.cid = self.fig.canvas.mpl_connect('key_press_event', self.onpress) self.cid_mouse = self.fig.canvas.mpl_connect('button_release_event',self.on_buttonrelease) def usage(self): print("t: flip edge") print("y: relax neighborhood") print("u: regrid at point") print("i: relax node") print("p: show bad cells") def flip_edge_at_point(self,pnt): """assumes an og instance is visible """ e = self.p.closest_edge(pnt) self.p.flip_edge(e) self.p.plot() def optimize_at_point(self,pnt): c = self.p.closest_cell(pnt) nbr = self.og.cell_neighborhood(c,2) self.og.relax_neighborhood(nbr) self.p.plot() last_node_relaxed = None def relax_node_at_point(self,pnt): v = self.p.closest_point(pnt) if v == self.last_node_relaxed: print("Allowing beta") self.p.safe_relax_one(v,use_beta=1) else: print("No beta") self.p.safe_relax_one(v) self.p.plot() self.last_node_relaxed = v def regrid_at_point(self,pnt): c = self.p.closest_cell(pnt) self.og.repave_neighborhood(c,scale_factor=0.8) self.p.plot() def show_bad_cells(self): bad = np.nonzero( self.og.cell_scores() <0.1 )[0] vc = self.p.vcenters() ax = plt.axis() plt.gca().texts = [] [plt.annotate(str(i),vc[i]) for i in bad] plt.axis(ax) def onpress(self,event): if event.inaxes is not None: print(event.xdata,event.ydata,event.key) pnt = np.array( [event.xdata,event.ydata] ) if event.key == 't': self.flip_edge_at_point(pnt) print("Returned from calcs") elif event.key == 'y': self.optimize_at_point(pnt) print("Returned from calcs") elif event.key == 'u': self.regrid_at_point(pnt) elif event.key == 'i': self.relax_node_at_point(pnt) elif event.key == 'p': self.show_bad_cells() return True last_axis = None def on_buttonrelease(self,event):
class GridOptimizer(object): def __init__(self,p): self.p = p self.original_density = p.density # These are the values that, as needed, are used to construct a reduced scale # apollonius field. since right now ApolloniusField doesn't support insertion # and updates, we keep it as an array and recreate the field on demand. valid = np.isfinite(p.points[:,0]) xy_min = p.points[valid].min(axis=0) xy_max = p.points[valid].max(axis=0) self.scale_reductions = np.array( [ [xy_min[0],xy_min[1],1e6], [xy_min[0],xy_max[1],1e6], [xy_max[0],xy_max[1],1e6], [xy_max[0],xy_min[1],1e6]] ) apollo_rate = 1.1 def update_apollonius_field(self): """ create an apollonius graph using the points/scales in self.scale_reductions, and install it in self.p. """ if len(self.scale_reductions) == 0: self.apollo = None return self.apollo = field.ApolloniusField(self.scale_reductions[:,:2], self.scale_reductions[:,2], r=self.apollo_rate) self.p.density = field.BinopField( self.original_density, minimum, self.apollo ) # Explore a cost function based on voronoi-edge distance def cell_scores(self,cell_ids=None,use_original_density=True): """ Return scores for each cell, based on the minimum distance from the voronoi center to an edge, normalized by local scale invalid cells (i.e. have been deleted) get inf score use_original_density: defaults to evaluating local scale using the original density field. If set to false, use the current density field of the paver (which may be a reduced Apollonius Graph field) """ p=self.p if cell_ids is None: cell_ids = np.arange(p.Ncells()) valid = (p.cells[cell_ids,0]>=0) vc = p.vcenters()[cell_ids] local_scale = np.zeros( len(cell_ids), np.float64) if use_original_density: local_scale[valid] = self.original_density( vc[valid,:] ) else: local_scale[valid] = p.density( vc[valid,:] ) local_scale[~valid] = 1.0 # dummy # cell_scores = np.inf*np.ones( len(cell_ids) ) # 3 edge centers for every cell ec1 = 0.5*(p.points[p.cells[cell_ids,0]] + p.points[p.cells[cell_ids,1]]) ec2 = 0.5*(p.points[p.cells[cell_ids,1]] + p.points[p.cells[cell_ids,2]]) ec3 = 0.5*(p.points[p.cells[cell_ids,2]] + p.points[p.cells[cell_ids,0]]) d1 = ((vc - ec1)**2).sum(axis=1) d2 = ((vc - ec2)**2).sum(axis=1) d3 = ((vc - ec3)**2).sum(axis=1) # could be smarter and ignore boundary edges.. later. # this also has the downside that as we refine the scales, the scores # get worse. Maybe it would be better to compare the minimum ec value to # the mean or maximum, say (max(ec) - min(ec)) / med(ec) scores = np.sqrt(np.minimum(d1,d2,d3)) / local_scale scores[~valid] = np.inf return scores def relax_neighborhood(self,nodes): """ starting from the given set of nodes, relax in the area until the neighborhood score stops going down. """ cells = set() for n in nodes: cells = cells.union( self.p.pnt2cells(n) ) cells = np.array(list(cells)) starting_worst = self.cell_scores(cells).min() worst = starting_worst while 1: cp = self.p.checkpoint() for n in nodes: self.p.safe_relax_one(n) new_worst = self.cell_scores(cells).min() sys.stdout.write('.') ; sys.stdout.flush() if new_worst < worst: #print "That made it even worse." self.p.revert(cp) new_worst = worst break if new_worst < 1.01*worst: #print "Not getting any better. ===> %g"%new_worst break worst = new_worst print("Relax: %g => %g"%(starting_worst,new_worst)) self.p.commit() def cell_neighborhood_apollo(self,c): """ return the nodes near the given cell the apollo version means the termination condition is based on the expected radius of influence of a reduced scale at c """ vcs = self.p.vcenters() c_vc = self.p.vcenters()[c] orig_scale = self.original_density(c_vc) apollo_scale = self.apollo(c_vc) r = (orig_scale - apollo_scale) / (self.apollo.r - 1) print("Will clear out a radius of %f"%r) c_set = set() def dfs(cc): if cc in c_set: return if np.linalg.norm(vcs[cc] - c_vc) > r: return c_set.add(cc) for child in self.p.cell_neighbors(cc): dfs(child) dfs(c) cell_list = np.array(list(c_set)) return np.unique( self.p.cells[cell_list,:] ) def cell_neighborhood(self,c,nbr_count=2): """ return the nodes near the given cell if use_apollo is true, the termination condition is based on where the apollonius scale is larger than the original scale """ c_set = set() def dfs(cc,i): if cc in c_set: return c_set.add(cc) if i > 0: for child in self.p.cell_neighbors(cc): dfs(child,i-1) dfs(c,nbr_count) cell_list = np.array(list(c_set)) return np.unique( self.p.cells[cell_list,:] ) def relax_neighborhoods(self,score_threshold=0.1,count_threshold=5000, neighborhood_size=2): """ find the worst scores and try just relaxing in the general vicinity """ all_scores = self.cell_scores() ranking = np.argsort(all_scores) count = 0 while 1: c = ranking[count] score = all_scores[c] if score > score_threshold: break nbr = self.cell_neighborhood(c,neighborhood_size) self.relax_neighborhood(nbr) count += 1 if count >= count_threshold: break # if set, then scale reductions will be handled through an Apollonius Graph # otherwise, the density field is temporarily scaled down everywhere. use_apollo = False def repave_neighborhoods(self,score_threshold=0.1,count_threshold=5000, neighborhood_size=3, scale_factor=None): """ find the worst scores and try just repaving the general vicinity see repave_neighborhood for use of scale_factor. if use_apollo is true, neighborhood size is ignored and instead the neighborhood is defined by the telescoping ratio """ all_scores = self.cell_scores() ranking = np.argsort(all_scores) ## neighborhoods may overlap - and cells might get deleted. Keep a # record of cells that get deleted, and skip them later on. # this could get replaced by a priority queue, and we would just update # metrics as we go. expired_cells = {} def expire_cell(dc): expired_cells[dc] = 1 cb_id = self.p.listen('delete_cell',expire_cell) if self.use_apollo and scale_factor is not None and scale_factor < 1.0: # Add reduction points for all cells currently over the limit to_reduce = np.nonzero(all_scores<score_threshold)[0] centers = self.p.vcenters()[to_reduce] orig_scales = self.original_density( centers ) new_scales = scale_factor * orig_scales xyz = np.concatenate( [centers,new_scales[:,newaxis]], axis=1) self.scale_reductions = np.concatenate( [self.scale_reductions,xyz]) print( "Installing new Apollonius Field...") self.update_apollonius_field() print( "... Done") count = 0 while 1: c = ranking[count] print("Considering cell %d"%c) count += 1 # cell may have been deleted during other repaving if self.p.cells[c,0] < 0: print("It's been deleted") continue if expired_cells.has_key(c): print("It had been deleted, and some other cell has taken its place") continue # cell may have been updated during other repaving # note that it's possible that this cell was made a bit better, # but still needs to be repaved. For now, don't worry about that # because we probably want to relax the neighborhood before a second # round of repaving. if self.cell_scores(array([c]))[0] > all_scores[c]: continue score = all_scores[c] if score > score_threshold: break # also, this cell may have gotten updated by another repaving - # in which case we probably want print( "Repaving a neighborhood") self.repave_neighborhood(c,neighborhood_size=neighborhood_size,scale_factor=scale_factor) print( "Done") if count >= count_threshold: break self.p.unlisten(cb_id) # a more heavy-handed approach - # remove the neighborhood and repave def repave_neighborhood(self,c,neighborhood_size=3,scale_factor=None,nbr_nodes=None): """ c: The cell around which to repave n_s: how big the neighborhood is around the cell scale_factor: if specified, a factor to be applied to the density field during the repaving. nbr_nodes: if specified, exactly these nodes will be removed (with their edges and the cells belonging to those edges). otherwise, a neighborhood will be built up around c. """ print("Top of repave_neighborhood - c = %d"%c) starting_score = self.cell_scores(array([c])) p = self.p if nbr_nodes is None: if scale_factor is not None and self.use_apollo and scale_factor < 1.0: print( "dynamically defining neighborhood based on radius of Apollonius Graph influence") nbr_nodes = self.cell_neighborhood_apollo(c) else: nbr_nodes = self.cell_neighborhood(c,neighborhood_size) # delete all non boundary edges going to these nodes edges_to_kill = np.unique( np.concatenate( [p.pnt2edges(n) for n in nbr_nodes] ) ) # but don't remove boundary edges: # check both that it has cells on both sides, but also that it's not an # internal guide edge to_remove = (p.edges[edges_to_kill,4] >= 0) & (p.edge_data[edges_to_kill,1] < 0) edges_to_kill = edges_to_kill[ to_remove] for e in edges_to_kill: # print "Deleting edge e=%d"%e p.delete_edge(e,handle_unpaved=1) # the nodes that are not on the boundary get deleted: for n in nbr_nodes: # node_on_boundary includes internal_guides, so this should be okay. if p.node_on_boundary(n): # SLIDE nodes are reset to HINT so that we're free to resample # the boundary if p.node_data[n,paver.STAT] == paver.SLIDE: # print "Setting node n=%d to HINT"%n p.node_data[n,paver.STAT] = paver.HINT else: # print "Deleting node n=%d"%n p.delete_node(n) old_ncells = p.Ncells() saved_density = None if scale_factor is not None: if not ( self.use_apollo and scale_factor<1.0): saved_density = p.density p.density = p.density * scale_factor print("Repaving...") p.pave_all(n_steps=inf) # n_steps will keep it from renumbering afterwards if saved_density is not None: p.density = saved_density new_cells = np.arange(old_ncells,p.Ncells()) new_scores = self.cell_scores(new_cells) print("Repave: %g => %g"%(starting_score,new_scores.min())) def full(self): self.p.verbose = 0 self.relax_neighborhoods() self.repave_neighborhoods(neighborhood_size=2) self.relax_neighborhoods() self.repave_neighborhoods(neighborhood_size=2,scale_factor=0.9) self.repave_neighborhoods(neighborhood_size=2,scale_factor=0.8) self.repave_neighborhoods(neighborhood_size=3,scale_factor=0.8) self.repave_neighborhoods(neighborhood_size=3,scale_factor=0.75) self.relax_neighborhoods() for i in range(10): scores = self.cell_scores() print("iteration %d, %d bad cells"%(i, (scores<0.1).sum() )) self.p.write_complete('iter%02d.pav'%i) self.repave_neighborhoods(neighborhood_size=2,scale_factor=0.7) self.p.write_complete('iter%02d-repaved.pav'%i) self.relax_neighborhoods(neighborhood_size=5) self.stats() def stats(self): scores = self.cell_scores() print("Total cells with score below 0.1: %d"%( (scores<0.1).sum() )) def gui(self): """ A very simple gui for hand-optimizing. """ g = OptimizeGui(self) g.run() return g if __name__ == '__main__': p = paver.Paving.load_complete('/home/rusty/classes/research/suntans/grids/fullbay-0610/final.pav') p.clean_unpaved() opter = GridOptimizer(p) opter.stats() opter.full() opter.stats() # down to 25. ## Note on using the Apollonius graph for modifying the scale field: # The idea is that rather than temporarily scaling down the density # field to repave a subset of the grid, insert new AG points that will # blend the reduced scale back into the background scale. # This field would be persistent throughout the optimization.
if event.inaxes is not None: if plt.axis() != self.last_axis: print("Viewport has changed") self.last_axis = plt.axis() self.p.default_clip = self.last_axis # simple resolution-dependent plotting: if self.last_axis[1] - self.last_axis[0] > 3000: self.p.plot(boundary=True) else: self.p.plot(boundary=False) else: print("button release but axis is the same")
identifier_body
file.rs
// "Tifflin" Kernel // - By John Hodge (thePowersGang) // // Modules/fs_fat/dir.rs use kernel::prelude::*; use kernel::lib::mem::aref::ArefBorrow; use kernel::vfs::node; const ERROR_SHORTCHAIN: node::IoError = node::IoError::Unknown("Cluster chain terminated early"); pub type FilesystemInner = super::FilesystemInner; pub struct FileNode { fs: ArefBorrow<FilesystemInner>, //parent_dir: u32, first_cluster: u32, size: u32, } impl FileNode { pub fn new_boxed(fs: ArefBorrow<FilesystemInner>, _parent: u32, first_cluster: u32, size: u32) -> Box<FileNode> { Box::new(FileNode { fs: fs, //parent_dir: parent, first_cluster: first_cluster, size: size, }) } }
impl node::NodeBase for FileNode { fn get_id(&self) -> node::InodeId { todo!("FileNode::get_id") } } impl node::File for FileNode { fn size(&self) -> u64 { self.size as u64 } fn truncate(&self, newsize: u64) -> node::Result<u64> { todo!("FileNode::truncate({:#x})", newsize); } fn clear(&self, ofs: u64, size: u64) -> node::Result<()> { todo!("FileNode::clear({:#x}+{:#x}", ofs, size); } fn read(&self, ofs: u64, buf: &mut [u8]) -> node::Result<usize> { // Sanity check and bound parameters if ofs >= self.size as u64 { // out of range return Err( node::IoError::OutOfRange ); } let maxread = (self.size as u64 - ofs) as usize; let buf = if buf.len() > maxread { &mut buf[..maxread] } else { buf }; let read_length = buf.len(); // Seek to correct position in the cluster chain let mut clusters = super::ClusterList::chained(self.fs.reborrow(), self.first_cluster) .skip( (ofs/self.fs.cluster_size as u64) as usize); let ofs = (ofs % self.fs.cluster_size as u64) as usize; // First incomplete cluster let chunks = if ofs != 0 { let cluster = match clusters.next() { Some(v) => v, None => return Err( ERROR_SHORTCHAIN ), }; let short_count = ::core::cmp::min(self.fs.cluster_size-ofs, buf.len()); let c = try!(self.fs.load_cluster(cluster)); let n = buf[..short_count].clone_from_slice( &c[ofs..] ); assert_eq!(n, short_count); buf[short_count..].chunks_mut(self.fs.cluster_size) } else { buf.chunks_mut(self.fs.cluster_size) }; // The rest of the clusters for dst in chunks { let cluster = match clusters.next() { Some(v) => v, None => return Err(ERROR_SHORTCHAIN), }; if dst.len() == self.fs.cluster_size { // Read directly try!(self.fs.read_cluster(cluster, dst)); } else { // Bounce (could leave the bouncing up to read_cluster I guess...) let c = try!(self.fs.load_cluster(cluster)); let n = dst.clone_from_slice( &c ); assert_eq!(n, dst.len()); } } Ok( read_length ) } /// Write data to the file, can only grow the file if ofs==size fn write(&self, ofs: u64, buf: &mut [u8]) -> node::Result<usize> { todo!("FileNode::write({:#x}, {:p})", ofs, ::kernel::lib::SlicePtr(buf)); } }
random_line_split
file.rs
// "Tifflin" Kernel // - By John Hodge (thePowersGang) // // Modules/fs_fat/dir.rs use kernel::prelude::*; use kernel::lib::mem::aref::ArefBorrow; use kernel::vfs::node; const ERROR_SHORTCHAIN: node::IoError = node::IoError::Unknown("Cluster chain terminated early"); pub type FilesystemInner = super::FilesystemInner; pub struct
{ fs: ArefBorrow<FilesystemInner>, //parent_dir: u32, first_cluster: u32, size: u32, } impl FileNode { pub fn new_boxed(fs: ArefBorrow<FilesystemInner>, _parent: u32, first_cluster: u32, size: u32) -> Box<FileNode> { Box::new(FileNode { fs: fs, //parent_dir: parent, first_cluster: first_cluster, size: size, }) } } impl node::NodeBase for FileNode { fn get_id(&self) -> node::InodeId { todo!("FileNode::get_id") } } impl node::File for FileNode { fn size(&self) -> u64 { self.size as u64 } fn truncate(&self, newsize: u64) -> node::Result<u64> { todo!("FileNode::truncate({:#x})", newsize); } fn clear(&self, ofs: u64, size: u64) -> node::Result<()> { todo!("FileNode::clear({:#x}+{:#x}", ofs, size); } fn read(&self, ofs: u64, buf: &mut [u8]) -> node::Result<usize> { // Sanity check and bound parameters if ofs >= self.size as u64 { // out of range return Err( node::IoError::OutOfRange ); } let maxread = (self.size as u64 - ofs) as usize; let buf = if buf.len() > maxread { &mut buf[..maxread] } else { buf }; let read_length = buf.len(); // Seek to correct position in the cluster chain let mut clusters = super::ClusterList::chained(self.fs.reborrow(), self.first_cluster) .skip( (ofs/self.fs.cluster_size as u64) as usize); let ofs = (ofs % self.fs.cluster_size as u64) as usize; // First incomplete cluster let chunks = if ofs != 0 { let cluster = match clusters.next() { Some(v) => v, None => return Err( ERROR_SHORTCHAIN ), }; let short_count = ::core::cmp::min(self.fs.cluster_size-ofs, buf.len()); let c = try!(self.fs.load_cluster(cluster)); let n = buf[..short_count].clone_from_slice( &c[ofs..] ); assert_eq!(n, short_count); buf[short_count..].chunks_mut(self.fs.cluster_size) } else { buf.chunks_mut(self.fs.cluster_size) }; // The rest of the clusters for dst in chunks { let cluster = match clusters.next() { Some(v) => v, None => return Err(ERROR_SHORTCHAIN), }; if dst.len() == self.fs.cluster_size { // Read directly try!(self.fs.read_cluster(cluster, dst)); } else { // Bounce (could leave the bouncing up to read_cluster I guess...) let c = try!(self.fs.load_cluster(cluster)); let n = dst.clone_from_slice( &c ); assert_eq!(n, dst.len()); } } Ok( read_length ) } /// Write data to the file, can only grow the file if ofs==size fn write(&self, ofs: u64, buf: &mut [u8]) -> node::Result<usize> { todo!("FileNode::write({:#x}, {:p})", ofs, ::kernel::lib::SlicePtr(buf)); } }
FileNode
identifier_name
file.rs
// "Tifflin" Kernel // - By John Hodge (thePowersGang) // // Modules/fs_fat/dir.rs use kernel::prelude::*; use kernel::lib::mem::aref::ArefBorrow; use kernel::vfs::node; const ERROR_SHORTCHAIN: node::IoError = node::IoError::Unknown("Cluster chain terminated early"); pub type FilesystemInner = super::FilesystemInner; pub struct FileNode { fs: ArefBorrow<FilesystemInner>, //parent_dir: u32, first_cluster: u32, size: u32, } impl FileNode { pub fn new_boxed(fs: ArefBorrow<FilesystemInner>, _parent: u32, first_cluster: u32, size: u32) -> Box<FileNode> { Box::new(FileNode { fs: fs, //parent_dir: parent, first_cluster: first_cluster, size: size, }) } } impl node::NodeBase for FileNode { fn get_id(&self) -> node::InodeId
} impl node::File for FileNode { fn size(&self) -> u64 { self.size as u64 } fn truncate(&self, newsize: u64) -> node::Result<u64> { todo!("FileNode::truncate({:#x})", newsize); } fn clear(&self, ofs: u64, size: u64) -> node::Result<()> { todo!("FileNode::clear({:#x}+{:#x}", ofs, size); } fn read(&self, ofs: u64, buf: &mut [u8]) -> node::Result<usize> { // Sanity check and bound parameters if ofs >= self.size as u64 { // out of range return Err( node::IoError::OutOfRange ); } let maxread = (self.size as u64 - ofs) as usize; let buf = if buf.len() > maxread { &mut buf[..maxread] } else { buf }; let read_length = buf.len(); // Seek to correct position in the cluster chain let mut clusters = super::ClusterList::chained(self.fs.reborrow(), self.first_cluster) .skip( (ofs/self.fs.cluster_size as u64) as usize); let ofs = (ofs % self.fs.cluster_size as u64) as usize; // First incomplete cluster let chunks = if ofs != 0 { let cluster = match clusters.next() { Some(v) => v, None => return Err( ERROR_SHORTCHAIN ), }; let short_count = ::core::cmp::min(self.fs.cluster_size-ofs, buf.len()); let c = try!(self.fs.load_cluster(cluster)); let n = buf[..short_count].clone_from_slice( &c[ofs..] ); assert_eq!(n, short_count); buf[short_count..].chunks_mut(self.fs.cluster_size) } else { buf.chunks_mut(self.fs.cluster_size) }; // The rest of the clusters for dst in chunks { let cluster = match clusters.next() { Some(v) => v, None => return Err(ERROR_SHORTCHAIN), }; if dst.len() == self.fs.cluster_size { // Read directly try!(self.fs.read_cluster(cluster, dst)); } else { // Bounce (could leave the bouncing up to read_cluster I guess...) let c = try!(self.fs.load_cluster(cluster)); let n = dst.clone_from_slice( &c ); assert_eq!(n, dst.len()); } } Ok( read_length ) } /// Write data to the file, can only grow the file if ofs==size fn write(&self, ofs: u64, buf: &mut [u8]) -> node::Result<usize> { todo!("FileNode::write({:#x}, {:p})", ofs, ::kernel::lib::SlicePtr(buf)); } }
{ todo!("FileNode::get_id") }
identifier_body
chrome.ts
import { RawConfig } from './config.js' import { ProxyHook, Storage, WebHook } from './switchyd.js' /* eslint-disable no-unused-vars */ declare type saveConfig = { 'switchyd.config':RawConfig } declare const chrome:{ webRequest :WebHook proxy : ProxyHook storage : { local : { set:(items:saveConfig)=>Promise<void>, get:(key:string)=>Promise<saveConfig> } } } export function resolveStorage ():Storage { if (chrome && chrome.storage) { return { get: async ():Promise<RawConfig> => { const save = await chrome.storage.local.get('switchyd.config') if (save['switchyd.config']) { return save['switchyd.config'] } // try local storage const defaultConfig = {
listen: [ 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_TIMED_OUT', 'net::ERR_SSL_PROTOCOL_ERROR', 'net::ERR_TIMED_OUT' ], server: 'SOCKS5 127.0.0.1:10086' }] } await chrome.storage.local.set({ 'switchyd.config': defaultConfig }) const config = await chrome.storage.local.get('switchyd.config') return config['switchyd.config'] }, set: (config:RawConfig):Promise<void> => { return chrome.storage.local.set({ 'switchyd.config': config }) } } } let mockConfig:RawConfig = { version: 3, servers: [ { accepts: ['www.google.com', 'www.facebook.com'], denys: ['www.weibo.com', 'www.baidu.com'], listen: [ 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_TIMED_OUT', 'net::ERR_SSL_PROTOCOL_ERROR', 'net::ERR_TIMED_OUT' ], server: 'SOCKS5:127.0.0.1:10086' }, { accepts: ['twitter.com', 'github.com'], denys: ['www.douban.com'], listen: [ 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_TIMED_OUT', 'net::ERR_SSL_PROTOCOL_ERROR', 'net::ERR_TIMED_OUT' ], server: 'SOCKS5:127.0.0.2:10086' } ] } return { get: ():Promise<RawConfig> => { return Promise.resolve(mockConfig) }, set: (config:RawConfig):Promise<void> => { mockConfig = config return Promise.resolve() } } }
version: 3, servers: [{ accepts: [], denys: [],
random_line_split
chrome.ts
import { RawConfig } from './config.js' import { ProxyHook, Storage, WebHook } from './switchyd.js' /* eslint-disable no-unused-vars */ declare type saveConfig = { 'switchyd.config':RawConfig } declare const chrome:{ webRequest :WebHook proxy : ProxyHook storage : { local : { set:(items:saveConfig)=>Promise<void>, get:(key:string)=>Promise<saveConfig> } } } export function resolveStorage ():Storage
{ if (chrome && chrome.storage) { return { get: async ():Promise<RawConfig> => { const save = await chrome.storage.local.get('switchyd.config') if (save['switchyd.config']) { return save['switchyd.config'] } // try local storage const defaultConfig = { version: 3, servers: [{ accepts: [], denys: [], listen: [ 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_TIMED_OUT', 'net::ERR_SSL_PROTOCOL_ERROR', 'net::ERR_TIMED_OUT' ], server: 'SOCKS5 127.0.0.1:10086' }] } await chrome.storage.local.set({ 'switchyd.config': defaultConfig }) const config = await chrome.storage.local.get('switchyd.config') return config['switchyd.config'] }, set: (config:RawConfig):Promise<void> => { return chrome.storage.local.set({ 'switchyd.config': config }) } } } let mockConfig:RawConfig = { version: 3, servers: [ { accepts: ['www.google.com', 'www.facebook.com'], denys: ['www.weibo.com', 'www.baidu.com'], listen: [ 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_TIMED_OUT', 'net::ERR_SSL_PROTOCOL_ERROR', 'net::ERR_TIMED_OUT' ], server: 'SOCKS5:127.0.0.1:10086' }, { accepts: ['twitter.com', 'github.com'], denys: ['www.douban.com'], listen: [ 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_TIMED_OUT', 'net::ERR_SSL_PROTOCOL_ERROR', 'net::ERR_TIMED_OUT' ], server: 'SOCKS5:127.0.0.2:10086' } ] } return { get: ():Promise<RawConfig> => { return Promise.resolve(mockConfig) }, set: (config:RawConfig):Promise<void> => { mockConfig = config return Promise.resolve() } } }
identifier_body
chrome.ts
import { RawConfig } from './config.js' import { ProxyHook, Storage, WebHook } from './switchyd.js' /* eslint-disable no-unused-vars */ declare type saveConfig = { 'switchyd.config':RawConfig } declare const chrome:{ webRequest :WebHook proxy : ProxyHook storage : { local : { set:(items:saveConfig)=>Promise<void>, get:(key:string)=>Promise<saveConfig> } } } export function
():Storage { if (chrome && chrome.storage) { return { get: async ():Promise<RawConfig> => { const save = await chrome.storage.local.get('switchyd.config') if (save['switchyd.config']) { return save['switchyd.config'] } // try local storage const defaultConfig = { version: 3, servers: [{ accepts: [], denys: [], listen: [ 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_TIMED_OUT', 'net::ERR_SSL_PROTOCOL_ERROR', 'net::ERR_TIMED_OUT' ], server: 'SOCKS5 127.0.0.1:10086' }] } await chrome.storage.local.set({ 'switchyd.config': defaultConfig }) const config = await chrome.storage.local.get('switchyd.config') return config['switchyd.config'] }, set: (config:RawConfig):Promise<void> => { return chrome.storage.local.set({ 'switchyd.config': config }) } } } let mockConfig:RawConfig = { version: 3, servers: [ { accepts: ['www.google.com', 'www.facebook.com'], denys: ['www.weibo.com', 'www.baidu.com'], listen: [ 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_TIMED_OUT', 'net::ERR_SSL_PROTOCOL_ERROR', 'net::ERR_TIMED_OUT' ], server: 'SOCKS5:127.0.0.1:10086' }, { accepts: ['twitter.com', 'github.com'], denys: ['www.douban.com'], listen: [ 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_TIMED_OUT', 'net::ERR_SSL_PROTOCOL_ERROR', 'net::ERR_TIMED_OUT' ], server: 'SOCKS5:127.0.0.2:10086' } ] } return { get: ():Promise<RawConfig> => { return Promise.resolve(mockConfig) }, set: (config:RawConfig):Promise<void> => { mockConfig = config return Promise.resolve() } } }
resolveStorage
identifier_name
chrome.ts
import { RawConfig } from './config.js' import { ProxyHook, Storage, WebHook } from './switchyd.js' /* eslint-disable no-unused-vars */ declare type saveConfig = { 'switchyd.config':RawConfig } declare const chrome:{ webRequest :WebHook proxy : ProxyHook storage : { local : { set:(items:saveConfig)=>Promise<void>, get:(key:string)=>Promise<saveConfig> } } } export function resolveStorage ():Storage { if (chrome && chrome.storage) { return { get: async ():Promise<RawConfig> => { const save = await chrome.storage.local.get('switchyd.config') if (save['switchyd.config'])
// try local storage const defaultConfig = { version: 3, servers: [{ accepts: [], denys: [], listen: [ 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_TIMED_OUT', 'net::ERR_SSL_PROTOCOL_ERROR', 'net::ERR_TIMED_OUT' ], server: 'SOCKS5 127.0.0.1:10086' }] } await chrome.storage.local.set({ 'switchyd.config': defaultConfig }) const config = await chrome.storage.local.get('switchyd.config') return config['switchyd.config'] }, set: (config:RawConfig):Promise<void> => { return chrome.storage.local.set({ 'switchyd.config': config }) } } } let mockConfig:RawConfig = { version: 3, servers: [ { accepts: ['www.google.com', 'www.facebook.com'], denys: ['www.weibo.com', 'www.baidu.com'], listen: [ 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_TIMED_OUT', 'net::ERR_SSL_PROTOCOL_ERROR', 'net::ERR_TIMED_OUT' ], server: 'SOCKS5:127.0.0.1:10086' }, { accepts: ['twitter.com', 'github.com'], denys: ['www.douban.com'], listen: [ 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_TIMED_OUT', 'net::ERR_SSL_PROTOCOL_ERROR', 'net::ERR_TIMED_OUT' ], server: 'SOCKS5:127.0.0.2:10086' } ] } return { get: ():Promise<RawConfig> => { return Promise.resolve(mockConfig) }, set: (config:RawConfig):Promise<void> => { mockConfig = config return Promise.resolve() } } }
{ return save['switchyd.config'] }
conditional_block
test_cew.py
#!/usr/bin/env python # coding=utf-8 # aeneas is a Python/C library and a set of tools # to automagically synchronize audio and text (aka forced alignment) # # Copyright (C) 2012-2013, Alberto Pettarin (www.albertopettarin.it) # Copyright (C) 2013-2015, ReadBeyond Srl (www.readbeyond.it) # Copyright (C) 2015-2017, Alberto Pettarin (www.albertopettarin.it) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import unittest import aeneas.globalfunctions as gf class TestCEW(unittest.TestCase): def test_cew_synthesize_multiple(self):
def test_cew_synthesize_multiple_lang(self): handler, output_file_path = gf.tmp_file(suffix=".wav") try: c_quit_after = 0.0 c_backwards = 0 c_text = [ (u"en", u"Dummy 1"), # NOTE cew requires the actual eSpeak voice code (u"it", u"Segnaposto 2"), # NOTE cew requires the actual eSpeak voice code (u"en", u"Dummy 3"), # NOTE cew requires the actual eSpeak voice code ] import aeneas.cew.cew sr, sf, intervals = aeneas.cew.cew.synthesize_multiple( output_file_path, c_quit_after, c_backwards, c_text ) self.assertEqual(sr, 22050) self.assertEqual(sf, 3) self.assertEqual(len(intervals), 3) except ImportError: pass gf.delete_file(handler, output_file_path) if __name__ == "__main__": unittest.main()
handler, output_file_path = gf.tmp_file(suffix=".wav") try: c_quit_after = 0.0 c_backwards = 0 c_text = [ (u"en", u"Dummy 1"), # NOTE cew requires the actual eSpeak voice code (u"en", u"Dummy 2"), # NOTE cew requires the actual eSpeak voice code (u"en", u"Dummy 3"), # NOTE cew requires the actual eSpeak voice code ] import aeneas.cew.cew sr, sf, intervals = aeneas.cew.cew.synthesize_multiple( output_file_path, c_quit_after, c_backwards, c_text ) self.assertEqual(sr, 22050) self.assertEqual(sf, 3) self.assertEqual(len(intervals), 3) except ImportError: pass gf.delete_file(handler, output_file_path)
identifier_body
test_cew.py
#!/usr/bin/env python # coding=utf-8 # aeneas is a Python/C library and a set of tools # to automagically synchronize audio and text (aka forced alignment) # # Copyright (C) 2012-2013, Alberto Pettarin (www.albertopettarin.it) # Copyright (C) 2013-2015, ReadBeyond Srl (www.readbeyond.it) # Copyright (C) 2015-2017, Alberto Pettarin (www.albertopettarin.it) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import unittest import aeneas.globalfunctions as gf class TestCEW(unittest.TestCase): def test_cew_synthesize_multiple(self): handler, output_file_path = gf.tmp_file(suffix=".wav") try: c_quit_after = 0.0 c_backwards = 0 c_text = [ (u"en", u"Dummy 1"), # NOTE cew requires the actual eSpeak voice code (u"en", u"Dummy 2"), # NOTE cew requires the actual eSpeak voice code (u"en", u"Dummy 3"), # NOTE cew requires the actual eSpeak voice code ] import aeneas.cew.cew sr, sf, intervals = aeneas.cew.cew.synthesize_multiple( output_file_path, c_quit_after, c_backwards, c_text ) self.assertEqual(sr, 22050) self.assertEqual(sf, 3) self.assertEqual(len(intervals), 3) except ImportError: pass gf.delete_file(handler, output_file_path) def test_cew_synthesize_multiple_lang(self): handler, output_file_path = gf.tmp_file(suffix=".wav") try: c_quit_after = 0.0 c_backwards = 0 c_text = [ (u"en", u"Dummy 1"), # NOTE cew requires the actual eSpeak voice code (u"it", u"Segnaposto 2"), # NOTE cew requires the actual eSpeak voice code (u"en", u"Dummy 3"), # NOTE cew requires the actual eSpeak voice code ] import aeneas.cew.cew sr, sf, intervals = aeneas.cew.cew.synthesize_multiple( output_file_path, c_quit_after, c_backwards, c_text ) self.assertEqual(sr, 22050) self.assertEqual(sf, 3) self.assertEqual(len(intervals), 3) except ImportError: pass gf.delete_file(handler, output_file_path) if __name__ == "__main__":
unittest.main()
conditional_block
test_cew.py
#!/usr/bin/env python # coding=utf-8 # aeneas is a Python/C library and a set of tools # to automagically synchronize audio and text (aka forced alignment) # # Copyright (C) 2012-2013, Alberto Pettarin (www.albertopettarin.it) # Copyright (C) 2013-2015, ReadBeyond Srl (www.readbeyond.it) # Copyright (C) 2015-2017, Alberto Pettarin (www.albertopettarin.it) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import unittest import aeneas.globalfunctions as gf class TestCEW(unittest.TestCase): def test_cew_synthesize_multiple(self): handler, output_file_path = gf.tmp_file(suffix=".wav") try: c_quit_after = 0.0 c_backwards = 0 c_text = [ (u"en", u"Dummy 1"), # NOTE cew requires the actual eSpeak voice code (u"en", u"Dummy 2"), # NOTE cew requires the actual eSpeak voice code (u"en", u"Dummy 3"), # NOTE cew requires the actual eSpeak voice code ]
c_backwards, c_text ) self.assertEqual(sr, 22050) self.assertEqual(sf, 3) self.assertEqual(len(intervals), 3) except ImportError: pass gf.delete_file(handler, output_file_path) def test_cew_synthesize_multiple_lang(self): handler, output_file_path = gf.tmp_file(suffix=".wav") try: c_quit_after = 0.0 c_backwards = 0 c_text = [ (u"en", u"Dummy 1"), # NOTE cew requires the actual eSpeak voice code (u"it", u"Segnaposto 2"), # NOTE cew requires the actual eSpeak voice code (u"en", u"Dummy 3"), # NOTE cew requires the actual eSpeak voice code ] import aeneas.cew.cew sr, sf, intervals = aeneas.cew.cew.synthesize_multiple( output_file_path, c_quit_after, c_backwards, c_text ) self.assertEqual(sr, 22050) self.assertEqual(sf, 3) self.assertEqual(len(intervals), 3) except ImportError: pass gf.delete_file(handler, output_file_path) if __name__ == "__main__": unittest.main()
import aeneas.cew.cew sr, sf, intervals = aeneas.cew.cew.synthesize_multiple( output_file_path, c_quit_after,
random_line_split
test_cew.py
#!/usr/bin/env python # coding=utf-8 # aeneas is a Python/C library and a set of tools # to automagically synchronize audio and text (aka forced alignment) # # Copyright (C) 2012-2013, Alberto Pettarin (www.albertopettarin.it) # Copyright (C) 2013-2015, ReadBeyond Srl (www.readbeyond.it) # Copyright (C) 2015-2017, Alberto Pettarin (www.albertopettarin.it) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import unittest import aeneas.globalfunctions as gf class TestCEW(unittest.TestCase): def
(self): handler, output_file_path = gf.tmp_file(suffix=".wav") try: c_quit_after = 0.0 c_backwards = 0 c_text = [ (u"en", u"Dummy 1"), # NOTE cew requires the actual eSpeak voice code (u"en", u"Dummy 2"), # NOTE cew requires the actual eSpeak voice code (u"en", u"Dummy 3"), # NOTE cew requires the actual eSpeak voice code ] import aeneas.cew.cew sr, sf, intervals = aeneas.cew.cew.synthesize_multiple( output_file_path, c_quit_after, c_backwards, c_text ) self.assertEqual(sr, 22050) self.assertEqual(sf, 3) self.assertEqual(len(intervals), 3) except ImportError: pass gf.delete_file(handler, output_file_path) def test_cew_synthesize_multiple_lang(self): handler, output_file_path = gf.tmp_file(suffix=".wav") try: c_quit_after = 0.0 c_backwards = 0 c_text = [ (u"en", u"Dummy 1"), # NOTE cew requires the actual eSpeak voice code (u"it", u"Segnaposto 2"), # NOTE cew requires the actual eSpeak voice code (u"en", u"Dummy 3"), # NOTE cew requires the actual eSpeak voice code ] import aeneas.cew.cew sr, sf, intervals = aeneas.cew.cew.synthesize_multiple( output_file_path, c_quit_after, c_backwards, c_text ) self.assertEqual(sr, 22050) self.assertEqual(sf, 3) self.assertEqual(len(intervals), 3) except ImportError: pass gf.delete_file(handler, output_file_path) if __name__ == "__main__": unittest.main()
test_cew_synthesize_multiple
identifier_name
cli.js
#!/usr/bin/env node 'use strict' const localWebServer = require('../') const cliOptions = require('../lib/cli-options') const commandLineArgs = require('command-line-args') const ansi = require('ansi-escape-sequences') const loadConfig = require('config-master') const path = require('path') const os = require('os') const arrayify = require('array-back') const t = require('typical') const flatten = require('reduce-flatten') const cli = commandLineArgs(cliOptions.definitions) const usage = cli.getUsage(cliOptions.usageData) const stored = loadConfig('local-web-server') let options let isHttps = false try { options = collectOptions() } catch (err) { stop([ `[red]{Error}: ${err.message}`, usage ], 1) return } if (options.misc.help) { stop(usage, 0) } else if (options.misc.config) { stop(JSON.stringify(options.server, null, ' '), 0) } else { const valid = validateOptions(options) if (!valid) { /* gracefully end the process */ return } const app = localWebServer({ static: { root: options.server.directory, options: { hidden: true } }, serveIndex: { path: options.server.directory, options: { icons: true, hidden: true } }, log: { format: options.server['log-format'] }, compress: options.server.compress, mime: options.server.mime, forbid: options.server.forbid, spa: options.server.spa, 'no-cache': options.server['no-cache'], rewrite: options.server.rewrite, verbose: options.server.verbose, mocks: options.server.mocks }) app.on('error', err => { if (options.server['log-format']) { console.error(ansi.format(err.message, 'red')) } }) if (options.server.https) { options.server.key = path.resolve(__dirname, '..', 'ssl', '127.0.0.1.key') options.server.cert = path.resolve(__dirname, '..', 'ssl', '127.0.0.1.crt') } if (options.server.key && options.server.cert) { const https = require('https') const fs = require('fs') isHttps = true const serverOptions = { key: fs.readFileSync(options.server.key), cert: fs.readFileSync(options.server.cert) } const server = https.createServer(serverOptions, app.callback()) server.listen(options.server.port, onServerUp) } else { app.listen(options.server.port, onServerUp) } } function stop (msgs, exitCode) { arrayify(msgs).forEach(msg => console.error(ansi.format(msg))) process.exitCode = exitCode } function onServerUp () { let ipList = Object.keys(os.networkInterfaces()) .map(key => os.networkInterfaces()[key]) .reduce(flatten, []) .filter(iface => iface.family === 'IPv4') ipList.unshift({ address: os.hostname() }) ipList = ipList .map(iface => `[underline]{${isHttps ? 'https' : 'http'}://${iface.address}:${options.server.port}}`) .join(', ') console.error(ansi.format( path.resolve(options.server.directory) === process.cwd() ? `serving at ${ipList}` : `serving [underline]{${options.server.directory}} at ${ipList}` )) } function
() { let options = {} /* parse command line args */ options = cli.parse() const builtIn = { port: 8000, directory: process.cwd(), forbid: [], rewrite: [] } if (options.server.rewrite) { options.server.rewrite = parseRewriteRules(options.server.rewrite) } /* override built-in defaults with stored config and then command line args */ options.server = Object.assign(builtIn, stored, options.server) return options } function parseRewriteRules (rules) { return rules && rules.map(rule => { const matches = rule.match(/(\S*)\s*->\s*(\S*)/) return { from: matches[1], to: matches[2] } }) } function validateOptions (options) { let valid = true function invalid (msg) { return `[red underline]{Invalid:} [bold]{${msg}}` } if (!t.isNumber(options.server.port)) { stop([ invalid(`--port must be numeric`), usage ], 1) valid = false } return valid }
collectOptions
identifier_name
cli.js
#!/usr/bin/env node 'use strict' const localWebServer = require('../') const cliOptions = require('../lib/cli-options') const commandLineArgs = require('command-line-args') const ansi = require('ansi-escape-sequences') const loadConfig = require('config-master') const path = require('path') const os = require('os') const arrayify = require('array-back') const t = require('typical') const flatten = require('reduce-flatten') const cli = commandLineArgs(cliOptions.definitions) const usage = cli.getUsage(cliOptions.usageData) const stored = loadConfig('local-web-server') let options let isHttps = false try { options = collectOptions() } catch (err) { stop([ `[red]{Error}: ${err.message}`, usage ], 1) return } if (options.misc.help) { stop(usage, 0) } else if (options.misc.config) { stop(JSON.stringify(options.server, null, ' '), 0) } else { const valid = validateOptions(options) if (!valid) { /* gracefully end the process */ return } const app = localWebServer({ static: { root: options.server.directory, options: { hidden: true } }, serveIndex: { path: options.server.directory, options: { icons: true, hidden: true } }, log: { format: options.server['log-format'] }, compress: options.server.compress, mime: options.server.mime, forbid: options.server.forbid, spa: options.server.spa, 'no-cache': options.server['no-cache'], rewrite: options.server.rewrite, verbose: options.server.verbose, mocks: options.server.mocks }) app.on('error', err => { if (options.server['log-format']) { console.error(ansi.format(err.message, 'red')) } }) if (options.server.https) { options.server.key = path.resolve(__dirname, '..', 'ssl', '127.0.0.1.key') options.server.cert = path.resolve(__dirname, '..', 'ssl', '127.0.0.1.crt') } if (options.server.key && options.server.cert) { const https = require('https') const fs = require('fs') isHttps = true const serverOptions = { key: fs.readFileSync(options.server.key), cert: fs.readFileSync(options.server.cert) } const server = https.createServer(serverOptions, app.callback()) server.listen(options.server.port, onServerUp) } else { app.listen(options.server.port, onServerUp) } } function stop (msgs, exitCode) { arrayify(msgs).forEach(msg => console.error(ansi.format(msg))) process.exitCode = exitCode } function onServerUp () { let ipList = Object.keys(os.networkInterfaces()) .map(key => os.networkInterfaces()[key]) .reduce(flatten, []) .filter(iface => iface.family === 'IPv4') ipList.unshift({ address: os.hostname() }) ipList = ipList .map(iface => `[underline]{${isHttps ? 'https' : 'http'}://${iface.address}:${options.server.port}}`) .join(', ') console.error(ansi.format( path.resolve(options.server.directory) === process.cwd() ? `serving at ${ipList}` : `serving [underline]{${options.server.directory}} at ${ipList}` )) } function collectOptions ()
function parseRewriteRules (rules) { return rules && rules.map(rule => { const matches = rule.match(/(\S*)\s*->\s*(\S*)/) return { from: matches[1], to: matches[2] } }) } function validateOptions (options) { let valid = true function invalid (msg) { return `[red underline]{Invalid:} [bold]{${msg}}` } if (!t.isNumber(options.server.port)) { stop([ invalid(`--port must be numeric`), usage ], 1) valid = false } return valid }
{ let options = {} /* parse command line args */ options = cli.parse() const builtIn = { port: 8000, directory: process.cwd(), forbid: [], rewrite: [] } if (options.server.rewrite) { options.server.rewrite = parseRewriteRules(options.server.rewrite) } /* override built-in defaults with stored config and then command line args */ options.server = Object.assign(builtIn, stored, options.server) return options }
identifier_body
cli.js
#!/usr/bin/env node 'use strict' const localWebServer = require('../') const cliOptions = require('../lib/cli-options') const commandLineArgs = require('command-line-args') const ansi = require('ansi-escape-sequences') const loadConfig = require('config-master') const path = require('path') const os = require('os') const arrayify = require('array-back') const t = require('typical') const flatten = require('reduce-flatten') const cli = commandLineArgs(cliOptions.definitions) const usage = cli.getUsage(cliOptions.usageData) const stored = loadConfig('local-web-server') let options let isHttps = false try { options = collectOptions() } catch (err) { stop([ `[red]{Error}: ${err.message}`, usage ], 1) return } if (options.misc.help) { stop(usage, 0) } else if (options.misc.config) { stop(JSON.stringify(options.server, null, ' '), 0) } else { const valid = validateOptions(options) if (!valid) { /* gracefully end the process */ return } const app = localWebServer({ static: { root: options.server.directory, options: { hidden: true } }, serveIndex: { path: options.server.directory, options: { icons: true, hidden: true } }, log: { format: options.server['log-format'] }, compress: options.server.compress, mime: options.server.mime, forbid: options.server.forbid, spa: options.server.spa, 'no-cache': options.server['no-cache'], rewrite: options.server.rewrite, verbose: options.server.verbose, mocks: options.server.mocks }) app.on('error', err => { if (options.server['log-format']) { console.error(ansi.format(err.message, 'red')) } }) if (options.server.https) { options.server.key = path.resolve(__dirname, '..', 'ssl', '127.0.0.1.key') options.server.cert = path.resolve(__dirname, '..', 'ssl', '127.0.0.1.crt') } if (options.server.key && options.server.cert) { const https = require('https') const fs = require('fs') isHttps = true const serverOptions = { key: fs.readFileSync(options.server.key), cert: fs.readFileSync(options.server.cert) } const server = https.createServer(serverOptions, app.callback()) server.listen(options.server.port, onServerUp) } else
} function stop (msgs, exitCode) { arrayify(msgs).forEach(msg => console.error(ansi.format(msg))) process.exitCode = exitCode } function onServerUp () { let ipList = Object.keys(os.networkInterfaces()) .map(key => os.networkInterfaces()[key]) .reduce(flatten, []) .filter(iface => iface.family === 'IPv4') ipList.unshift({ address: os.hostname() }) ipList = ipList .map(iface => `[underline]{${isHttps ? 'https' : 'http'}://${iface.address}:${options.server.port}}`) .join(', ') console.error(ansi.format( path.resolve(options.server.directory) === process.cwd() ? `serving at ${ipList}` : `serving [underline]{${options.server.directory}} at ${ipList}` )) } function collectOptions () { let options = {} /* parse command line args */ options = cli.parse() const builtIn = { port: 8000, directory: process.cwd(), forbid: [], rewrite: [] } if (options.server.rewrite) { options.server.rewrite = parseRewriteRules(options.server.rewrite) } /* override built-in defaults with stored config and then command line args */ options.server = Object.assign(builtIn, stored, options.server) return options } function parseRewriteRules (rules) { return rules && rules.map(rule => { const matches = rule.match(/(\S*)\s*->\s*(\S*)/) return { from: matches[1], to: matches[2] } }) } function validateOptions (options) { let valid = true function invalid (msg) { return `[red underline]{Invalid:} [bold]{${msg}}` } if (!t.isNumber(options.server.port)) { stop([ invalid(`--port must be numeric`), usage ], 1) valid = false } return valid }
{ app.listen(options.server.port, onServerUp) }
conditional_block
cli.js
#!/usr/bin/env node 'use strict' const localWebServer = require('../') const cliOptions = require('../lib/cli-options') const commandLineArgs = require('command-line-args') const ansi = require('ansi-escape-sequences') const loadConfig = require('config-master') const path = require('path') const os = require('os') const arrayify = require('array-back') const t = require('typical') const flatten = require('reduce-flatten') const cli = commandLineArgs(cliOptions.definitions) const usage = cli.getUsage(cliOptions.usageData) const stored = loadConfig('local-web-server') let options let isHttps = false try { options = collectOptions() } catch (err) { stop([ `[red]{Error}: ${err.message}`, usage ], 1) return } if (options.misc.help) { stop(usage, 0) } else if (options.misc.config) { stop(JSON.stringify(options.server, null, ' '), 0) } else { const valid = validateOptions(options) if (!valid) { /* gracefully end the process */ return } const app = localWebServer({ static: { root: options.server.directory, options: { hidden: true } }, serveIndex: { path: options.server.directory, options: { icons: true, hidden: true } }, log: { format: options.server['log-format'] }, compress: options.server.compress, mime: options.server.mime, forbid: options.server.forbid, spa: options.server.spa, 'no-cache': options.server['no-cache'], rewrite: options.server.rewrite, verbose: options.server.verbose, mocks: options.server.mocks }) app.on('error', err => { if (options.server['log-format']) { console.error(ansi.format(err.message, 'red')) } }) if (options.server.https) { options.server.key = path.resolve(__dirname, '..', 'ssl', '127.0.0.1.key') options.server.cert = path.resolve(__dirname, '..', 'ssl', '127.0.0.1.crt') } if (options.server.key && options.server.cert) { const https = require('https') const fs = require('fs') isHttps = true const serverOptions = { key: fs.readFileSync(options.server.key), cert: fs.readFileSync(options.server.cert) } const server = https.createServer(serverOptions, app.callback()) server.listen(options.server.port, onServerUp) } else { app.listen(options.server.port, onServerUp) } } function stop (msgs, exitCode) { arrayify(msgs).forEach(msg => console.error(ansi.format(msg))) process.exitCode = exitCode } function onServerUp () { let ipList = Object.keys(os.networkInterfaces()) .map(key => os.networkInterfaces()[key]) .reduce(flatten, []) .filter(iface => iface.family === 'IPv4') ipList.unshift({ address: os.hostname() }) ipList = ipList .map(iface => `[underline]{${isHttps ? 'https' : 'http'}://${iface.address}:${options.server.port}}`) .join(', ') console.error(ansi.format( path.resolve(options.server.directory) === process.cwd() ? `serving at ${ipList}` : `serving [underline]{${options.server.directory}} at ${ipList}` )) } function collectOptions () { let options = {} /* parse command line args */ options = cli.parse() const builtIn = { port: 8000, directory: process.cwd(), forbid: [], rewrite: []
if (options.server.rewrite) { options.server.rewrite = parseRewriteRules(options.server.rewrite) } /* override built-in defaults with stored config and then command line args */ options.server = Object.assign(builtIn, stored, options.server) return options } function parseRewriteRules (rules) { return rules && rules.map(rule => { const matches = rule.match(/(\S*)\s*->\s*(\S*)/) return { from: matches[1], to: matches[2] } }) } function validateOptions (options) { let valid = true function invalid (msg) { return `[red underline]{Invalid:} [bold]{${msg}}` } if (!t.isNumber(options.server.port)) { stop([ invalid(`--port must be numeric`), usage ], 1) valid = false } return valid }
}
random_line_split
acct_stop_process.py
#!/usr/bin/env python #coding=utf-8 from twisted.python import log from toughradius.radiusd.settings import * import logging import datetime def process(req=None,user=None,radiusd=None,**kwargs): if not req.get_acct_status_type() == STATUS_TYPE_STOP: return runstat=radiusd.runstat store = radiusd.store runstat.acct_stop += 1 ticket = req.get_ticket() if not ticket.nas_addr:
_datetime = datetime.datetime.now() online = store.get_online(ticket.nas_addr,ticket.acct_session_id) if not online: session_time = ticket.acct_session_time stop_time = _datetime.strftime( "%Y-%m-%d %H:%M:%S") start_time = (_datetime - datetime.timedelta(seconds=int(session_time))).strftime( "%Y-%m-%d %H:%M:%S") ticket.acct_start_time = start_time ticket.acct_stop_time = stop_time ticket.start_source= STATUS_TYPE_STOP ticket.stop_source = STATUS_TYPE_STOP store.add_ticket(ticket) else: store.del_online(ticket.nas_addr,ticket.acct_session_id) ticket.acct_start_time = online['acct_start_time'] ticket.acct_stop_time= _datetime.strftime( "%Y-%m-%d %H:%M:%S") ticket.start_source = online['start_source'] ticket.stop_source = STATUS_TYPE_STOP store.add_ticket(ticket) radiusd.syslog.info('[username:%s] Accounting stop request, remove online'%req.get_user_name(),level=logging.INFO)
ticket.nas_addr = req.source[0]
conditional_block
acct_stop_process.py
#!/usr/bin/env python #coding=utf-8 from twisted.python import log from toughradius.radiusd.settings import * import logging import datetime def process(req=None,user=None,radiusd=None,**kwargs): if not req.get_acct_status_type() == STATUS_TYPE_STOP: return runstat=radiusd.runstat store = radiusd.store runstat.acct_stop += 1 ticket = req.get_ticket() if not ticket.nas_addr: ticket.nas_addr = req.source[0] _datetime = datetime.datetime.now() online = store.get_online(ticket.nas_addr,ticket.acct_session_id) if not online: session_time = ticket.acct_session_time stop_time = _datetime.strftime( "%Y-%m-%d %H:%M:%S") start_time = (_datetime - datetime.timedelta(seconds=int(session_time))).strftime( "%Y-%m-%d %H:%M:%S") ticket.acct_start_time = start_time ticket.acct_stop_time = stop_time ticket.start_source= STATUS_TYPE_STOP ticket.stop_source = STATUS_TYPE_STOP store.add_ticket(ticket) else: store.del_online(ticket.nas_addr,ticket.acct_session_id) ticket.acct_start_time = online['acct_start_time'] ticket.acct_stop_time= _datetime.strftime( "%Y-%m-%d %H:%M:%S") ticket.start_source = online['start_source'] ticket.stop_source = STATUS_TYPE_STOP
store.add_ticket(ticket) radiusd.syslog.info('[username:%s] Accounting stop request, remove online'%req.get_user_name(),level=logging.INFO)
random_line_split
acct_stop_process.py
#!/usr/bin/env python #coding=utf-8 from twisted.python import log from toughradius.radiusd.settings import * import logging import datetime def process(req=None,user=None,radiusd=None,**kwargs):
if not req.get_acct_status_type() == STATUS_TYPE_STOP: return runstat=radiusd.runstat store = radiusd.store runstat.acct_stop += 1 ticket = req.get_ticket() if not ticket.nas_addr: ticket.nas_addr = req.source[0] _datetime = datetime.datetime.now() online = store.get_online(ticket.nas_addr,ticket.acct_session_id) if not online: session_time = ticket.acct_session_time stop_time = _datetime.strftime( "%Y-%m-%d %H:%M:%S") start_time = (_datetime - datetime.timedelta(seconds=int(session_time))).strftime( "%Y-%m-%d %H:%M:%S") ticket.acct_start_time = start_time ticket.acct_stop_time = stop_time ticket.start_source= STATUS_TYPE_STOP ticket.stop_source = STATUS_TYPE_STOP store.add_ticket(ticket) else: store.del_online(ticket.nas_addr,ticket.acct_session_id) ticket.acct_start_time = online['acct_start_time'] ticket.acct_stop_time= _datetime.strftime( "%Y-%m-%d %H:%M:%S") ticket.start_source = online['start_source'] ticket.stop_source = STATUS_TYPE_STOP store.add_ticket(ticket) radiusd.syslog.info('[username:%s] Accounting stop request, remove online'%req.get_user_name(),level=logging.INFO)
identifier_body
acct_stop_process.py
#!/usr/bin/env python #coding=utf-8 from twisted.python import log from toughradius.radiusd.settings import * import logging import datetime def
(req=None,user=None,radiusd=None,**kwargs): if not req.get_acct_status_type() == STATUS_TYPE_STOP: return runstat=radiusd.runstat store = radiusd.store runstat.acct_stop += 1 ticket = req.get_ticket() if not ticket.nas_addr: ticket.nas_addr = req.source[0] _datetime = datetime.datetime.now() online = store.get_online(ticket.nas_addr,ticket.acct_session_id) if not online: session_time = ticket.acct_session_time stop_time = _datetime.strftime( "%Y-%m-%d %H:%M:%S") start_time = (_datetime - datetime.timedelta(seconds=int(session_time))).strftime( "%Y-%m-%d %H:%M:%S") ticket.acct_start_time = start_time ticket.acct_stop_time = stop_time ticket.start_source= STATUS_TYPE_STOP ticket.stop_source = STATUS_TYPE_STOP store.add_ticket(ticket) else: store.del_online(ticket.nas_addr,ticket.acct_session_id) ticket.acct_start_time = online['acct_start_time'] ticket.acct_stop_time= _datetime.strftime( "%Y-%m-%d %H:%M:%S") ticket.start_source = online['start_source'] ticket.stop_source = STATUS_TYPE_STOP store.add_ticket(ticket) radiusd.syslog.info('[username:%s] Accounting stop request, remove online'%req.get_user_name(),level=logging.INFO)
process
identifier_name
webpack.config.js
const path = require('path'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const PATHS = { SRC: path.join(__dirname, 'src') }; const webpackConfig = { entry: ['./src/index.jsx'], plugins: [new ExtractTextPlugin('style.css')], devtool: 'source-map', node: { fs: 'empty' }, output: { path: __dirname, publicPath: '/', filename: 'bundle.js' }, module: { rules: [ { test: /\.(js|jsx)?$/, use: [ { loader: 'eslint-loader' } ], include: [PATHS.SRC], enforce: 'pre' }, { test: /\.jsx?$/, include: [path.resolve('src')], exclude: /node_modules/, use: [ { loader: 'babel-loader', options: { cacheDirectory: true } } ] }, { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.(woff|eot|ttf|woff2)$/, use: { loader: 'url-loader' } }, { test: /\.(jpg|gif|png|svg)$/, use: {
}, resolve: { extensions: ['.js', '.jsx'] }, devServer: { historyApiFallback: true, contentBase: './' } }; module.exports = webpackConfig;
loader: 'file-loader?name=[name].[hash].[ext]' } } ]
random_line_split
radio.class.js
const MnCheckbox = require('../checkbox/checkbox.class.js') const evaluate = require('evaluate-string') module.exports = class MnRadio extends MnCheckbox { constructor(self) { self = super(self) return self } connectedCallback() { this.innerHTML = '' this._setStyle() super._setLabel() this._setInput() this._setCustomInput() this._setForm() // this.checked = this.hasAttribute('checked') this.disabled = this.hasAttribute('disabled') this.readonly = this.hasAttribute('readonly') this.name = this.hasAttribute('name') this._setValidations() } _setStyle() { this.classList.add('mn-radio') this.classList.add('mn-option') } _setInput() { this.input = document.createElement('input') this.input.setAttribute('type', 'radio') this.label.appendChild(this.input) this.input.addEventListener('change', (event) => { this.checked ? this.setAttribute('checked', '') : this.removeAttribute('checked') this.options.forEach(option => { if (option !== event.target.closest('mn-radio')) { option.removeAttribute('checked') option.input.checked = false } option.form && option.form.classList && option.form.classList.contains('submitted') ? option.validate() : null }) }) } _setCustomInput() { const input = document.createElement('div') input.classList.add('input') this.label.appendChild(input) } _setValidations() { this.validations = { required: () => !this.value, } } get options() { const name = this.getAttribute('name') ? `[name="${this.getAttribute('name')}"]` : ':not([name])' return Array.from(this.form.querySelectorAll(`.mn-radio${name}`)) } get value() { const value = this .options .filter(option => option.checked) .map(option => option.hasAttribute('value') ? evaluate(option.getAttribute('value')) : option.getAttribute('placeholder') ) return value[0] } set value(value) { this.options.forEach(option => { option.checked = false }) const option = this.options.find(option => evaluate(option.getAttribute('value')) === value) if (option)
} }
{ option.checked = true }
conditional_block
radio.class.js
const MnCheckbox = require('../checkbox/checkbox.class.js') const evaluate = require('evaluate-string') module.exports = class MnRadio extends MnCheckbox { constructor(self) { self = super(self) return self } connectedCallback() { this.innerHTML = '' this._setStyle() super._setLabel() this._setInput() this._setCustomInput() this._setForm() // this.checked = this.hasAttribute('checked') this.disabled = this.hasAttribute('disabled') this.readonly = this.hasAttribute('readonly') this.name = this.hasAttribute('name') this._setValidations() }
() { this.classList.add('mn-radio') this.classList.add('mn-option') } _setInput() { this.input = document.createElement('input') this.input.setAttribute('type', 'radio') this.label.appendChild(this.input) this.input.addEventListener('change', (event) => { this.checked ? this.setAttribute('checked', '') : this.removeAttribute('checked') this.options.forEach(option => { if (option !== event.target.closest('mn-radio')) { option.removeAttribute('checked') option.input.checked = false } option.form && option.form.classList && option.form.classList.contains('submitted') ? option.validate() : null }) }) } _setCustomInput() { const input = document.createElement('div') input.classList.add('input') this.label.appendChild(input) } _setValidations() { this.validations = { required: () => !this.value, } } get options() { const name = this.getAttribute('name') ? `[name="${this.getAttribute('name')}"]` : ':not([name])' return Array.from(this.form.querySelectorAll(`.mn-radio${name}`)) } get value() { const value = this .options .filter(option => option.checked) .map(option => option.hasAttribute('value') ? evaluate(option.getAttribute('value')) : option.getAttribute('placeholder') ) return value[0] } set value(value) { this.options.forEach(option => { option.checked = false }) const option = this.options.find(option => evaluate(option.getAttribute('value')) === value) if (option) { option.checked = true } } }
_setStyle
identifier_name
radio.class.js
const MnCheckbox = require('../checkbox/checkbox.class.js') const evaluate = require('evaluate-string') module.exports = class MnRadio extends MnCheckbox { constructor(self) {
return self } connectedCallback() { this.innerHTML = '' this._setStyle() super._setLabel() this._setInput() this._setCustomInput() this._setForm() // this.checked = this.hasAttribute('checked') this.disabled = this.hasAttribute('disabled') this.readonly = this.hasAttribute('readonly') this.name = this.hasAttribute('name') this._setValidations() } _setStyle() { this.classList.add('mn-radio') this.classList.add('mn-option') } _setInput() { this.input = document.createElement('input') this.input.setAttribute('type', 'radio') this.label.appendChild(this.input) this.input.addEventListener('change', (event) => { this.checked ? this.setAttribute('checked', '') : this.removeAttribute('checked') this.options.forEach(option => { if (option !== event.target.closest('mn-radio')) { option.removeAttribute('checked') option.input.checked = false } option.form && option.form.classList && option.form.classList.contains('submitted') ? option.validate() : null }) }) } _setCustomInput() { const input = document.createElement('div') input.classList.add('input') this.label.appendChild(input) } _setValidations() { this.validations = { required: () => !this.value, } } get options() { const name = this.getAttribute('name') ? `[name="${this.getAttribute('name')}"]` : ':not([name])' return Array.from(this.form.querySelectorAll(`.mn-radio${name}`)) } get value() { const value = this .options .filter(option => option.checked) .map(option => option.hasAttribute('value') ? evaluate(option.getAttribute('value')) : option.getAttribute('placeholder') ) return value[0] } set value(value) { this.options.forEach(option => { option.checked = false }) const option = this.options.find(option => evaluate(option.getAttribute('value')) === value) if (option) { option.checked = true } } }
self = super(self)
random_line_split
radio.class.js
const MnCheckbox = require('../checkbox/checkbox.class.js') const evaluate = require('evaluate-string') module.exports = class MnRadio extends MnCheckbox { constructor(self) { self = super(self) return self } connectedCallback() { this.innerHTML = '' this._setStyle() super._setLabel() this._setInput() this._setCustomInput() this._setForm() // this.checked = this.hasAttribute('checked') this.disabled = this.hasAttribute('disabled') this.readonly = this.hasAttribute('readonly') this.name = this.hasAttribute('name') this._setValidations() } _setStyle() { this.classList.add('mn-radio') this.classList.add('mn-option') } _setInput() { this.input = document.createElement('input') this.input.setAttribute('type', 'radio') this.label.appendChild(this.input) this.input.addEventListener('change', (event) => { this.checked ? this.setAttribute('checked', '') : this.removeAttribute('checked') this.options.forEach(option => { if (option !== event.target.closest('mn-radio')) { option.removeAttribute('checked') option.input.checked = false } option.form && option.form.classList && option.form.classList.contains('submitted') ? option.validate() : null }) }) } _setCustomInput() { const input = document.createElement('div') input.classList.add('input') this.label.appendChild(input) } _setValidations() { this.validations = { required: () => !this.value, } } get options() { const name = this.getAttribute('name') ? `[name="${this.getAttribute('name')}"]` : ':not([name])' return Array.from(this.form.querySelectorAll(`.mn-radio${name}`)) } get value() { const value = this .options .filter(option => option.checked) .map(option => option.hasAttribute('value') ? evaluate(option.getAttribute('value')) : option.getAttribute('placeholder') ) return value[0] } set value(value)
}
{ this.options.forEach(option => { option.checked = false }) const option = this.options.find(option => evaluate(option.getAttribute('value')) === value) if (option) { option.checked = true } }
identifier_body
consumer_tracking_pipeline_visitor_test.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """Tests for consumer_tracking_pipeline_visitor.""" # pytype: skip-file from __future__ import absolute_import import logging import unittest import apache_beam as beam from apache_beam import pvalue from apache_beam.pipeline import Pipeline from apache_beam.pvalue import AsList from apache_beam.runners.direct import DirectRunner from apache_beam.runners.direct.consumer_tracking_pipeline_visitor import ConsumerTrackingPipelineVisitor from apache_beam.transforms import CoGroupByKey from apache_beam.transforms import Create from apache_beam.transforms import DoFn from apache_beam.transforms import FlatMap from apache_beam.transforms import Flatten from apache_beam.transforms import ParDo # Disable frequent lint warning due to pipe operator for chaining transforms. # pylint: disable=expression-not-assigned # pylint: disable=pointless-statement class ConsumerTrackingPipelineVisitorTest(unittest.TestCase): def
(self): self.pipeline = Pipeline(DirectRunner()) self.visitor = ConsumerTrackingPipelineVisitor() try: # Python 2 self.assertCountEqual = self.assertItemsEqual except AttributeError: # Python 3 pass def test_root_transforms(self): root_read = beam.Impulse() root_flatten = Flatten(pipeline=self.pipeline) pbegin = pvalue.PBegin(self.pipeline) pcoll_read = pbegin | 'read' >> root_read pcoll_read | FlatMap(lambda x: x) [] | 'flatten' >> root_flatten self.pipeline.visit(self.visitor) root_transforms = [t.transform for t in self.visitor.root_transforms] self.assertCountEqual(root_transforms, [root_read, root_flatten]) pbegin_consumers = [ c.transform for c in self.visitor.value_to_consumers[pbegin] ] self.assertCountEqual(pbegin_consumers, [root_read]) self.assertEqual(len(self.visitor.step_names), 3) def test_side_inputs(self): class SplitNumbersFn(DoFn): def process(self, element): if element < 0: yield pvalue.TaggedOutput('tag_negative', element) else: yield element class ProcessNumbersFn(DoFn): def process(self, element, negatives): yield element def _process_numbers(pcoll, negatives): first_output = ( pcoll | 'process numbers step 1' >> ParDo(ProcessNumbersFn(), negatives)) second_output = ( first_output | 'process numbers step 2' >> ParDo(ProcessNumbersFn(), negatives)) output_pc = ((first_output, second_output) | 'flatten results' >> beam.Flatten()) return output_pc root_read = beam.Impulse() result = ( self.pipeline | 'read' >> root_read | ParDo(SplitNumbersFn()).with_outputs('tag_negative', main='positive')) positive, negative = result _process_numbers(positive, AsList(negative)) self.pipeline.visit(self.visitor) root_transforms = [t.transform for t in self.visitor.root_transforms] self.assertEqual(root_transforms, [root_read]) self.assertEqual(len(self.visitor.step_names), 5) self.assertEqual(len(self.visitor.views), 1) self.assertTrue(isinstance(self.visitor.views[0], pvalue.AsList)) def test_co_group_by_key(self): emails = self.pipeline | 'email' >> Create([('joe', 'joe@example.com')]) phones = self.pipeline | 'phone' >> Create([('mary', '111-222-3333')]) {'emails': emails, 'phones': phones} | CoGroupByKey() self.pipeline.visit(self.visitor) root_transforms = [t.transform for t in self.visitor.root_transforms] self.assertEqual(len(root_transforms), 2) self.assertGreater( len(self.visitor.step_names), 3) # 2 creates + expanded CoGBK self.assertEqual(len(self.visitor.views), 0) def test_visitor_not_sorted(self): p = Pipeline() # pylint: disable=expression-not-assigned from apache_beam.testing.test_stream import TestStream p | TestStream().add_elements(['']) | beam.Map(lambda _: _) original_graph = p.to_runner_api(return_context=False) out_of_order_graph = p.to_runner_api(return_context=False) root_id = out_of_order_graph.root_transform_ids[0] root = out_of_order_graph.components.transforms[root_id] tmp = root.subtransforms[0] root.subtransforms[0] = root.subtransforms[1] root.subtransforms[1] = tmp p = beam.Pipeline().from_runner_api( out_of_order_graph, runner='BundleBasedDirectRunner', options=None) v_out_of_order = ConsumerTrackingPipelineVisitor() p.visit(v_out_of_order) p = beam.Pipeline().from_runner_api( original_graph, runner='BundleBasedDirectRunner', options=None) v_original = ConsumerTrackingPipelineVisitor() p.visit(v_original) # Convert to string to assert they are equal. out_of_order_labels = { str(k): [str(t) for t in v_out_of_order.value_to_consumers[k]] for k in v_out_of_order.value_to_consumers } original_labels = { str(k): [str(t) for t in v_original.value_to_consumers[k]] for k in v_original.value_to_consumers } self.assertDictEqual(out_of_order_labels, original_labels) if __name__ == '__main__': logging.getLogger().setLevel(logging.DEBUG) unittest.main()
setUp
identifier_name
consumer_tracking_pipeline_visitor_test.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """Tests for consumer_tracking_pipeline_visitor.""" # pytype: skip-file from __future__ import absolute_import import logging import unittest import apache_beam as beam from apache_beam import pvalue from apache_beam.pipeline import Pipeline from apache_beam.pvalue import AsList from apache_beam.runners.direct import DirectRunner from apache_beam.runners.direct.consumer_tracking_pipeline_visitor import ConsumerTrackingPipelineVisitor from apache_beam.transforms import CoGroupByKey from apache_beam.transforms import Create from apache_beam.transforms import DoFn from apache_beam.transforms import FlatMap from apache_beam.transforms import Flatten from apache_beam.transforms import ParDo # Disable frequent lint warning due to pipe operator for chaining transforms. # pylint: disable=expression-not-assigned # pylint: disable=pointless-statement class ConsumerTrackingPipelineVisitorTest(unittest.TestCase): def setUp(self): self.pipeline = Pipeline(DirectRunner()) self.visitor = ConsumerTrackingPipelineVisitor() try: # Python 2 self.assertCountEqual = self.assertItemsEqual except AttributeError: # Python 3 pass
def test_root_transforms(self): root_read = beam.Impulse() root_flatten = Flatten(pipeline=self.pipeline) pbegin = pvalue.PBegin(self.pipeline) pcoll_read = pbegin | 'read' >> root_read pcoll_read | FlatMap(lambda x: x) [] | 'flatten' >> root_flatten self.pipeline.visit(self.visitor) root_transforms = [t.transform for t in self.visitor.root_transforms] self.assertCountEqual(root_transforms, [root_read, root_flatten]) pbegin_consumers = [ c.transform for c in self.visitor.value_to_consumers[pbegin] ] self.assertCountEqual(pbegin_consumers, [root_read]) self.assertEqual(len(self.visitor.step_names), 3) def test_side_inputs(self): class SplitNumbersFn(DoFn): def process(self, element): if element < 0: yield pvalue.TaggedOutput('tag_negative', element) else: yield element class ProcessNumbersFn(DoFn): def process(self, element, negatives): yield element def _process_numbers(pcoll, negatives): first_output = ( pcoll | 'process numbers step 1' >> ParDo(ProcessNumbersFn(), negatives)) second_output = ( first_output | 'process numbers step 2' >> ParDo(ProcessNumbersFn(), negatives)) output_pc = ((first_output, second_output) | 'flatten results' >> beam.Flatten()) return output_pc root_read = beam.Impulse() result = ( self.pipeline | 'read' >> root_read | ParDo(SplitNumbersFn()).with_outputs('tag_negative', main='positive')) positive, negative = result _process_numbers(positive, AsList(negative)) self.pipeline.visit(self.visitor) root_transforms = [t.transform for t in self.visitor.root_transforms] self.assertEqual(root_transforms, [root_read]) self.assertEqual(len(self.visitor.step_names), 5) self.assertEqual(len(self.visitor.views), 1) self.assertTrue(isinstance(self.visitor.views[0], pvalue.AsList)) def test_co_group_by_key(self): emails = self.pipeline | 'email' >> Create([('joe', 'joe@example.com')]) phones = self.pipeline | 'phone' >> Create([('mary', '111-222-3333')]) {'emails': emails, 'phones': phones} | CoGroupByKey() self.pipeline.visit(self.visitor) root_transforms = [t.transform for t in self.visitor.root_transforms] self.assertEqual(len(root_transforms), 2) self.assertGreater( len(self.visitor.step_names), 3) # 2 creates + expanded CoGBK self.assertEqual(len(self.visitor.views), 0) def test_visitor_not_sorted(self): p = Pipeline() # pylint: disable=expression-not-assigned from apache_beam.testing.test_stream import TestStream p | TestStream().add_elements(['']) | beam.Map(lambda _: _) original_graph = p.to_runner_api(return_context=False) out_of_order_graph = p.to_runner_api(return_context=False) root_id = out_of_order_graph.root_transform_ids[0] root = out_of_order_graph.components.transforms[root_id] tmp = root.subtransforms[0] root.subtransforms[0] = root.subtransforms[1] root.subtransforms[1] = tmp p = beam.Pipeline().from_runner_api( out_of_order_graph, runner='BundleBasedDirectRunner', options=None) v_out_of_order = ConsumerTrackingPipelineVisitor() p.visit(v_out_of_order) p = beam.Pipeline().from_runner_api( original_graph, runner='BundleBasedDirectRunner', options=None) v_original = ConsumerTrackingPipelineVisitor() p.visit(v_original) # Convert to string to assert they are equal. out_of_order_labels = { str(k): [str(t) for t in v_out_of_order.value_to_consumers[k]] for k in v_out_of_order.value_to_consumers } original_labels = { str(k): [str(t) for t in v_original.value_to_consumers[k]] for k in v_original.value_to_consumers } self.assertDictEqual(out_of_order_labels, original_labels) if __name__ == '__main__': logging.getLogger().setLevel(logging.DEBUG) unittest.main()
random_line_split
consumer_tracking_pipeline_visitor_test.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """Tests for consumer_tracking_pipeline_visitor.""" # pytype: skip-file from __future__ import absolute_import import logging import unittest import apache_beam as beam from apache_beam import pvalue from apache_beam.pipeline import Pipeline from apache_beam.pvalue import AsList from apache_beam.runners.direct import DirectRunner from apache_beam.runners.direct.consumer_tracking_pipeline_visitor import ConsumerTrackingPipelineVisitor from apache_beam.transforms import CoGroupByKey from apache_beam.transforms import Create from apache_beam.transforms import DoFn from apache_beam.transforms import FlatMap from apache_beam.transforms import Flatten from apache_beam.transforms import ParDo # Disable frequent lint warning due to pipe operator for chaining transforms. # pylint: disable=expression-not-assigned # pylint: disable=pointless-statement class ConsumerTrackingPipelineVisitorTest(unittest.TestCase): def setUp(self): self.pipeline = Pipeline(DirectRunner()) self.visitor = ConsumerTrackingPipelineVisitor() try: # Python 2 self.assertCountEqual = self.assertItemsEqual except AttributeError: # Python 3 pass def test_root_transforms(self): root_read = beam.Impulse() root_flatten = Flatten(pipeline=self.pipeline) pbegin = pvalue.PBegin(self.pipeline) pcoll_read = pbegin | 'read' >> root_read pcoll_read | FlatMap(lambda x: x) [] | 'flatten' >> root_flatten self.pipeline.visit(self.visitor) root_transforms = [t.transform for t in self.visitor.root_transforms] self.assertCountEqual(root_transforms, [root_read, root_flatten]) pbegin_consumers = [ c.transform for c in self.visitor.value_to_consumers[pbegin] ] self.assertCountEqual(pbegin_consumers, [root_read]) self.assertEqual(len(self.visitor.step_names), 3) def test_side_inputs(self): class SplitNumbersFn(DoFn):
class ProcessNumbersFn(DoFn): def process(self, element, negatives): yield element def _process_numbers(pcoll, negatives): first_output = ( pcoll | 'process numbers step 1' >> ParDo(ProcessNumbersFn(), negatives)) second_output = ( first_output | 'process numbers step 2' >> ParDo(ProcessNumbersFn(), negatives)) output_pc = ((first_output, second_output) | 'flatten results' >> beam.Flatten()) return output_pc root_read = beam.Impulse() result = ( self.pipeline | 'read' >> root_read | ParDo(SplitNumbersFn()).with_outputs('tag_negative', main='positive')) positive, negative = result _process_numbers(positive, AsList(negative)) self.pipeline.visit(self.visitor) root_transforms = [t.transform for t in self.visitor.root_transforms] self.assertEqual(root_transforms, [root_read]) self.assertEqual(len(self.visitor.step_names), 5) self.assertEqual(len(self.visitor.views), 1) self.assertTrue(isinstance(self.visitor.views[0], pvalue.AsList)) def test_co_group_by_key(self): emails = self.pipeline | 'email' >> Create([('joe', 'joe@example.com')]) phones = self.pipeline | 'phone' >> Create([('mary', '111-222-3333')]) {'emails': emails, 'phones': phones} | CoGroupByKey() self.pipeline.visit(self.visitor) root_transforms = [t.transform for t in self.visitor.root_transforms] self.assertEqual(len(root_transforms), 2) self.assertGreater( len(self.visitor.step_names), 3) # 2 creates + expanded CoGBK self.assertEqual(len(self.visitor.views), 0) def test_visitor_not_sorted(self): p = Pipeline() # pylint: disable=expression-not-assigned from apache_beam.testing.test_stream import TestStream p | TestStream().add_elements(['']) | beam.Map(lambda _: _) original_graph = p.to_runner_api(return_context=False) out_of_order_graph = p.to_runner_api(return_context=False) root_id = out_of_order_graph.root_transform_ids[0] root = out_of_order_graph.components.transforms[root_id] tmp = root.subtransforms[0] root.subtransforms[0] = root.subtransforms[1] root.subtransforms[1] = tmp p = beam.Pipeline().from_runner_api( out_of_order_graph, runner='BundleBasedDirectRunner', options=None) v_out_of_order = ConsumerTrackingPipelineVisitor() p.visit(v_out_of_order) p = beam.Pipeline().from_runner_api( original_graph, runner='BundleBasedDirectRunner', options=None) v_original = ConsumerTrackingPipelineVisitor() p.visit(v_original) # Convert to string to assert they are equal. out_of_order_labels = { str(k): [str(t) for t in v_out_of_order.value_to_consumers[k]] for k in v_out_of_order.value_to_consumers } original_labels = { str(k): [str(t) for t in v_original.value_to_consumers[k]] for k in v_original.value_to_consumers } self.assertDictEqual(out_of_order_labels, original_labels) if __name__ == '__main__': logging.getLogger().setLevel(logging.DEBUG) unittest.main()
def process(self, element): if element < 0: yield pvalue.TaggedOutput('tag_negative', element) else: yield element
identifier_body
consumer_tracking_pipeline_visitor_test.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """Tests for consumer_tracking_pipeline_visitor.""" # pytype: skip-file from __future__ import absolute_import import logging import unittest import apache_beam as beam from apache_beam import pvalue from apache_beam.pipeline import Pipeline from apache_beam.pvalue import AsList from apache_beam.runners.direct import DirectRunner from apache_beam.runners.direct.consumer_tracking_pipeline_visitor import ConsumerTrackingPipelineVisitor from apache_beam.transforms import CoGroupByKey from apache_beam.transforms import Create from apache_beam.transforms import DoFn from apache_beam.transforms import FlatMap from apache_beam.transforms import Flatten from apache_beam.transforms import ParDo # Disable frequent lint warning due to pipe operator for chaining transforms. # pylint: disable=expression-not-assigned # pylint: disable=pointless-statement class ConsumerTrackingPipelineVisitorTest(unittest.TestCase): def setUp(self): self.pipeline = Pipeline(DirectRunner()) self.visitor = ConsumerTrackingPipelineVisitor() try: # Python 2 self.assertCountEqual = self.assertItemsEqual except AttributeError: # Python 3 pass def test_root_transforms(self): root_read = beam.Impulse() root_flatten = Flatten(pipeline=self.pipeline) pbegin = pvalue.PBegin(self.pipeline) pcoll_read = pbegin | 'read' >> root_read pcoll_read | FlatMap(lambda x: x) [] | 'flatten' >> root_flatten self.pipeline.visit(self.visitor) root_transforms = [t.transform for t in self.visitor.root_transforms] self.assertCountEqual(root_transforms, [root_read, root_flatten]) pbegin_consumers = [ c.transform for c in self.visitor.value_to_consumers[pbegin] ] self.assertCountEqual(pbegin_consumers, [root_read]) self.assertEqual(len(self.visitor.step_names), 3) def test_side_inputs(self): class SplitNumbersFn(DoFn): def process(self, element): if element < 0:
else: yield element class ProcessNumbersFn(DoFn): def process(self, element, negatives): yield element def _process_numbers(pcoll, negatives): first_output = ( pcoll | 'process numbers step 1' >> ParDo(ProcessNumbersFn(), negatives)) second_output = ( first_output | 'process numbers step 2' >> ParDo(ProcessNumbersFn(), negatives)) output_pc = ((first_output, second_output) | 'flatten results' >> beam.Flatten()) return output_pc root_read = beam.Impulse() result = ( self.pipeline | 'read' >> root_read | ParDo(SplitNumbersFn()).with_outputs('tag_negative', main='positive')) positive, negative = result _process_numbers(positive, AsList(negative)) self.pipeline.visit(self.visitor) root_transforms = [t.transform for t in self.visitor.root_transforms] self.assertEqual(root_transforms, [root_read]) self.assertEqual(len(self.visitor.step_names), 5) self.assertEqual(len(self.visitor.views), 1) self.assertTrue(isinstance(self.visitor.views[0], pvalue.AsList)) def test_co_group_by_key(self): emails = self.pipeline | 'email' >> Create([('joe', 'joe@example.com')]) phones = self.pipeline | 'phone' >> Create([('mary', '111-222-3333')]) {'emails': emails, 'phones': phones} | CoGroupByKey() self.pipeline.visit(self.visitor) root_transforms = [t.transform for t in self.visitor.root_transforms] self.assertEqual(len(root_transforms), 2) self.assertGreater( len(self.visitor.step_names), 3) # 2 creates + expanded CoGBK self.assertEqual(len(self.visitor.views), 0) def test_visitor_not_sorted(self): p = Pipeline() # pylint: disable=expression-not-assigned from apache_beam.testing.test_stream import TestStream p | TestStream().add_elements(['']) | beam.Map(lambda _: _) original_graph = p.to_runner_api(return_context=False) out_of_order_graph = p.to_runner_api(return_context=False) root_id = out_of_order_graph.root_transform_ids[0] root = out_of_order_graph.components.transforms[root_id] tmp = root.subtransforms[0] root.subtransforms[0] = root.subtransforms[1] root.subtransforms[1] = tmp p = beam.Pipeline().from_runner_api( out_of_order_graph, runner='BundleBasedDirectRunner', options=None) v_out_of_order = ConsumerTrackingPipelineVisitor() p.visit(v_out_of_order) p = beam.Pipeline().from_runner_api( original_graph, runner='BundleBasedDirectRunner', options=None) v_original = ConsumerTrackingPipelineVisitor() p.visit(v_original) # Convert to string to assert they are equal. out_of_order_labels = { str(k): [str(t) for t in v_out_of_order.value_to_consumers[k]] for k in v_out_of_order.value_to_consumers } original_labels = { str(k): [str(t) for t in v_original.value_to_consumers[k]] for k in v_original.value_to_consumers } self.assertDictEqual(out_of_order_labels, original_labels) if __name__ == '__main__': logging.getLogger().setLevel(logging.DEBUG) unittest.main()
yield pvalue.TaggedOutput('tag_negative', element)
conditional_block
km.js
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'liststyle', 'km', { armenian: 'លេខ​អារមេនី', bulletedTitle: 'លក្ខណៈ​សម្បត្តិ​បញ្ជី​ជា​ចំណុច', circle: 'រង្វង់​មូល', decimal: 'លេខ​ទសភាគ (1, 2, 3, ...)', decimalLeadingZero: 'ទសភាគ​ចាប់​ផ្ដើម​ពី​សូន្យ (01, 02, 03, ...)', disc: 'ថាស', georgian: 'លេខ​ចចជា (an, ban, gan, ...)', lowerAlpha: 'ព្យញ្ជនៈ​តូច (a, b, c, d, e, ...)', lowerGreek: 'លេខ​ក្រិក​តូច (alpha, beta, gamma, ...)', lowerRoman: 'លេខ​រ៉ូម៉ាំង​តូច (i, ii, iii, iv, v, ...)', none: 'គ្មាន', notset: '<not set>', numberedTitle: 'លក្ខណៈ​សម្បត្តិ​បញ្ជី​ជា​លេខ', square: 'ការេ',
validateStartNumber: 'លេខ​ចាប់​ផ្ដើម​បញ្ជី ត្រូវ​តែ​ជា​តួ​លេខ​ពិត​ប្រាកដ។' } );
start: 'ចាប់​ផ្ដើម', type: 'ប្រភេទ', upperAlpha: 'អក្សរ​ធំ (A, B, C, D, E, ...)', upperRoman: 'លេខ​រ៉ូម៉ាំង​ធំ (I, II, III, IV, V, ...)',
random_line_split
open_unit_async.py
""" This example opens the connection in async mode (does not work properly in Python 2.7). """ import os import time from msl.equipment import ( EquipmentRecord, ConnectionRecord, Backend, ) record = EquipmentRecord( manufacturer='Pico Technology', model='5244B', # update for your PicoScope serial='DY135/055', # update for your PicoScope connection=ConnectionRecord( backend=Backend.MSL, address='SDK::ps5000a.dll', # update for your PicoScope properties={'open_async': True}, # opening in async mode is done in the properties ) ) # optional: ensure that the PicoTech DLLs are available on PATH os.environ['PATH'] += os.pathsep + r'C:\Program Files\Pico Technology\SDK\lib' t0 = time.time() scope = record.connect() while True: now = time.time() progress = scope.open_unit_progress() print('Progress: {}%'.format(progress)) if progress == 100:
time.sleep(0.02) print('Took {:.2f} seconds to establish a connection to the PicoScope'.format(time.time()-t0)) # flash the LED light for 5 seconds scope.flash_led(-1) time.sleep(5)
break
conditional_block
open_unit_async.py
""" This example opens the connection in async mode (does not work properly in Python 2.7). """ import os import time from msl.equipment import ( EquipmentRecord, ConnectionRecord, Backend,
serial='DY135/055', # update for your PicoScope connection=ConnectionRecord( backend=Backend.MSL, address='SDK::ps5000a.dll', # update for your PicoScope properties={'open_async': True}, # opening in async mode is done in the properties ) ) # optional: ensure that the PicoTech DLLs are available on PATH os.environ['PATH'] += os.pathsep + r'C:\Program Files\Pico Technology\SDK\lib' t0 = time.time() scope = record.connect() while True: now = time.time() progress = scope.open_unit_progress() print('Progress: {}%'.format(progress)) if progress == 100: break time.sleep(0.02) print('Took {:.2f} seconds to establish a connection to the PicoScope'.format(time.time()-t0)) # flash the LED light for 5 seconds scope.flash_led(-1) time.sleep(5)
) record = EquipmentRecord( manufacturer='Pico Technology', model='5244B', # update for your PicoScope
random_line_split
function.rs
//! Defines the `FunctionProto` type, which is a garbage-collected version of core's `FnData`, as //! well as the `Function` type, which is an instantiated, runnable function inside the VM. use lea_core::fndata::{UpvalDesc, FnData}; use lea_core::opcode::*; use mem::*; use Value; use std::rc::Rc; use std::cell::Cell; /// A compiled function. When instantiated by the VM, becomes a `Function`. #[derive(Clone, Debug)] pub struct FunctionProto { /// The name of the source from which this function was compiled pub source_name: String, /// The number of stack slots required by this function (might be dynamically increased) pub stacksize: u8, /// Number of parameters accepted (ignoring varargs) pub params: u8, /// True if declared as a varargs function pub varargs: bool, /// The opcodes emitted for the code in the function bodyt.mark_traceable(r), pub opcodes: Opcodes, /// Constants used by this function. pub consts: Vec<Value>, /// List of Upvalue reference descriptions pub upvalues: Vec<UpvalDesc>, /// Names of Upvalues (names may not be defined) pub upval_names: Vec<String>, /// Contains the last opcode number emitted for a given line pub lines: Vec<usize>, /// References to the prototypes of all function declared within the body of this function. /// When dynamically compiling code, this allows the GC to collect prototypes that are unused. pub child_protos: Vec<TracedRef<FunctionProto>>, } impl FunctionProto { pub fn from_fndata<G: GcStrategy>(fndata: FnData, gc: &mut G) -> TracedRef<FunctionProto> { let proto = FunctionProto { source_name: fndata.source_name, stacksize: fndata.stacksize, params: fndata.params, varargs: fndata.varargs, opcodes: fndata.opcodes, upvalues: fndata.upvals, upval_names: vec![], // TODO lines: fndata.lines, consts: fndata.consts.into_iter().map(|lit| Value::from_literal(lit, gc)).collect(), child_protos: fndata.child_protos.into_iter() .map(|data| FunctionProto::from_fndata(*data, gc)).collect(), }; gc.register_obj(proto) } } impl Traceable for FunctionProto { fn trace<T: Tracer>(&self, t: &mut T) { for ch in &self.child_protos { t.mark_traceable(*ch); } } } /// An active Upvalue #[derive(Debug, Clone, Copy)] pub enum Upval { /// Upvalue is stored in a stack slot Open(usize), /// Closed upvalue, storing its value inline Closed(Value), } /// Instantiated function #[derive(Debug)] pub struct Function { /// The prototype from which this function was instantiated pub proto: TracedRef<FunctionProto>, /// Upvalue references, indexed by upvalue ID pub upvalues: Vec<Rc<Cell<Upval>>>, } impl Function { /// Create a new `Function` from its prototype. /// /// Upvalues are filled in by calling `search_upval` with the upvalue description from the /// prototype. `search_upval` will be called in the right order: Upvalue 0 will be resolved /// first. pub fn new<F, G: GcStrategy>(gc: &G, proto: TracedRef<FunctionProto>, mut search_upval: F) -> Function where F: FnMut(&UpvalDesc) -> Rc<Cell<Upval>> { // TODO Code style of fn decl (is there something official?) let protoref = unsafe { gc.get_ref(proto) }; Function { proto: proto, upvalues: protoref.upvalues.iter().map(|desc| search_upval(desc)).collect(), } } pub fn with_env<G: GcStrategy>(gc: &G, proto: TracedRef<FunctionProto>, env: Value) -> Function { let mut first = true; Function::new(gc, proto, |_| if first
else { Rc::new(Cell::new(Upval::Closed(Value::Nil))) }) } /// Sets an upvalue to the given value. pub fn set_upvalue(&mut self, id: usize, val: Upval) { self.upvalues[id].set(val); } } impl Traceable for Function { fn trace<T: Tracer>(&self, t: &mut T) { t.mark_traceable(self.proto); for uv in &self.upvalues { if let Upval::Closed(val) = uv.get() { val.trace(t); } } } }
{ first = false; Rc::new(Cell::new(Upval::Closed(env))) }
conditional_block
function.rs
//! Defines the `FunctionProto` type, which is a garbage-collected version of core's `FnData`, as //! well as the `Function` type, which is an instantiated, runnable function inside the VM. use lea_core::fndata::{UpvalDesc, FnData}; use lea_core::opcode::*; use mem::*; use Value; use std::rc::Rc; use std::cell::Cell; /// A compiled function. When instantiated by the VM, becomes a `Function`. #[derive(Clone, Debug)] pub struct FunctionProto { /// The name of the source from which this function was compiled pub source_name: String, /// The number of stack slots required by this function (might be dynamically increased) pub stacksize: u8, /// Number of parameters accepted (ignoring varargs) pub params: u8, /// True if declared as a varargs function pub varargs: bool, /// The opcodes emitted for the code in the function bodyt.mark_traceable(r), pub opcodes: Opcodes, /// Constants used by this function. pub consts: Vec<Value>, /// List of Upvalue reference descriptions pub upvalues: Vec<UpvalDesc>, /// Names of Upvalues (names may not be defined) pub upval_names: Vec<String>, /// Contains the last opcode number emitted for a given line pub lines: Vec<usize>, /// References to the prototypes of all function declared within the body of this function. /// When dynamically compiling code, this allows the GC to collect prototypes that are unused. pub child_protos: Vec<TracedRef<FunctionProto>>, } impl FunctionProto { pub fn from_fndata<G: GcStrategy>(fndata: FnData, gc: &mut G) -> TracedRef<FunctionProto> { let proto = FunctionProto { source_name: fndata.source_name, stacksize: fndata.stacksize, params: fndata.params, varargs: fndata.varargs, opcodes: fndata.opcodes, upvalues: fndata.upvals, upval_names: vec![], // TODO lines: fndata.lines, consts: fndata.consts.into_iter().map(|lit| Value::from_literal(lit, gc)).collect(), child_protos: fndata.child_protos.into_iter() .map(|data| FunctionProto::from_fndata(*data, gc)).collect(), }; gc.register_obj(proto) } } impl Traceable for FunctionProto { fn trace<T: Tracer>(&self, t: &mut T) { for ch in &self.child_protos { t.mark_traceable(*ch); } } } /// An active Upvalue #[derive(Debug, Clone, Copy)] pub enum Upval { /// Upvalue is stored in a stack slot Open(usize), /// Closed upvalue, storing its value inline Closed(Value), } /// Instantiated function #[derive(Debug)] pub struct Function { /// The prototype from which this function was instantiated pub proto: TracedRef<FunctionProto>, /// Upvalue references, indexed by upvalue ID pub upvalues: Vec<Rc<Cell<Upval>>>, } impl Function { /// Create a new `Function` from its prototype. /// /// Upvalues are filled in by calling `search_upval` with the upvalue description from the /// prototype. `search_upval` will be called in the right order: Upvalue 0 will be resolved /// first. pub fn new<F, G: GcStrategy>(gc: &G, proto: TracedRef<FunctionProto>, mut search_upval: F) -> Function where F: FnMut(&UpvalDesc) -> Rc<Cell<Upval>> { // TODO Code style of fn decl (is there something official?) let protoref = unsafe { gc.get_ref(proto) }; Function { proto: proto, upvalues: protoref.upvalues.iter().map(|desc| search_upval(desc)).collect(), } } pub fn with_env<G: GcStrategy>(gc: &G, proto: TracedRef<FunctionProto>, env: Value) -> Function { let mut first = true; Function::new(gc, proto, |_| if first { first = false; Rc::new(Cell::new(Upval::Closed(env))) } else { Rc::new(Cell::new(Upval::Closed(Value::Nil))) }) } /// Sets an upvalue to the given value. pub fn
(&mut self, id: usize, val: Upval) { self.upvalues[id].set(val); } } impl Traceable for Function { fn trace<T: Tracer>(&self, t: &mut T) { t.mark_traceable(self.proto); for uv in &self.upvalues { if let Upval::Closed(val) = uv.get() { val.trace(t); } } } }
set_upvalue
identifier_name
function.rs
//! Defines the `FunctionProto` type, which is a garbage-collected version of core's `FnData`, as //! well as the `Function` type, which is an instantiated, runnable function inside the VM. use lea_core::fndata::{UpvalDesc, FnData}; use lea_core::opcode::*; use mem::*; use Value; use std::rc::Rc; use std::cell::Cell; /// A compiled function. When instantiated by the VM, becomes a `Function`. #[derive(Clone, Debug)] pub struct FunctionProto { /// The name of the source from which this function was compiled pub source_name: String, /// The number of stack slots required by this function (might be dynamically increased) pub stacksize: u8, /// Number of parameters accepted (ignoring varargs) pub params: u8, /// True if declared as a varargs function pub varargs: bool, /// The opcodes emitted for the code in the function bodyt.mark_traceable(r), pub opcodes: Opcodes, /// Constants used by this function. pub consts: Vec<Value>, /// List of Upvalue reference descriptions pub upvalues: Vec<UpvalDesc>, /// Names of Upvalues (names may not be defined) pub upval_names: Vec<String>, /// Contains the last opcode number emitted for a given line pub lines: Vec<usize>, /// References to the prototypes of all function declared within the body of this function. /// When dynamically compiling code, this allows the GC to collect prototypes that are unused. pub child_protos: Vec<TracedRef<FunctionProto>>, } impl FunctionProto { pub fn from_fndata<G: GcStrategy>(fndata: FnData, gc: &mut G) -> TracedRef<FunctionProto> { let proto = FunctionProto { source_name: fndata.source_name, stacksize: fndata.stacksize, params: fndata.params, varargs: fndata.varargs, opcodes: fndata.opcodes, upvalues: fndata.upvals, upval_names: vec![], // TODO lines: fndata.lines, consts: fndata.consts.into_iter().map(|lit| Value::from_literal(lit, gc)).collect(), child_protos: fndata.child_protos.into_iter() .map(|data| FunctionProto::from_fndata(*data, gc)).collect(), }; gc.register_obj(proto) } } impl Traceable for FunctionProto { fn trace<T: Tracer>(&self, t: &mut T) { for ch in &self.child_protos { t.mark_traceable(*ch); } } } /// An active Upvalue #[derive(Debug, Clone, Copy)] pub enum Upval { /// Upvalue is stored in a stack slot
Open(usize), /// Closed upvalue, storing its value inline Closed(Value), } /// Instantiated function #[derive(Debug)] pub struct Function { /// The prototype from which this function was instantiated pub proto: TracedRef<FunctionProto>, /// Upvalue references, indexed by upvalue ID pub upvalues: Vec<Rc<Cell<Upval>>>, } impl Function { /// Create a new `Function` from its prototype. /// /// Upvalues are filled in by calling `search_upval` with the upvalue description from the /// prototype. `search_upval` will be called in the right order: Upvalue 0 will be resolved /// first. pub fn new<F, G: GcStrategy>(gc: &G, proto: TracedRef<FunctionProto>, mut search_upval: F) -> Function where F: FnMut(&UpvalDesc) -> Rc<Cell<Upval>> { // TODO Code style of fn decl (is there something official?) let protoref = unsafe { gc.get_ref(proto) }; Function { proto: proto, upvalues: protoref.upvalues.iter().map(|desc| search_upval(desc)).collect(), } } pub fn with_env<G: GcStrategy>(gc: &G, proto: TracedRef<FunctionProto>, env: Value) -> Function { let mut first = true; Function::new(gc, proto, |_| if first { first = false; Rc::new(Cell::new(Upval::Closed(env))) } else { Rc::new(Cell::new(Upval::Closed(Value::Nil))) }) } /// Sets an upvalue to the given value. pub fn set_upvalue(&mut self, id: usize, val: Upval) { self.upvalues[id].set(val); } } impl Traceable for Function { fn trace<T: Tracer>(&self, t: &mut T) { t.mark_traceable(self.proto); for uv in &self.upvalues { if let Upval::Closed(val) = uv.get() { val.trace(t); } } } }
random_line_split
function.rs
//! Defines the `FunctionProto` type, which is a garbage-collected version of core's `FnData`, as //! well as the `Function` type, which is an instantiated, runnable function inside the VM. use lea_core::fndata::{UpvalDesc, FnData}; use lea_core::opcode::*; use mem::*; use Value; use std::rc::Rc; use std::cell::Cell; /// A compiled function. When instantiated by the VM, becomes a `Function`. #[derive(Clone, Debug)] pub struct FunctionProto { /// The name of the source from which this function was compiled pub source_name: String, /// The number of stack slots required by this function (might be dynamically increased) pub stacksize: u8, /// Number of parameters accepted (ignoring varargs) pub params: u8, /// True if declared as a varargs function pub varargs: bool, /// The opcodes emitted for the code in the function bodyt.mark_traceable(r), pub opcodes: Opcodes, /// Constants used by this function. pub consts: Vec<Value>, /// List of Upvalue reference descriptions pub upvalues: Vec<UpvalDesc>, /// Names of Upvalues (names may not be defined) pub upval_names: Vec<String>, /// Contains the last opcode number emitted for a given line pub lines: Vec<usize>, /// References to the prototypes of all function declared within the body of this function. /// When dynamically compiling code, this allows the GC to collect prototypes that are unused. pub child_protos: Vec<TracedRef<FunctionProto>>, } impl FunctionProto { pub fn from_fndata<G: GcStrategy>(fndata: FnData, gc: &mut G) -> TracedRef<FunctionProto> { let proto = FunctionProto { source_name: fndata.source_name, stacksize: fndata.stacksize, params: fndata.params, varargs: fndata.varargs, opcodes: fndata.opcodes, upvalues: fndata.upvals, upval_names: vec![], // TODO lines: fndata.lines, consts: fndata.consts.into_iter().map(|lit| Value::from_literal(lit, gc)).collect(), child_protos: fndata.child_protos.into_iter() .map(|data| FunctionProto::from_fndata(*data, gc)).collect(), }; gc.register_obj(proto) } } impl Traceable for FunctionProto { fn trace<T: Tracer>(&self, t: &mut T)
} /// An active Upvalue #[derive(Debug, Clone, Copy)] pub enum Upval { /// Upvalue is stored in a stack slot Open(usize), /// Closed upvalue, storing its value inline Closed(Value), } /// Instantiated function #[derive(Debug)] pub struct Function { /// The prototype from which this function was instantiated pub proto: TracedRef<FunctionProto>, /// Upvalue references, indexed by upvalue ID pub upvalues: Vec<Rc<Cell<Upval>>>, } impl Function { /// Create a new `Function` from its prototype. /// /// Upvalues are filled in by calling `search_upval` with the upvalue description from the /// prototype. `search_upval` will be called in the right order: Upvalue 0 will be resolved /// first. pub fn new<F, G: GcStrategy>(gc: &G, proto: TracedRef<FunctionProto>, mut search_upval: F) -> Function where F: FnMut(&UpvalDesc) -> Rc<Cell<Upval>> { // TODO Code style of fn decl (is there something official?) let protoref = unsafe { gc.get_ref(proto) }; Function { proto: proto, upvalues: protoref.upvalues.iter().map(|desc| search_upval(desc)).collect(), } } pub fn with_env<G: GcStrategy>(gc: &G, proto: TracedRef<FunctionProto>, env: Value) -> Function { let mut first = true; Function::new(gc, proto, |_| if first { first = false; Rc::new(Cell::new(Upval::Closed(env))) } else { Rc::new(Cell::new(Upval::Closed(Value::Nil))) }) } /// Sets an upvalue to the given value. pub fn set_upvalue(&mut self, id: usize, val: Upval) { self.upvalues[id].set(val); } } impl Traceable for Function { fn trace<T: Tracer>(&self, t: &mut T) { t.mark_traceable(self.proto); for uv in &self.upvalues { if let Upval::Closed(val) = uv.get() { val.trace(t); } } } }
{ for ch in &self.child_protos { t.mark_traceable(*ch); } }
identifier_body
manager.py
# ============================================================================== # Copyright (C) 2011 Diego Duclos # Copyright (C) 2011-2018 Anton Vorobyov # # This file is part of Eos. # # Eos is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Eos is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Eos. If not, see <http://www.gnu.org/licenses/>. # ============================================================================== from logging import getLogger from eos import __version__ as eos_version from eos.eve_obj_builder import EveObjBuilder from eos.util.repr import make_repr_str from .exception import ExistingSourceError from .exception import UnknownSourceError from .source import Source logger = getLogger(__name__) class SourceManager: """Manages data sources. Handle and access different sources in an easy way. Useful for cases when you want to work with, for example, Tranquility and Singularity data at the same time. """ # Format: {literal alias: Source} _sources = {} # Default source, will be used implicitly when instantiating fit default = None @classmethod def add(cls, alias, data_handler, cache_handler, make_default=False): """Add source to source manager. Adding includes initializing all facilities hidden behind name 'source'. After source has been added, it is accessible with alias. Args: alias: Alias under which source will be accessible. data_handler: Data handler instance. cache_handler: Cache handler instance. make_default (optional): Do we need to mark passed source as default or not. Default source will be used for instantiating new fits, if no other source is specified. """ logger.info('adding source with alias "{}"'.format(alias)) if alias in cls._sources: raise ExistingSourceError(alias) # Compare fingerprints from data and cache cache_fp = cache_handler.get_fingerprint() data_version = data_handler.get_version() current_fp = cls.__format_fingerprint(data_version) # If data version is corrupt or fingerprints mismatch, update cache if data_version is None or cache_fp != current_fp: if data_version is None: logger.info('data version is None, updating cache') else: msg = ( 'fingerprint mismatch: cache "{}", data "{}", ' 'updating cache' ).format(cache_fp, current_fp) logger.info(msg) # Generate eve objects and cache them, as generation takes # significant amount of time eve_objects = EveObjBuilder.run(data_handler) cache_handler.update_cache(eve_objects, current_fp) # Finally, add record to list of sources source = Source(alias=alias, cache_handler=cache_handler) cls._sources[alias] = source if make_default is True: cls.default = source @classmethod def get(cls, alias): """Using source alias, return source. Args: alias: Alias of source to return. Returns: Source instance. """ try: return cls._sources[alias] except KeyError:
Args: alias: Alias of source to remove. """ logger.info('removing source with alias "{}"'.format(alias)) try: del cls._sources[alias] except KeyError: raise UnknownSourceError(alias) @classmethod def list(cls): return list(cls._sources.keys()) @staticmethod def __format_fingerprint(data_version): return '{}_{}'.format(data_version, eos_version) @classmethod def __repr__(cls): spec = [['sources', '_sources']] return make_repr_str(cls, spec)
raise UnknownSourceError(alias) @classmethod def remove(cls, alias): """Remove source by alias.
random_line_split
manager.py
# ============================================================================== # Copyright (C) 2011 Diego Duclos # Copyright (C) 2011-2018 Anton Vorobyov # # This file is part of Eos. # # Eos is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Eos is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Eos. If not, see <http://www.gnu.org/licenses/>. # ============================================================================== from logging import getLogger from eos import __version__ as eos_version from eos.eve_obj_builder import EveObjBuilder from eos.util.repr import make_repr_str from .exception import ExistingSourceError from .exception import UnknownSourceError from .source import Source logger = getLogger(__name__) class SourceManager: """Manages data sources. Handle and access different sources in an easy way. Useful for cases when you want to work with, for example, Tranquility and Singularity data at the same time. """ # Format: {literal alias: Source} _sources = {} # Default source, will be used implicitly when instantiating fit default = None @classmethod def add(cls, alias, data_handler, cache_handler, make_default=False): """Add source to source manager. Adding includes initializing all facilities hidden behind name 'source'. After source has been added, it is accessible with alias. Args: alias: Alias under which source will be accessible. data_handler: Data handler instance. cache_handler: Cache handler instance. make_default (optional): Do we need to mark passed source as default or not. Default source will be used for instantiating new fits, if no other source is specified. """ logger.info('adding source with alias "{}"'.format(alias)) if alias in cls._sources: raise ExistingSourceError(alias) # Compare fingerprints from data and cache cache_fp = cache_handler.get_fingerprint() data_version = data_handler.get_version() current_fp = cls.__format_fingerprint(data_version) # If data version is corrupt or fingerprints mismatch, update cache if data_version is None or cache_fp != current_fp: if data_version is None: logger.info('data version is None, updating cache') else:
# Generate eve objects and cache them, as generation takes # significant amount of time eve_objects = EveObjBuilder.run(data_handler) cache_handler.update_cache(eve_objects, current_fp) # Finally, add record to list of sources source = Source(alias=alias, cache_handler=cache_handler) cls._sources[alias] = source if make_default is True: cls.default = source @classmethod def get(cls, alias): """Using source alias, return source. Args: alias: Alias of source to return. Returns: Source instance. """ try: return cls._sources[alias] except KeyError: raise UnknownSourceError(alias) @classmethod def remove(cls, alias): """Remove source by alias. Args: alias: Alias of source to remove. """ logger.info('removing source with alias "{}"'.format(alias)) try: del cls._sources[alias] except KeyError: raise UnknownSourceError(alias) @classmethod def list(cls): return list(cls._sources.keys()) @staticmethod def __format_fingerprint(data_version): return '{}_{}'.format(data_version, eos_version) @classmethod def __repr__(cls): spec = [['sources', '_sources']] return make_repr_str(cls, spec)
msg = ( 'fingerprint mismatch: cache "{}", data "{}", ' 'updating cache' ).format(cache_fp, current_fp) logger.info(msg)
conditional_block
manager.py
# ============================================================================== # Copyright (C) 2011 Diego Duclos # Copyright (C) 2011-2018 Anton Vorobyov # # This file is part of Eos. # # Eos is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Eos is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Eos. If not, see <http://www.gnu.org/licenses/>. # ============================================================================== from logging import getLogger from eos import __version__ as eos_version from eos.eve_obj_builder import EveObjBuilder from eos.util.repr import make_repr_str from .exception import ExistingSourceError from .exception import UnknownSourceError from .source import Source logger = getLogger(__name__) class SourceManager: """Manages data sources. Handle and access different sources in an easy way. Useful for cases when you want to work with, for example, Tranquility and Singularity data at the same time. """ # Format: {literal alias: Source} _sources = {} # Default source, will be used implicitly when instantiating fit default = None @classmethod def add(cls, alias, data_handler, cache_handler, make_default=False): """Add source to source manager. Adding includes initializing all facilities hidden behind name 'source'. After source has been added, it is accessible with alias. Args: alias: Alias under which source will be accessible. data_handler: Data handler instance. cache_handler: Cache handler instance. make_default (optional): Do we need to mark passed source as default or not. Default source will be used for instantiating new fits, if no other source is specified. """ logger.info('adding source with alias "{}"'.format(alias)) if alias in cls._sources: raise ExistingSourceError(alias) # Compare fingerprints from data and cache cache_fp = cache_handler.get_fingerprint() data_version = data_handler.get_version() current_fp = cls.__format_fingerprint(data_version) # If data version is corrupt or fingerprints mismatch, update cache if data_version is None or cache_fp != current_fp: if data_version is None: logger.info('data version is None, updating cache') else: msg = ( 'fingerprint mismatch: cache "{}", data "{}", ' 'updating cache' ).format(cache_fp, current_fp) logger.info(msg) # Generate eve objects and cache them, as generation takes # significant amount of time eve_objects = EveObjBuilder.run(data_handler) cache_handler.update_cache(eve_objects, current_fp) # Finally, add record to list of sources source = Source(alias=alias, cache_handler=cache_handler) cls._sources[alias] = source if make_default is True: cls.default = source @classmethod def get(cls, alias): """Using source alias, return source. Args: alias: Alias of source to return. Returns: Source instance. """ try: return cls._sources[alias] except KeyError: raise UnknownSourceError(alias) @classmethod def remove(cls, alias): """Remove source by alias. Args: alias: Alias of source to remove. """ logger.info('removing source with alias "{}"'.format(alias)) try: del cls._sources[alias] except KeyError: raise UnknownSourceError(alias) @classmethod def list(cls):
@staticmethod def __format_fingerprint(data_version): return '{}_{}'.format(data_version, eos_version) @classmethod def __repr__(cls): spec = [['sources', '_sources']] return make_repr_str(cls, spec)
return list(cls._sources.keys())
identifier_body
manager.py
# ============================================================================== # Copyright (C) 2011 Diego Duclos # Copyright (C) 2011-2018 Anton Vorobyov # # This file is part of Eos. # # Eos is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Eos is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Eos. If not, see <http://www.gnu.org/licenses/>. # ============================================================================== from logging import getLogger from eos import __version__ as eos_version from eos.eve_obj_builder import EveObjBuilder from eos.util.repr import make_repr_str from .exception import ExistingSourceError from .exception import UnknownSourceError from .source import Source logger = getLogger(__name__) class SourceManager: """Manages data sources. Handle and access different sources in an easy way. Useful for cases when you want to work with, for example, Tranquility and Singularity data at the same time. """ # Format: {literal alias: Source} _sources = {} # Default source, will be used implicitly when instantiating fit default = None @classmethod def add(cls, alias, data_handler, cache_handler, make_default=False): """Add source to source manager. Adding includes initializing all facilities hidden behind name 'source'. After source has been added, it is accessible with alias. Args: alias: Alias under which source will be accessible. data_handler: Data handler instance. cache_handler: Cache handler instance. make_default (optional): Do we need to mark passed source as default or not. Default source will be used for instantiating new fits, if no other source is specified. """ logger.info('adding source with alias "{}"'.format(alias)) if alias in cls._sources: raise ExistingSourceError(alias) # Compare fingerprints from data and cache cache_fp = cache_handler.get_fingerprint() data_version = data_handler.get_version() current_fp = cls.__format_fingerprint(data_version) # If data version is corrupt or fingerprints mismatch, update cache if data_version is None or cache_fp != current_fp: if data_version is None: logger.info('data version is None, updating cache') else: msg = ( 'fingerprint mismatch: cache "{}", data "{}", ' 'updating cache' ).format(cache_fp, current_fp) logger.info(msg) # Generate eve objects and cache them, as generation takes # significant amount of time eve_objects = EveObjBuilder.run(data_handler) cache_handler.update_cache(eve_objects, current_fp) # Finally, add record to list of sources source = Source(alias=alias, cache_handler=cache_handler) cls._sources[alias] = source if make_default is True: cls.default = source @classmethod def get(cls, alias): """Using source alias, return source. Args: alias: Alias of source to return. Returns: Source instance. """ try: return cls._sources[alias] except KeyError: raise UnknownSourceError(alias) @classmethod def remove(cls, alias): """Remove source by alias. Args: alias: Alias of source to remove. """ logger.info('removing source with alias "{}"'.format(alias)) try: del cls._sources[alias] except KeyError: raise UnknownSourceError(alias) @classmethod def list(cls): return list(cls._sources.keys()) @staticmethod def
(data_version): return '{}_{}'.format(data_version, eos_version) @classmethod def __repr__(cls): spec = [['sources', '_sources']] return make_repr_str(cls, spec)
__format_fingerprint
identifier_name
CalendarEventStatusRoute.ts
/* globals module */ /** * @module calendarEventStatusRoute * @description BaasicCalendarEventStatusRoute Definition provides Baasic route templates which can be expanded to Baasic REST URIs. Various services can use BaasicCalendarEventStatusRoute Definition to obtain needed routes while other routes will be obtained through HAL. By convention, all route services use the same function names as their corresponding services. */ import { injectable, inject } from "inversify"; import { BaseRoute, TYPES as commonTypes } from '../../../../common'; import { IGetRequestOptions, IOptions } from '../../../../common/contracts';; import { IAppOptions, TYPES as coreTypes } from '../../../../core/contracts'; import { ICalendarEventStatus, IGetCalendarOptions } from '../../contracts'; @injectable() export class CalendarEventStatusRoute extends BaseRoute { public readonly findRoute: string = 'calendar-lookups/statuses/{?searchQuery,page,rpp,sort,embed,fields,from,to,ids}'; public readonly getRoute: string = 'calendar-lookups/statuses/{id}/{?embed,fields}'; public readonly createRoute: string = 'calendar-lookups/statuses'; public readonly updateRoute: string = 'calendar-lookups/statuses/{id}'; public readonly deleteRoute: string = 'calendar-lookups/statuses/{id}'; public readonly purgeRoute: string = 'calendar-lookups/statuses/purge'; constructor(@inject(coreTypes.IAppOptions) protected appOptions: IAppOptions) { super(appOptions); } /** * Parses find route which can be expanded with additional options. Supported items are: * - `searchQuery` - A string referencing CalendarEventStatus properties using the phrase or BQL (Baasic Query Language) search. * - `page` - A value used to set the page number, i.e. to retrieve certain CalendarEventStatus subset from the storage. * - `rpp` - A value used to limit the size of result set per page. * - `sort` - A string used to set the CalendarEventStatus property to sort the result collection by. * - `embed` - Comma separated list of resources to be contained within the current representation. * - `from` - Fluent syntax for 'From' date. Used to limit the dataset to only use events starting from this date * - `to` - Fluent syntax for 'To' date. Used to limit the dataset to only use events ending to this date. * - `ids` - CalendarEventStatus ids which uniquely identify CalendarEventStatus resources that need to be retrieved * @method * @param options Query resource GetCalendarOptions object. * @example calendarEventStatusRoute.find({searchQuery: '<search-phrase>'}); */ find(options?: IGetCalendarOptions): any { var opt; if (options) { opt = options; opt.to = this.getToDate(opt); opt.from = this.getFromDate(opt); } else
return super.baseFind(this.findRoute, opt); } /** * Parses get route which must be expanded with the id of the previously created CalendarEventStatus resource. The route can be expanded using additional options. Supported items are: * - `embed` - Comma separated list of resources to be contained within the current representation. * @method * @param id CalendarEventStatus id which uniquely identifies CalendarEventStatus resource that needs to be retrieved. * @param options Query resource GetRequestOptions object. * @example calendarEventStatusRoute.get(id); */ get(id: string, options?: IGetRequestOptions): any { return super.baseGet(this.getRoute, id, options); } /** * Parses create route. This URI template does not expose any additional options. * @method * @param data A CalendarEventStatus object that needs to be inserted into the system. * @example calendarEventStatusRoute.create(data); */ create(data: ICalendarEventStatus): any { return super.baseCreate(this.createRoute, data); } /** * Parses update route. This URI template does not expose any additional options. * @method * @param data A CalendarEventStatus object used to update specified CalendarEventStatus resource. * @example calendarEventStatusRoute.update(data); */ update(data: ICalendarEventStatus): any { return super.baseUpdate(this.updateRoute, data); } /** * Parses delte route. This URI template does not expose any additional options. * @method * @param data A CalendarEventStatus object used to delete specified CalendarEventStatus resource. * @example calendarEventStatusRoute.delete(data); */ delete(data: ICalendarEventStatus): any { return super.baseDelete(this.deleteRoute, data); } /** * Parses purge route. This URI template does not expose any additional options. * @method * @example calendarEventStatusRoute.purge(); */ purge(): any { return super.parse(this.purgeRoute); } protected getToDate(options: any) { if (!this.utility.isUndefined(options.to) && options.to !== null) { return options.to.toISOString(); } return undefined; } protected getFromDate(options: any) { if (!this.utility.isUndefined(options.from) && options.from !== null) { return options.from.toISOString(); } return undefined; } } /** * @overview ***Notes:** - Refer to the [REST API documentation](https://github.com/Baasic/baasic-rest-api/wiki) for detailed information about available Baasic REST API end-points. - [URI Template](https://github.com/Baasic/uritemplate-js) syntax enables expanding the Baasic route templates to Baasic REST URIs providing it with an object that contains URI parameters. - All end-point objects are transformed by the associated route service. */
{ opt = {}; }
conditional_block
CalendarEventStatusRoute.ts
/* globals module */ /** * @module calendarEventStatusRoute * @description BaasicCalendarEventStatusRoute Definition provides Baasic route templates which can be expanded to Baasic REST URIs. Various services can use BaasicCalendarEventStatusRoute Definition to obtain needed routes while other routes will be obtained through HAL. By convention, all route services use the same function names as their corresponding services. */ import { injectable, inject } from "inversify"; import { BaseRoute, TYPES as commonTypes } from '../../../../common'; import { IGetRequestOptions, IOptions } from '../../../../common/contracts';; import { IAppOptions, TYPES as coreTypes } from '../../../../core/contracts'; import { ICalendarEventStatus, IGetCalendarOptions } from '../../contracts'; @injectable() export class CalendarEventStatusRoute extends BaseRoute { public readonly findRoute: string = 'calendar-lookups/statuses/{?searchQuery,page,rpp,sort,embed,fields,from,to,ids}'; public readonly getRoute: string = 'calendar-lookups/statuses/{id}/{?embed,fields}'; public readonly createRoute: string = 'calendar-lookups/statuses'; public readonly updateRoute: string = 'calendar-lookups/statuses/{id}'; public readonly deleteRoute: string = 'calendar-lookups/statuses/{id}'; public readonly purgeRoute: string = 'calendar-lookups/statuses/purge'; constructor(@inject(coreTypes.IAppOptions) protected appOptions: IAppOptions) { super(appOptions); } /** * Parses find route which can be expanded with additional options. Supported items are: * - `searchQuery` - A string referencing CalendarEventStatus properties using the phrase or BQL (Baasic Query Language) search. * - `page` - A value used to set the page number, i.e. to retrieve certain CalendarEventStatus subset from the storage. * - `rpp` - A value used to limit the size of result set per page. * - `sort` - A string used to set the CalendarEventStatus property to sort the result collection by. * - `embed` - Comma separated list of resources to be contained within the current representation. * - `from` - Fluent syntax for 'From' date. Used to limit the dataset to only use events starting from this date * - `to` - Fluent syntax for 'To' date. Used to limit the dataset to only use events ending to this date. * - `ids` - CalendarEventStatus ids which uniquely identify CalendarEventStatus resources that need to be retrieved * @method * @param options Query resource GetCalendarOptions object. * @example calendarEventStatusRoute.find({searchQuery: '<search-phrase>'}); */ find(options?: IGetCalendarOptions): any { var opt; if (options) { opt = options; opt.to = this.getToDate(opt); opt.from = this.getFromDate(opt); } else { opt = {}; } return super.baseFind(this.findRoute, opt); } /** * Parses get route which must be expanded with the id of the previously created CalendarEventStatus resource. The route can be expanded using additional options. Supported items are: * - `embed` - Comma separated list of resources to be contained within the current representation. * @method * @param id CalendarEventStatus id which uniquely identifies CalendarEventStatus resource that needs to be retrieved. * @param options Query resource GetRequestOptions object. * @example calendarEventStatusRoute.get(id); */ get(id: string, options?: IGetRequestOptions): any { return super.baseGet(this.getRoute, id, options); } /** * Parses create route. This URI template does not expose any additional options. * @method * @param data A CalendarEventStatus object that needs to be inserted into the system. * @example calendarEventStatusRoute.create(data); */ create(data: ICalendarEventStatus): any { return super.baseCreate(this.createRoute, data); } /** * Parses update route. This URI template does not expose any additional options. * @method * @param data A CalendarEventStatus object used to update specified CalendarEventStatus resource. * @example calendarEventStatusRoute.update(data); */ update(data: ICalendarEventStatus): any { return super.baseUpdate(this.updateRoute, data); } /** * Parses delte route. This URI template does not expose any additional options. * @method * @param data A CalendarEventStatus object used to delete specified CalendarEventStatus resource. * @example calendarEventStatusRoute.delete(data); */ delete(data: ICalendarEventStatus): any
/** * Parses purge route. This URI template does not expose any additional options. * @method * @example calendarEventStatusRoute.purge(); */ purge(): any { return super.parse(this.purgeRoute); } protected getToDate(options: any) { if (!this.utility.isUndefined(options.to) && options.to !== null) { return options.to.toISOString(); } return undefined; } protected getFromDate(options: any) { if (!this.utility.isUndefined(options.from) && options.from !== null) { return options.from.toISOString(); } return undefined; } } /** * @overview ***Notes:** - Refer to the [REST API documentation](https://github.com/Baasic/baasic-rest-api/wiki) for detailed information about available Baasic REST API end-points. - [URI Template](https://github.com/Baasic/uritemplate-js) syntax enables expanding the Baasic route templates to Baasic REST URIs providing it with an object that contains URI parameters. - All end-point objects are transformed by the associated route service. */
{ return super.baseDelete(this.deleteRoute, data); }
identifier_body
CalendarEventStatusRoute.ts
/* globals module */ /** * @module calendarEventStatusRoute * @description BaasicCalendarEventStatusRoute Definition provides Baasic route templates which can be expanded to Baasic REST URIs. Various services can use BaasicCalendarEventStatusRoute Definition to obtain needed routes while other routes will be obtained through HAL. By convention, all route services use the same function names as their corresponding services. */ import { injectable, inject } from "inversify"; import { BaseRoute, TYPES as commonTypes } from '../../../../common'; import { IGetRequestOptions, IOptions } from '../../../../common/contracts';; import { IAppOptions, TYPES as coreTypes } from '../../../../core/contracts'; import { ICalendarEventStatus, IGetCalendarOptions } from '../../contracts'; @injectable() export class CalendarEventStatusRoute extends BaseRoute { public readonly findRoute: string = 'calendar-lookups/statuses/{?searchQuery,page,rpp,sort,embed,fields,from,to,ids}'; public readonly getRoute: string = 'calendar-lookups/statuses/{id}/{?embed,fields}'; public readonly createRoute: string = 'calendar-lookups/statuses'; public readonly updateRoute: string = 'calendar-lookups/statuses/{id}'; public readonly deleteRoute: string = 'calendar-lookups/statuses/{id}'; public readonly purgeRoute: string = 'calendar-lookups/statuses/purge'; constructor(@inject(coreTypes.IAppOptions) protected appOptions: IAppOptions) { super(appOptions); } /** * Parses find route which can be expanded with additional options. Supported items are: * - `searchQuery` - A string referencing CalendarEventStatus properties using the phrase or BQL (Baasic Query Language) search. * - `page` - A value used to set the page number, i.e. to retrieve certain CalendarEventStatus subset from the storage. * - `rpp` - A value used to limit the size of result set per page. * - `sort` - A string used to set the CalendarEventStatus property to sort the result collection by. * - `embed` - Comma separated list of resources to be contained within the current representation. * - `from` - Fluent syntax for 'From' date. Used to limit the dataset to only use events starting from this date * - `to` - Fluent syntax for 'To' date. Used to limit the dataset to only use events ending to this date. * - `ids` - CalendarEventStatus ids which uniquely identify CalendarEventStatus resources that need to be retrieved * @method * @param options Query resource GetCalendarOptions object. * @example calendarEventStatusRoute.find({searchQuery: '<search-phrase>'}); */ find(options?: IGetCalendarOptions): any { var opt; if (options) { opt = options; opt.to = this.getToDate(opt); opt.from = this.getFromDate(opt); } else { opt = {}; } return super.baseFind(this.findRoute, opt); } /** * Parses get route which must be expanded with the id of the previously created CalendarEventStatus resource. The route can be expanded using additional options. Supported items are: * - `embed` - Comma separated list of resources to be contained within the current representation. * @method * @param id CalendarEventStatus id which uniquely identifies CalendarEventStatus resource that needs to be retrieved. * @param options Query resource GetRequestOptions object. * @example calendarEventStatusRoute.get(id); */ get(id: string, options?: IGetRequestOptions): any { return super.baseGet(this.getRoute, id, options); } /** * Parses create route. This URI template does not expose any additional options. * @method * @param data A CalendarEventStatus object that needs to be inserted into the system. * @example calendarEventStatusRoute.create(data); */ create(data: ICalendarEventStatus): any { return super.baseCreate(this.createRoute, data); } /** * Parses update route. This URI template does not expose any additional options. * @method * @param data A CalendarEventStatus object used to update specified CalendarEventStatus resource. * @example calendarEventStatusRoute.update(data); */ update(data: ICalendarEventStatus): any { return super.baseUpdate(this.updateRoute, data); } /** * Parses delte route. This URI template does not expose any additional options. * @method * @param data A CalendarEventStatus object used to delete specified CalendarEventStatus resource. * @example calendarEventStatusRoute.delete(data); */ delete(data: ICalendarEventStatus): any { return super.baseDelete(this.deleteRoute, data); } /** * Parses purge route. This URI template does not expose any additional options. * @method * @example calendarEventStatusRoute.purge(); */ purge(): any { return super.parse(this.purgeRoute); } protected getToDate(options: any) { if (!this.utility.isUndefined(options.to) && options.to !== null) { return options.to.toISOString(); } return undefined; } protected
(options: any) { if (!this.utility.isUndefined(options.from) && options.from !== null) { return options.from.toISOString(); } return undefined; } } /** * @overview ***Notes:** - Refer to the [REST API documentation](https://github.com/Baasic/baasic-rest-api/wiki) for detailed information about available Baasic REST API end-points. - [URI Template](https://github.com/Baasic/uritemplate-js) syntax enables expanding the Baasic route templates to Baasic REST URIs providing it with an object that contains URI parameters. - All end-point objects are transformed by the associated route service. */
getFromDate
identifier_name
CalendarEventStatusRoute.ts
/* globals module */
/** * @module calendarEventStatusRoute * @description BaasicCalendarEventStatusRoute Definition provides Baasic route templates which can be expanded to Baasic REST URIs. Various services can use BaasicCalendarEventStatusRoute Definition to obtain needed routes while other routes will be obtained through HAL. By convention, all route services use the same function names as their corresponding services. */ import { injectable, inject } from "inversify"; import { BaseRoute, TYPES as commonTypes } from '../../../../common'; import { IGetRequestOptions, IOptions } from '../../../../common/contracts';; import { IAppOptions, TYPES as coreTypes } from '../../../../core/contracts'; import { ICalendarEventStatus, IGetCalendarOptions } from '../../contracts'; @injectable() export class CalendarEventStatusRoute extends BaseRoute { public readonly findRoute: string = 'calendar-lookups/statuses/{?searchQuery,page,rpp,sort,embed,fields,from,to,ids}'; public readonly getRoute: string = 'calendar-lookups/statuses/{id}/{?embed,fields}'; public readonly createRoute: string = 'calendar-lookups/statuses'; public readonly updateRoute: string = 'calendar-lookups/statuses/{id}'; public readonly deleteRoute: string = 'calendar-lookups/statuses/{id}'; public readonly purgeRoute: string = 'calendar-lookups/statuses/purge'; constructor(@inject(coreTypes.IAppOptions) protected appOptions: IAppOptions) { super(appOptions); } /** * Parses find route which can be expanded with additional options. Supported items are: * - `searchQuery` - A string referencing CalendarEventStatus properties using the phrase or BQL (Baasic Query Language) search. * - `page` - A value used to set the page number, i.e. to retrieve certain CalendarEventStatus subset from the storage. * - `rpp` - A value used to limit the size of result set per page. * - `sort` - A string used to set the CalendarEventStatus property to sort the result collection by. * - `embed` - Comma separated list of resources to be contained within the current representation. * - `from` - Fluent syntax for 'From' date. Used to limit the dataset to only use events starting from this date * - `to` - Fluent syntax for 'To' date. Used to limit the dataset to only use events ending to this date. * - `ids` - CalendarEventStatus ids which uniquely identify CalendarEventStatus resources that need to be retrieved * @method * @param options Query resource GetCalendarOptions object. * @example calendarEventStatusRoute.find({searchQuery: '<search-phrase>'}); */ find(options?: IGetCalendarOptions): any { var opt; if (options) { opt = options; opt.to = this.getToDate(opt); opt.from = this.getFromDate(opt); } else { opt = {}; } return super.baseFind(this.findRoute, opt); } /** * Parses get route which must be expanded with the id of the previously created CalendarEventStatus resource. The route can be expanded using additional options. Supported items are: * - `embed` - Comma separated list of resources to be contained within the current representation. * @method * @param id CalendarEventStatus id which uniquely identifies CalendarEventStatus resource that needs to be retrieved. * @param options Query resource GetRequestOptions object. * @example calendarEventStatusRoute.get(id); */ get(id: string, options?: IGetRequestOptions): any { return super.baseGet(this.getRoute, id, options); } /** * Parses create route. This URI template does not expose any additional options. * @method * @param data A CalendarEventStatus object that needs to be inserted into the system. * @example calendarEventStatusRoute.create(data); */ create(data: ICalendarEventStatus): any { return super.baseCreate(this.createRoute, data); } /** * Parses update route. This URI template does not expose any additional options. * @method * @param data A CalendarEventStatus object used to update specified CalendarEventStatus resource. * @example calendarEventStatusRoute.update(data); */ update(data: ICalendarEventStatus): any { return super.baseUpdate(this.updateRoute, data); } /** * Parses delte route. This URI template does not expose any additional options. * @method * @param data A CalendarEventStatus object used to delete specified CalendarEventStatus resource. * @example calendarEventStatusRoute.delete(data); */ delete(data: ICalendarEventStatus): any { return super.baseDelete(this.deleteRoute, data); } /** * Parses purge route. This URI template does not expose any additional options. * @method * @example calendarEventStatusRoute.purge(); */ purge(): any { return super.parse(this.purgeRoute); } protected getToDate(options: any) { if (!this.utility.isUndefined(options.to) && options.to !== null) { return options.to.toISOString(); } return undefined; } protected getFromDate(options: any) { if (!this.utility.isUndefined(options.from) && options.from !== null) { return options.from.toISOString(); } return undefined; } } /** * @overview ***Notes:** - Refer to the [REST API documentation](https://github.com/Baasic/baasic-rest-api/wiki) for detailed information about available Baasic REST API end-points. - [URI Template](https://github.com/Baasic/uritemplate-js) syntax enables expanding the Baasic route templates to Baasic REST URIs providing it with an object that contains URI parameters. - All end-point objects are transformed by the associated route service. */
random_line_split
connection-basics.component.ts
import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { TourService } from 'ngx-tour-ngx-bootstrap'; import { CurrentConnectionService } from '../current-connection'; import { Connectors, Connector, TypeFactory } from '../../../model'; import { ConnectorStore } from '../../../store/connector/connector.store'; import { UserService } from '../../../common/user.service'; @Component({ selector: 'syndesis-connections-connection-basics', templateUrl: 'connection-basics.component.html' }) export class ConnectionsConnectionBasicsComponent implements OnInit { loading: Observable<boolean>; connectors: Observable<Connectors>; filteredConnectors: Subject<Connectors> = new BehaviorSubject(<Connectors>{}); constructor( private current: CurrentConnectionService, private connectorStore: ConnectorStore, public tourService: TourService, private userService: UserService ) { this.loading = connectorStore.loading; this.connectors = connectorStore.list; } ngOnInit()
onSelected(connector: Connector) { const connection = TypeFactory.createConnection(); const plain = connector['plain']; if (plain && typeof plain === 'function') { connection.connector = plain(); } else { connection.connector = connector; } connection.icon = connector.icon; connection.connectorId = connector.id; this.current.connection = connection; } }
{ this.connectorStore.loadAll(); /** * If guided tour state is set to be shown (i.e. true), then show it for this page, otherwise don't. */ if (this.userService.getTourState() === true) { this.tourService.initialize([ { anchorId: 'connections.type', title: 'Connection', content: 'A connection represents a specific application that you want to obtain data from or send data to.', placement: 'top', } ] ); setTimeout(() => this.tourService.start()); } }
identifier_body
connection-basics.component.ts
import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { TourService } from 'ngx-tour-ngx-bootstrap'; import { CurrentConnectionService } from '../current-connection'; import { Connectors, Connector, TypeFactory } from '../../../model'; import { ConnectorStore } from '../../../store/connector/connector.store'; import { UserService } from '../../../common/user.service'; @Component({ selector: 'syndesis-connections-connection-basics', templateUrl: 'connection-basics.component.html' }) export class
implements OnInit { loading: Observable<boolean>; connectors: Observable<Connectors>; filteredConnectors: Subject<Connectors> = new BehaviorSubject(<Connectors>{}); constructor( private current: CurrentConnectionService, private connectorStore: ConnectorStore, public tourService: TourService, private userService: UserService ) { this.loading = connectorStore.loading; this.connectors = connectorStore.list; } ngOnInit() { this.connectorStore.loadAll(); /** * If guided tour state is set to be shown (i.e. true), then show it for this page, otherwise don't. */ if (this.userService.getTourState() === true) { this.tourService.initialize([ { anchorId: 'connections.type', title: 'Connection', content: 'A connection represents a specific application that you want to obtain data from or send data to.', placement: 'top', } ] ); setTimeout(() => this.tourService.start()); } } onSelected(connector: Connector) { const connection = TypeFactory.createConnection(); const plain = connector['plain']; if (plain && typeof plain === 'function') { connection.connector = plain(); } else { connection.connector = connector; } connection.icon = connector.icon; connection.connectorId = connector.id; this.current.connection = connection; } }
ConnectionsConnectionBasicsComponent
identifier_name
connection-basics.component.ts
import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { TourService } from 'ngx-tour-ngx-bootstrap'; import { CurrentConnectionService } from '../current-connection'; import { Connectors, Connector, TypeFactory } from '../../../model'; import { ConnectorStore } from '../../../store/connector/connector.store'; import { UserService } from '../../../common/user.service'; @Component({ selector: 'syndesis-connections-connection-basics', templateUrl: 'connection-basics.component.html' }) export class ConnectionsConnectionBasicsComponent implements OnInit { loading: Observable<boolean>; connectors: Observable<Connectors>; filteredConnectors: Subject<Connectors> = new BehaviorSubject(<Connectors>{}); constructor( private current: CurrentConnectionService, private connectorStore: ConnectorStore, public tourService: TourService, private userService: UserService ) { this.loading = connectorStore.loading; this.connectors = connectorStore.list; } ngOnInit() { this.connectorStore.loadAll(); /** * If guided tour state is set to be shown (i.e. true), then show it for this page, otherwise don't. */ if (this.userService.getTourState() === true) { this.tourService.initialize([ { anchorId: 'connections.type', title: 'Connection', content: 'A connection represents a specific application that you want to obtain data from or send data to.', placement: 'top', } ] ); setTimeout(() => this.tourService.start()); } } onSelected(connector: Connector) { const connection = TypeFactory.createConnection(); const plain = connector['plain']; if (plain && typeof plain === 'function') { connection.connector = plain(); } else
connection.icon = connector.icon; connection.connectorId = connector.id; this.current.connection = connection; } }
{ connection.connector = connector; }
conditional_block
connection-basics.component.ts
import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { TourService } from 'ngx-tour-ngx-bootstrap'; import { CurrentConnectionService } from '../current-connection'; import { Connectors, Connector, TypeFactory } from '../../../model'; import { ConnectorStore } from '../../../store/connector/connector.store'; import { UserService } from '../../../common/user.service';
@Component({ selector: 'syndesis-connections-connection-basics', templateUrl: 'connection-basics.component.html' }) export class ConnectionsConnectionBasicsComponent implements OnInit { loading: Observable<boolean>; connectors: Observable<Connectors>; filteredConnectors: Subject<Connectors> = new BehaviorSubject(<Connectors>{}); constructor( private current: CurrentConnectionService, private connectorStore: ConnectorStore, public tourService: TourService, private userService: UserService ) { this.loading = connectorStore.loading; this.connectors = connectorStore.list; } ngOnInit() { this.connectorStore.loadAll(); /** * If guided tour state is set to be shown (i.e. true), then show it for this page, otherwise don't. */ if (this.userService.getTourState() === true) { this.tourService.initialize([ { anchorId: 'connections.type', title: 'Connection', content: 'A connection represents a specific application that you want to obtain data from or send data to.', placement: 'top', } ] ); setTimeout(() => this.tourService.start()); } } onSelected(connector: Connector) { const connection = TypeFactory.createConnection(); const plain = connector['plain']; if (plain && typeof plain === 'function') { connection.connector = plain(); } else { connection.connector = connector; } connection.icon = connector.icon; connection.connectorId = connector.id; this.current.connection = connection; } }
random_line_split
ping_working_public.py
#! /usr/bin/python # @author: wtie import subprocess import sys import time import argparse DIFF = False FIRST = [] def get_floating_ips(): sql = """SELECT fip.floating_ip_address FROM neutron.floatingips AS fip JOIN neutron.ports AS p JOIN neutron.securitygroupportbindings AS sgb JOIN neutron.securitygrouprules AS sgr JOIN ( SELECT ins.uuid , Count(p.id) AS count FROM nova.instances AS ins JOIN neutron.ports AS p where ins.uuid=p.device_id AND ins.deleted=0 AND ins.vm_state='active' AND ins.task_state IS NULL GROUP BY ins.uuid ) AS i WHERE fip.fixed_port_id=p.id AND p.admin_state_up=1 AND sgb.port_id=p.id AND sgb.security_group_id=sgr.security_group_id AND sgr.direction='ingress' AND sgr.protocol='icmp' AND sgr.remote_ip_prefix='0.0.0.0/0' AND p.device_id=i.uuid AND i.count=1;""" floating_ips = [ip for ip in subprocess.Popen( ["mysql", "-sNe", sql], stdout=subprocess.PIPE).communicate()[0].split("\n") if ip] return floating_ips def get_public_ips(net_uuid): if not net_uuid: return None sql = """SELECT ipa.ip_address FROM neutron.ports AS p JOIN neutron.ipallocations AS ipa JOIN neutron.securitygroupportbindings AS sgb JOIN neutron.securitygrouprules AS sgr JOIN ( SELECT ins.uuid , Count(p.id) AS count FROM nova.instances AS ins JOIN neutron.ports AS p where ins.uuid=p.device_id AND ins.deleted=0 AND ins.vm_state='active' AND ins.task_state IS NULL GROUP BY ins.uuid ) AS i WHERE ipa.network_id='""" + net_uuid + """' AND ipa.port_id=p.id AND p.admin_state_up=1 AND p.device_owner LIKE "compute:%" AND sgb.port_id=p.id AND sgb.security_group_id=sgr.security_group_id AND sgr.direction='ingress' AND sgr.protocol='icmp' AND sgr.remote_ip_prefix='0.0.0.0/0' AND p.device_id=i.uuid AND i.count=1;""" public_ips = [ip for ip in subprocess.Popen( ["mysql", "-sNe", sql], stdout=subprocess.PIPE).communicate()[0].split("\n") if ip] return public_ips def ping(ip): return subprocess.call(["ping", "-c", "1", "-w", "1", ip], stdout=subprocess.PIPE, stderr=subprocess.PIPE) def ping_loop(net_uuid=None): pingable_ips = get_public_ips(net_uuid) if net_uuid else [] pingable_ips += get_floating_ips() total = len(pingable_ips) fail_list = [] global DIFF global FIRST for ip in pingable_ips: if DIFF and FIRST and ip in FIRST: result = "?" else: result = ping(ip) sys.stdout.write(str(result)) sys.stdout.flush() if result == 1: fail_list.append(ip) #simple way to remove duplicate ips, need to improve fail_list = list(set(fail_list)) if DIFF:
else: print "\n[%s] %s: %s" % (total, len(fail_list), fail_list) return fail_list def print_report(failed_map, least_interval): report = {} for ip in failed_map: if failed_map[ip] == 1: pass if failed_map[ip] in report: report[failed_map[ip]].append(ip) else: report[failed_map[ip]] = [ip] print "REPORT:\n" for count in report: outage = least_interval * (count - 1) print("~%s :\n %s\n" % (outage, report[count])) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--net_id", help="Include netwrok <net-id>") parser.add_argument("--diff", action="store_true", help="Only print diff ips compare with first round", default=False) args = parser.parse_args() public_network_uuid = args.net_id if args.net_id else None least_interval = 10 if args.diff: DIFF = True while True: try: start = time.time() print time.strftime("%x %X") failed_map = {} fail_list = ping_loop(public_network_uuid) for ip in fail_list: if ip in failed_map: failed_map[ip] += 1 else: failed_map[ip] = 1 end = time.time() if (end-start) < least_interval: time.sleep(least_interval - (end-start)) except KeyboardInterrupt: print_report(failed_map,least_interval) sys.exit(0)
if FIRST: diff_list = [ip for ip in fail_list if ip not in FIRST] print "\n@DIFF: [%s] %s/%s: %s" % (total, len(diff_list), len(fail_list), diff_list) else: FIRST = fail_list print "\nFIRST: [%s] %s/%s: %s" % (total, len(fail_list), len(fail_list), fail_list)
conditional_block
ping_working_public.py
#! /usr/bin/python # @author: wtie import subprocess import sys import time import argparse DIFF = False FIRST = [] def get_floating_ips(): sql = """SELECT fip.floating_ip_address FROM neutron.floatingips AS fip JOIN neutron.ports AS p JOIN neutron.securitygroupportbindings AS sgb JOIN neutron.securitygrouprules AS sgr JOIN ( SELECT ins.uuid , Count(p.id) AS count FROM nova.instances AS ins JOIN neutron.ports AS p where ins.uuid=p.device_id AND ins.deleted=0 AND ins.vm_state='active' AND ins.task_state IS NULL GROUP BY ins.uuid ) AS i WHERE fip.fixed_port_id=p.id AND p.admin_state_up=1 AND sgb.port_id=p.id AND sgb.security_group_id=sgr.security_group_id AND sgr.direction='ingress' AND sgr.protocol='icmp' AND sgr.remote_ip_prefix='0.0.0.0/0' AND p.device_id=i.uuid AND i.count=1;""" floating_ips = [ip for ip in subprocess.Popen( ["mysql", "-sNe", sql], stdout=subprocess.PIPE).communicate()[0].split("\n") if ip] return floating_ips def get_public_ips(net_uuid): if not net_uuid: return None sql = """SELECT ipa.ip_address FROM neutron.ports AS p JOIN neutron.ipallocations AS ipa JOIN neutron.securitygroupportbindings AS sgb JOIN neutron.securitygrouprules AS sgr JOIN ( SELECT ins.uuid , Count(p.id) AS count FROM nova.instances AS ins JOIN neutron.ports AS p where ins.uuid=p.device_id AND ins.deleted=0 AND ins.vm_state='active' AND ins.task_state IS NULL GROUP BY ins.uuid ) AS i WHERE ipa.network_id='""" + net_uuid + """' AND ipa.port_id=p.id AND p.admin_state_up=1 AND p.device_owner LIKE "compute:%" AND sgb.port_id=p.id AND sgb.security_group_id=sgr.security_group_id AND sgr.direction='ingress' AND sgr.protocol='icmp' AND sgr.remote_ip_prefix='0.0.0.0/0' AND p.device_id=i.uuid AND i.count=1;""" public_ips = [ip for ip in subprocess.Popen( ["mysql", "-sNe", sql], stdout=subprocess.PIPE).communicate()[0].split("\n") if ip] return public_ips def ping(ip): return subprocess.call(["ping", "-c", "1", "-w", "1", ip], stdout=subprocess.PIPE, stderr=subprocess.PIPE) def ping_loop(net_uuid=None):
def print_report(failed_map, least_interval): report = {} for ip in failed_map: if failed_map[ip] == 1: pass if failed_map[ip] in report: report[failed_map[ip]].append(ip) else: report[failed_map[ip]] = [ip] print "REPORT:\n" for count in report: outage = least_interval * (count - 1) print("~%s :\n %s\n" % (outage, report[count])) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--net_id", help="Include netwrok <net-id>") parser.add_argument("--diff", action="store_true", help="Only print diff ips compare with first round", default=False) args = parser.parse_args() public_network_uuid = args.net_id if args.net_id else None least_interval = 10 if args.diff: DIFF = True while True: try: start = time.time() print time.strftime("%x %X") failed_map = {} fail_list = ping_loop(public_network_uuid) for ip in fail_list: if ip in failed_map: failed_map[ip] += 1 else: failed_map[ip] = 1 end = time.time() if (end-start) < least_interval: time.sleep(least_interval - (end-start)) except KeyboardInterrupt: print_report(failed_map,least_interval) sys.exit(0)
pingable_ips = get_public_ips(net_uuid) if net_uuid else [] pingable_ips += get_floating_ips() total = len(pingable_ips) fail_list = [] global DIFF global FIRST for ip in pingable_ips: if DIFF and FIRST and ip in FIRST: result = "?" else: result = ping(ip) sys.stdout.write(str(result)) sys.stdout.flush() if result == 1: fail_list.append(ip) #simple way to remove duplicate ips, need to improve fail_list = list(set(fail_list)) if DIFF: if FIRST: diff_list = [ip for ip in fail_list if ip not in FIRST] print "\n@DIFF: [%s] %s/%s: %s" % (total, len(diff_list), len(fail_list), diff_list) else: FIRST = fail_list print "\nFIRST: [%s] %s/%s: %s" % (total, len(fail_list), len(fail_list), fail_list) else: print "\n[%s] %s: %s" % (total, len(fail_list), fail_list) return fail_list
identifier_body
ping_working_public.py
#! /usr/bin/python # @author: wtie import subprocess import sys import time import argparse DIFF = False FIRST = [] def
(): sql = """SELECT fip.floating_ip_address FROM neutron.floatingips AS fip JOIN neutron.ports AS p JOIN neutron.securitygroupportbindings AS sgb JOIN neutron.securitygrouprules AS sgr JOIN ( SELECT ins.uuid , Count(p.id) AS count FROM nova.instances AS ins JOIN neutron.ports AS p where ins.uuid=p.device_id AND ins.deleted=0 AND ins.vm_state='active' AND ins.task_state IS NULL GROUP BY ins.uuid ) AS i WHERE fip.fixed_port_id=p.id AND p.admin_state_up=1 AND sgb.port_id=p.id AND sgb.security_group_id=sgr.security_group_id AND sgr.direction='ingress' AND sgr.protocol='icmp' AND sgr.remote_ip_prefix='0.0.0.0/0' AND p.device_id=i.uuid AND i.count=1;""" floating_ips = [ip for ip in subprocess.Popen( ["mysql", "-sNe", sql], stdout=subprocess.PIPE).communicate()[0].split("\n") if ip] return floating_ips def get_public_ips(net_uuid): if not net_uuid: return None sql = """SELECT ipa.ip_address FROM neutron.ports AS p JOIN neutron.ipallocations AS ipa JOIN neutron.securitygroupportbindings AS sgb JOIN neutron.securitygrouprules AS sgr JOIN ( SELECT ins.uuid , Count(p.id) AS count FROM nova.instances AS ins JOIN neutron.ports AS p where ins.uuid=p.device_id AND ins.deleted=0 AND ins.vm_state='active' AND ins.task_state IS NULL GROUP BY ins.uuid ) AS i WHERE ipa.network_id='""" + net_uuid + """' AND ipa.port_id=p.id AND p.admin_state_up=1 AND p.device_owner LIKE "compute:%" AND sgb.port_id=p.id AND sgb.security_group_id=sgr.security_group_id AND sgr.direction='ingress' AND sgr.protocol='icmp' AND sgr.remote_ip_prefix='0.0.0.0/0' AND p.device_id=i.uuid AND i.count=1;""" public_ips = [ip for ip in subprocess.Popen( ["mysql", "-sNe", sql], stdout=subprocess.PIPE).communicate()[0].split("\n") if ip] return public_ips def ping(ip): return subprocess.call(["ping", "-c", "1", "-w", "1", ip], stdout=subprocess.PIPE, stderr=subprocess.PIPE) def ping_loop(net_uuid=None): pingable_ips = get_public_ips(net_uuid) if net_uuid else [] pingable_ips += get_floating_ips() total = len(pingable_ips) fail_list = [] global DIFF global FIRST for ip in pingable_ips: if DIFF and FIRST and ip in FIRST: result = "?" else: result = ping(ip) sys.stdout.write(str(result)) sys.stdout.flush() if result == 1: fail_list.append(ip) #simple way to remove duplicate ips, need to improve fail_list = list(set(fail_list)) if DIFF: if FIRST: diff_list = [ip for ip in fail_list if ip not in FIRST] print "\n@DIFF: [%s] %s/%s: %s" % (total, len(diff_list), len(fail_list), diff_list) else: FIRST = fail_list print "\nFIRST: [%s] %s/%s: %s" % (total, len(fail_list), len(fail_list), fail_list) else: print "\n[%s] %s: %s" % (total, len(fail_list), fail_list) return fail_list def print_report(failed_map, least_interval): report = {} for ip in failed_map: if failed_map[ip] == 1: pass if failed_map[ip] in report: report[failed_map[ip]].append(ip) else: report[failed_map[ip]] = [ip] print "REPORT:\n" for count in report: outage = least_interval * (count - 1) print("~%s :\n %s\n" % (outage, report[count])) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--net_id", help="Include netwrok <net-id>") parser.add_argument("--diff", action="store_true", help="Only print diff ips compare with first round", default=False) args = parser.parse_args() public_network_uuid = args.net_id if args.net_id else None least_interval = 10 if args.diff: DIFF = True while True: try: start = time.time() print time.strftime("%x %X") failed_map = {} fail_list = ping_loop(public_network_uuid) for ip in fail_list: if ip in failed_map: failed_map[ip] += 1 else: failed_map[ip] = 1 end = time.time() if (end-start) < least_interval: time.sleep(least_interval - (end-start)) except KeyboardInterrupt: print_report(failed_map,least_interval) sys.exit(0)
get_floating_ips
identifier_name
ping_working_public.py
#! /usr/bin/python # @author: wtie import subprocess import sys import time import argparse DIFF = False FIRST = [] def get_floating_ips(): sql = """SELECT fip.floating_ip_address FROM neutron.floatingips AS fip JOIN neutron.ports AS p JOIN neutron.securitygroupportbindings AS sgb JOIN neutron.securitygrouprules AS sgr JOIN ( SELECT ins.uuid , Count(p.id) AS count FROM nova.instances AS ins JOIN neutron.ports AS p where ins.uuid=p.device_id AND ins.deleted=0 AND ins.vm_state='active' AND ins.task_state IS NULL GROUP BY ins.uuid ) AS i WHERE fip.fixed_port_id=p.id AND p.admin_state_up=1 AND sgb.port_id=p.id AND sgb.security_group_id=sgr.security_group_id AND sgr.direction='ingress' AND sgr.protocol='icmp' AND sgr.remote_ip_prefix='0.0.0.0/0' AND p.device_id=i.uuid AND i.count=1;""" floating_ips = [ip for ip in subprocess.Popen( ["mysql", "-sNe", sql], stdout=subprocess.PIPE).communicate()[0].split("\n") if ip] return floating_ips def get_public_ips(net_uuid): if not net_uuid: return None sql = """SELECT ipa.ip_address FROM neutron.ports AS p JOIN neutron.ipallocations AS ipa JOIN neutron.securitygroupportbindings AS sgb JOIN neutron.securitygrouprules AS sgr JOIN ( SELECT ins.uuid , Count(p.id) AS count FROM nova.instances AS ins JOIN neutron.ports AS p where ins.uuid=p.device_id AND ins.deleted=0 AND ins.vm_state='active' AND ins.task_state IS NULL GROUP BY ins.uuid ) AS i WHERE ipa.network_id='""" + net_uuid + """' AND ipa.port_id=p.id AND p.admin_state_up=1 AND p.device_owner LIKE "compute:%" AND sgb.port_id=p.id AND sgb.security_group_id=sgr.security_group_id AND sgr.direction='ingress' AND sgr.protocol='icmp' AND sgr.remote_ip_prefix='0.0.0.0/0' AND p.device_id=i.uuid AND i.count=1;""" public_ips = [ip for ip in subprocess.Popen( ["mysql", "-sNe", sql], stdout=subprocess.PIPE).communicate()[0].split("\n") if ip] return public_ips def ping(ip):
def ping_loop(net_uuid=None): pingable_ips = get_public_ips(net_uuid) if net_uuid else [] pingable_ips += get_floating_ips() total = len(pingable_ips) fail_list = [] global DIFF global FIRST for ip in pingable_ips: if DIFF and FIRST and ip in FIRST: result = "?" else: result = ping(ip) sys.stdout.write(str(result)) sys.stdout.flush() if result == 1: fail_list.append(ip) #simple way to remove duplicate ips, need to improve fail_list = list(set(fail_list)) if DIFF: if FIRST: diff_list = [ip for ip in fail_list if ip not in FIRST] print "\n@DIFF: [%s] %s/%s: %s" % (total, len(diff_list), len(fail_list), diff_list) else: FIRST = fail_list print "\nFIRST: [%s] %s/%s: %s" % (total, len(fail_list), len(fail_list), fail_list) else: print "\n[%s] %s: %s" % (total, len(fail_list), fail_list) return fail_list def print_report(failed_map, least_interval): report = {} for ip in failed_map: if failed_map[ip] == 1: pass if failed_map[ip] in report: report[failed_map[ip]].append(ip) else: report[failed_map[ip]] = [ip] print "REPORT:\n" for count in report: outage = least_interval * (count - 1) print("~%s :\n %s\n" % (outage, report[count])) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--net_id", help="Include netwrok <net-id>") parser.add_argument("--diff", action="store_true", help="Only print diff ips compare with first round", default=False) args = parser.parse_args() public_network_uuid = args.net_id if args.net_id else None least_interval = 10 if args.diff: DIFF = True while True: try: start = time.time() print time.strftime("%x %X") failed_map = {} fail_list = ping_loop(public_network_uuid) for ip in fail_list: if ip in failed_map: failed_map[ip] += 1 else: failed_map[ip] = 1 end = time.time() if (end-start) < least_interval: time.sleep(least_interval - (end-start)) except KeyboardInterrupt: print_report(failed_map,least_interval) sys.exit(0)
return subprocess.call(["ping", "-c", "1", "-w", "1", ip], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
random_line_split
PaginationBar.js.uncompressed.js
define( "gridx/nls/kk/PaginationBar", ({ pagerWai: 'Пейджер', pageIndex: '${0}', pageIndexTitle: '${0}-бет', firstPageTitle: 'Бірінші бет', prevPageTitle: 'Алдыңғы бет', nextPageTitle: 'Келесі бет', lastPageTitle: 'Соңғы бет', pageSize: '${0}',
descriptionEmpty: 'Тор – бос.', // OneUI blueprint summary: 'Барлығы: ${0}', summaryWithSelection: 'Барлығы: ${0} Таңдалды: ${1}', gotoBtnTitle: 'Белгілі бір бетке өту', gotoDialogTitle: 'Бетке өту', gotoDialogMainMsg: 'Бет санын көрсетіңіз:', gotoDialogPageCount: ' (${0} бет)', gotoDialogOKBtn: 'Өту', gotoDialogCancelBtn: 'Болдырмау', // for drop down pagination bar pageLabel: 'Бет', pageSizeLabel: 'Жолдар' }) );
pageSizeTitle: 'Бетіне ${0} элемент', pageSizeAll: 'Барлығы', pageSizeAllTitle: 'Барлық элементтер', description: '${0} - ${2} элементтің ${1} элементі.',
random_line_split
setup.py
#!/usr/bin/env python from __future__ import division, print_function, absolute_import from os.path import join def configuration(parent_package='', top_path=None):
if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
import warnings from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info, BlasNotFoundError config = Configuration('odr', parent_package, top_path) libodr_files = ['d_odr.f', 'd_mprec.f', 'dlunoc.f'] blas_info = get_info('blas_opt') if blas_info: libodr_files.append('d_lpk.f') else: warnings.warn(BlasNotFoundError.__doc__) libodr_files.append('d_lpkbls.f') odrpack_src = [join('odrpack', x) for x in libodr_files] config.add_library('odrpack', sources=odrpack_src) sources = ['__odrpack.c'] libraries = ['odrpack'] + blas_info.pop('libraries', []) include_dirs = ['.'] + blas_info.pop('include_dirs', []) config.add_extension('__odrpack', sources=sources, libraries=libraries, include_dirs=include_dirs, depends=(['odrpack.h'] + odrpack_src), **blas_info ) config.add_data_dir('tests') return config
identifier_body
setup.py
def configuration(parent_package='', top_path=None): import warnings from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info, BlasNotFoundError config = Configuration('odr', parent_package, top_path) libodr_files = ['d_odr.f', 'd_mprec.f', 'dlunoc.f'] blas_info = get_info('blas_opt') if blas_info: libodr_files.append('d_lpk.f') else: warnings.warn(BlasNotFoundError.__doc__) libodr_files.append('d_lpkbls.f') odrpack_src = [join('odrpack', x) for x in libodr_files] config.add_library('odrpack', sources=odrpack_src) sources = ['__odrpack.c'] libraries = ['odrpack'] + blas_info.pop('libraries', []) include_dirs = ['.'] + blas_info.pop('include_dirs', []) config.add_extension('__odrpack', sources=sources, libraries=libraries, include_dirs=include_dirs, depends=(['odrpack.h'] + odrpack_src), **blas_info ) config.add_data_dir('tests') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
#!/usr/bin/env python from __future__ import division, print_function, absolute_import from os.path import join
random_line_split
setup.py
#!/usr/bin/env python from __future__ import division, print_function, absolute_import from os.path import join def
(parent_package='', top_path=None): import warnings from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info, BlasNotFoundError config = Configuration('odr', parent_package, top_path) libodr_files = ['d_odr.f', 'd_mprec.f', 'dlunoc.f'] blas_info = get_info('blas_opt') if blas_info: libodr_files.append('d_lpk.f') else: warnings.warn(BlasNotFoundError.__doc__) libodr_files.append('d_lpkbls.f') odrpack_src = [join('odrpack', x) for x in libodr_files] config.add_library('odrpack', sources=odrpack_src) sources = ['__odrpack.c'] libraries = ['odrpack'] + blas_info.pop('libraries', []) include_dirs = ['.'] + blas_info.pop('include_dirs', []) config.add_extension('__odrpack', sources=sources, libraries=libraries, include_dirs=include_dirs, depends=(['odrpack.h'] + odrpack_src), **blas_info ) config.add_data_dir('tests') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
configuration
identifier_name
setup.py
#!/usr/bin/env python from __future__ import division, print_function, absolute_import from os.path import join def configuration(parent_package='', top_path=None): import warnings from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info, BlasNotFoundError config = Configuration('odr', parent_package, top_path) libodr_files = ['d_odr.f', 'd_mprec.f', 'dlunoc.f'] blas_info = get_info('blas_opt') if blas_info: libodr_files.append('d_lpk.f') else: warnings.warn(BlasNotFoundError.__doc__) libodr_files.append('d_lpkbls.f') odrpack_src = [join('odrpack', x) for x in libodr_files] config.add_library('odrpack', sources=odrpack_src) sources = ['__odrpack.c'] libraries = ['odrpack'] + blas_info.pop('libraries', []) include_dirs = ['.'] + blas_info.pop('include_dirs', []) config.add_extension('__odrpack', sources=sources, libraries=libraries, include_dirs=include_dirs, depends=(['odrpack.h'] + odrpack_src), **blas_info ) config.add_data_dir('tests') return config if __name__ == '__main__':
from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
conditional_block
test_notification.py
# -*- coding: utf-8 -*- # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Integration tests for notification command.""" from __future__ import absolute_import from __future__ import print_function from __future__ import division from __future__ import unicode_literals import re import time import uuid import boto import gslib.tests.testcase as testcase from gslib.tests.util import ObjectToURI as suri from gslib.tests.util import unittest from gslib.utils.retry_util import Retry def _LoadNotificationUrl(): return boto.config.get_value('GSUtil', 'test_notification_url') NOTIFICATION_URL = _LoadNotificationUrl() class TestNotification(testcase.GsUtilIntegrationTestCase):
"""Integration tests for notification command.""" @unittest.skipUnless(NOTIFICATION_URL, 'Test requires notification URL configuration.') def test_watch_bucket(self): """Tests creating a notification channel on a bucket.""" bucket_uri = self.CreateBucket() self.RunGsUtil( ['notification', 'watchbucket', NOTIFICATION_URL, suri(bucket_uri)]) identifier = str(uuid.uuid4()) token = str(uuid.uuid4()) stderr = self.RunGsUtil([ 'notification', 'watchbucket', '-i', identifier, '-t', token, NOTIFICATION_URL, suri(bucket_uri) ], return_stderr=True) self.assertIn('token: %s' % token, stderr) self.assertIn('identifier: %s' % identifier, stderr) @unittest.skipUnless(NOTIFICATION_URL, 'Test requires notification URL configuration.') def test_stop_channel(self): """Tests stopping a notification channel on a bucket.""" bucket_uri = self.CreateBucket() stderr = self.RunGsUtil( ['notification', 'watchbucket', NOTIFICATION_URL, suri(bucket_uri)], return_stderr=True) channel_id = re.findall(r'channel identifier: (?P<id>.*)', stderr) self.assertEqual(len(channel_id), 1) resource_id = re.findall(r'resource identifier: (?P<id>.*)', stderr) self.assertEqual(len(resource_id), 1) channel_id = channel_id[0] resource_id = resource_id[0] self.RunGsUtil(['notification', 'stopchannel', channel_id, resource_id]) @unittest.skipUnless(NOTIFICATION_URL, 'Test requires notification URL configuration.') def test_list_one_channel(self): """Tests listing notification channel on a bucket.""" # TODO(b/132277269): Re-enable these once the service-side bug is fixed. return unittest.skip('Functionality has been disabled due to b/132277269') bucket_uri = self.CreateBucket() # Set up an OCN (object change notification) on the newly created bucket. self.RunGsUtil( ['notification', 'watchbucket', NOTIFICATION_URL, suri(bucket_uri)], return_stderr=False) # The OCN listing in the service is eventually consistent. In initial # tests, it almost never was ready immediately after calling WatchBucket # above, so we A) sleep for a few seconds before the first OCN listing # attempt, and B) wrap the OCN listing attempt in retry logic in case # it raises a BucketNotFoundException (note that RunGsUtil will raise this # as an AssertionError due to the exit status not being 0). @Retry(AssertionError, tries=3, timeout_secs=5) def _ListObjectChangeNotifications(): stderr = self.RunGsUtil(['notification', 'list', '-o', suri(bucket_uri)], return_stderr=True) return stderr time.sleep(5) stderr = _ListObjectChangeNotifications() channel_id = re.findall(r'Channel identifier: (?P<id>.*)', stderr) self.assertEqual(len(channel_id), 1) resource_id = re.findall(r'Resource identifier: (?P<id>.*)', stderr) self.assertEqual(len(resource_id), 1) push_url = re.findall(r'Application URL: (?P<id>.*)', stderr) self.assertEqual(len(push_url), 1) subscriber_email = re.findall(r'Created by: (?P<id>.*)', stderr) self.assertEqual(len(subscriber_email), 1) creation_time = re.findall(r'Creation time: (?P<id>.*)', stderr) self.assertEqual(len(creation_time), 1) def test_invalid_subcommand(self): stderr = self.RunGsUtil(['notification', 'foo', 'bar', 'baz'], return_stderr=True, expected_status=1) self.assertIn('Invalid subcommand', stderr)
identifier_body
test_notification.py
# -*- coding: utf-8 -*- # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Integration tests for notification command.""" from __future__ import absolute_import from __future__ import print_function from __future__ import division from __future__ import unicode_literals import re import time import uuid import boto import gslib.tests.testcase as testcase from gslib.tests.util import ObjectToURI as suri from gslib.tests.util import unittest from gslib.utils.retry_util import Retry def _LoadNotificationUrl(): return boto.config.get_value('GSUtil', 'test_notification_url') NOTIFICATION_URL = _LoadNotificationUrl() class TestNotification(testcase.GsUtilIntegrationTestCase): """Integration tests for notification command.""" @unittest.skipUnless(NOTIFICATION_URL, 'Test requires notification URL configuration.') def
(self): """Tests creating a notification channel on a bucket.""" bucket_uri = self.CreateBucket() self.RunGsUtil( ['notification', 'watchbucket', NOTIFICATION_URL, suri(bucket_uri)]) identifier = str(uuid.uuid4()) token = str(uuid.uuid4()) stderr = self.RunGsUtil([ 'notification', 'watchbucket', '-i', identifier, '-t', token, NOTIFICATION_URL, suri(bucket_uri) ], return_stderr=True) self.assertIn('token: %s' % token, stderr) self.assertIn('identifier: %s' % identifier, stderr) @unittest.skipUnless(NOTIFICATION_URL, 'Test requires notification URL configuration.') def test_stop_channel(self): """Tests stopping a notification channel on a bucket.""" bucket_uri = self.CreateBucket() stderr = self.RunGsUtil( ['notification', 'watchbucket', NOTIFICATION_URL, suri(bucket_uri)], return_stderr=True) channel_id = re.findall(r'channel identifier: (?P<id>.*)', stderr) self.assertEqual(len(channel_id), 1) resource_id = re.findall(r'resource identifier: (?P<id>.*)', stderr) self.assertEqual(len(resource_id), 1) channel_id = channel_id[0] resource_id = resource_id[0] self.RunGsUtil(['notification', 'stopchannel', channel_id, resource_id]) @unittest.skipUnless(NOTIFICATION_URL, 'Test requires notification URL configuration.') def test_list_one_channel(self): """Tests listing notification channel on a bucket.""" # TODO(b/132277269): Re-enable these once the service-side bug is fixed. return unittest.skip('Functionality has been disabled due to b/132277269') bucket_uri = self.CreateBucket() # Set up an OCN (object change notification) on the newly created bucket. self.RunGsUtil( ['notification', 'watchbucket', NOTIFICATION_URL, suri(bucket_uri)], return_stderr=False) # The OCN listing in the service is eventually consistent. In initial # tests, it almost never was ready immediately after calling WatchBucket # above, so we A) sleep for a few seconds before the first OCN listing # attempt, and B) wrap the OCN listing attempt in retry logic in case # it raises a BucketNotFoundException (note that RunGsUtil will raise this # as an AssertionError due to the exit status not being 0). @Retry(AssertionError, tries=3, timeout_secs=5) def _ListObjectChangeNotifications(): stderr = self.RunGsUtil(['notification', 'list', '-o', suri(bucket_uri)], return_stderr=True) return stderr time.sleep(5) stderr = _ListObjectChangeNotifications() channel_id = re.findall(r'Channel identifier: (?P<id>.*)', stderr) self.assertEqual(len(channel_id), 1) resource_id = re.findall(r'Resource identifier: (?P<id>.*)', stderr) self.assertEqual(len(resource_id), 1) push_url = re.findall(r'Application URL: (?P<id>.*)', stderr) self.assertEqual(len(push_url), 1) subscriber_email = re.findall(r'Created by: (?P<id>.*)', stderr) self.assertEqual(len(subscriber_email), 1) creation_time = re.findall(r'Creation time: (?P<id>.*)', stderr) self.assertEqual(len(creation_time), 1) def test_invalid_subcommand(self): stderr = self.RunGsUtil(['notification', 'foo', 'bar', 'baz'], return_stderr=True, expected_status=1) self.assertIn('Invalid subcommand', stderr)
test_watch_bucket
identifier_name
test_notification.py
# -*- coding: utf-8 -*- # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Integration tests for notification command.""" from __future__ import absolute_import from __future__ import print_function from __future__ import division from __future__ import unicode_literals import re import time import uuid import boto import gslib.tests.testcase as testcase from gslib.tests.util import ObjectToURI as suri from gslib.tests.util import unittest from gslib.utils.retry_util import Retry def _LoadNotificationUrl(): return boto.config.get_value('GSUtil', 'test_notification_url') NOTIFICATION_URL = _LoadNotificationUrl() class TestNotification(testcase.GsUtilIntegrationTestCase): """Integration tests for notification command.""" @unittest.skipUnless(NOTIFICATION_URL, 'Test requires notification URL configuration.') def test_watch_bucket(self): """Tests creating a notification channel on a bucket.""" bucket_uri = self.CreateBucket() self.RunGsUtil( ['notification', 'watchbucket', NOTIFICATION_URL,
identifier = str(uuid.uuid4()) token = str(uuid.uuid4()) stderr = self.RunGsUtil([ 'notification', 'watchbucket', '-i', identifier, '-t', token, NOTIFICATION_URL, suri(bucket_uri) ], return_stderr=True) self.assertIn('token: %s' % token, stderr) self.assertIn('identifier: %s' % identifier, stderr) @unittest.skipUnless(NOTIFICATION_URL, 'Test requires notification URL configuration.') def test_stop_channel(self): """Tests stopping a notification channel on a bucket.""" bucket_uri = self.CreateBucket() stderr = self.RunGsUtil( ['notification', 'watchbucket', NOTIFICATION_URL, suri(bucket_uri)], return_stderr=True) channel_id = re.findall(r'channel identifier: (?P<id>.*)', stderr) self.assertEqual(len(channel_id), 1) resource_id = re.findall(r'resource identifier: (?P<id>.*)', stderr) self.assertEqual(len(resource_id), 1) channel_id = channel_id[0] resource_id = resource_id[0] self.RunGsUtil(['notification', 'stopchannel', channel_id, resource_id]) @unittest.skipUnless(NOTIFICATION_URL, 'Test requires notification URL configuration.') def test_list_one_channel(self): """Tests listing notification channel on a bucket.""" # TODO(b/132277269): Re-enable these once the service-side bug is fixed. return unittest.skip('Functionality has been disabled due to b/132277269') bucket_uri = self.CreateBucket() # Set up an OCN (object change notification) on the newly created bucket. self.RunGsUtil( ['notification', 'watchbucket', NOTIFICATION_URL, suri(bucket_uri)], return_stderr=False) # The OCN listing in the service is eventually consistent. In initial # tests, it almost never was ready immediately after calling WatchBucket # above, so we A) sleep for a few seconds before the first OCN listing # attempt, and B) wrap the OCN listing attempt in retry logic in case # it raises a BucketNotFoundException (note that RunGsUtil will raise this # as an AssertionError due to the exit status not being 0). @Retry(AssertionError, tries=3, timeout_secs=5) def _ListObjectChangeNotifications(): stderr = self.RunGsUtil(['notification', 'list', '-o', suri(bucket_uri)], return_stderr=True) return stderr time.sleep(5) stderr = _ListObjectChangeNotifications() channel_id = re.findall(r'Channel identifier: (?P<id>.*)', stderr) self.assertEqual(len(channel_id), 1) resource_id = re.findall(r'Resource identifier: (?P<id>.*)', stderr) self.assertEqual(len(resource_id), 1) push_url = re.findall(r'Application URL: (?P<id>.*)', stderr) self.assertEqual(len(push_url), 1) subscriber_email = re.findall(r'Created by: (?P<id>.*)', stderr) self.assertEqual(len(subscriber_email), 1) creation_time = re.findall(r'Creation time: (?P<id>.*)', stderr) self.assertEqual(len(creation_time), 1) def test_invalid_subcommand(self): stderr = self.RunGsUtil(['notification', 'foo', 'bar', 'baz'], return_stderr=True, expected_status=1) self.assertIn('Invalid subcommand', stderr)
suri(bucket_uri)])
random_line_split
dependent_pairs.rs
use iterators::adaptors::Concat; use iterators::general::CachedIterator; use iterators::tuples::{LogPairIndices, ZOrderTupleIndices}; use malachite_base::num::conversion::traits::ExactFrom; use std::collections::HashMap; use std::hash::Hash; pub fn dependent_pairs<'a, I: Iterator + 'a, J: Iterator, F: 'a>( xs: I, f: F, ) -> Box<dyn Iterator<Item = (I::Item, J::Item)> + 'a> where F: Fn(&I::Item) -> J, I::Item: Clone, { Box::new(Concat::new( xs.map(move |x| f(&x).map(move |y| (x.clone(), y))), )) } pub struct RandomDependentPairs<I: Iterator, J: Iterator, F, T> where F: Fn(&T, &I::Item) -> J, { xs: I, f: F, data: T, x_to_ys: HashMap<I::Item, J>, } impl<I: Iterator, J: Iterator, F, T> Iterator for RandomDependentPairs<I, J, F, T> where F: Fn(&T, &I::Item) -> J, I::Item: Clone + Eq + Hash, { type Item = (I::Item, J::Item); fn next(&mut self) -> Option<(I::Item, J::Item)> { let x = self.xs.next().unwrap(); let ys = self .x_to_ys .entry(x.clone()) .or_insert((self.f)(&self.data, &x)); Some((x, ys.next().unwrap())) } } pub fn random_dependent_pairs<I: Iterator, J: Iterator, F, T>( data: T, xs: I, f: F, ) -> RandomDependentPairs<I, J, F, T> where F: Fn(&T, &I::Item) -> J, I::Item: Clone + Eq + Hash, { RandomDependentPairs { xs, f, data, x_to_ys: HashMap::new(), } } macro_rules! exhaustive_dependent_pairs { ( $struct_name:ident, $fn_name:ident, $index_type:ident, $index_ctor:expr, $x_index_fn:expr ) => { pub struct $struct_name<I: Iterator, J: Iterator, F, T> where I::Item: Clone, { f: F, xs: CachedIterator<I>, x_to_ys: HashMap<I::Item, J>, i: $index_type, data: T, } impl<I: Iterator, J: Iterator, F, T> Iterator for $struct_name<I, J, F, T> where F: Fn(&T, &I::Item) -> J, I::Item: Clone + Eq + Hash, { type Item = (I::Item, J::Item); fn next(&mut self) -> Option<(I::Item, J::Item)> { let xi = $x_index_fn(&self.i);
return Some((x, ys.next().unwrap())); } let mut ys = (self.f)(&self.data, &x); let y = ys.next().unwrap(); self.x_to_ys.insert(x.clone(), ys); Some((x, y)) } } pub fn $fn_name<I: Iterator, J: Iterator, F, T>( data: T, xs: I, f: F, ) -> $struct_name<I, J, F, T> where F: Fn(&T, &I::Item) -> J, I::Item: Clone + Eq + Hash, { $struct_name { f, xs: CachedIterator::new(xs), x_to_ys: HashMap::new(), i: $index_ctor, data, } } }; } exhaustive_dependent_pairs!( ExhaustiveDependentPairsInfiniteLog, exhaustive_dependent_pairs_infinite_log, LogPairIndices, LogPairIndices::new(), |i: &LogPairIndices| i.indices().1 ); exhaustive_dependent_pairs!( ExhaustiveDependentPairsInfinite, exhaustive_dependent_pairs_infinite, ZOrderTupleIndices, ZOrderTupleIndices::new(2), |i: &ZOrderTupleIndices| usize::exact_from(i.0[1]) );
let x = self.xs.get(xi).unwrap(); self.i.increment(); if let Some(ys) = self.x_to_ys.get_mut(&x) {
random_line_split
dependent_pairs.rs
use iterators::adaptors::Concat; use iterators::general::CachedIterator; use iterators::tuples::{LogPairIndices, ZOrderTupleIndices}; use malachite_base::num::conversion::traits::ExactFrom; use std::collections::HashMap; use std::hash::Hash; pub fn dependent_pairs<'a, I: Iterator + 'a, J: Iterator, F: 'a>( xs: I, f: F, ) -> Box<dyn Iterator<Item = (I::Item, J::Item)> + 'a> where F: Fn(&I::Item) -> J, I::Item: Clone, { Box::new(Concat::new( xs.map(move |x| f(&x).map(move |y| (x.clone(), y))), )) } pub struct
<I: Iterator, J: Iterator, F, T> where F: Fn(&T, &I::Item) -> J, { xs: I, f: F, data: T, x_to_ys: HashMap<I::Item, J>, } impl<I: Iterator, J: Iterator, F, T> Iterator for RandomDependentPairs<I, J, F, T> where F: Fn(&T, &I::Item) -> J, I::Item: Clone + Eq + Hash, { type Item = (I::Item, J::Item); fn next(&mut self) -> Option<(I::Item, J::Item)> { let x = self.xs.next().unwrap(); let ys = self .x_to_ys .entry(x.clone()) .or_insert((self.f)(&self.data, &x)); Some((x, ys.next().unwrap())) } } pub fn random_dependent_pairs<I: Iterator, J: Iterator, F, T>( data: T, xs: I, f: F, ) -> RandomDependentPairs<I, J, F, T> where F: Fn(&T, &I::Item) -> J, I::Item: Clone + Eq + Hash, { RandomDependentPairs { xs, f, data, x_to_ys: HashMap::new(), } } macro_rules! exhaustive_dependent_pairs { ( $struct_name:ident, $fn_name:ident, $index_type:ident, $index_ctor:expr, $x_index_fn:expr ) => { pub struct $struct_name<I: Iterator, J: Iterator, F, T> where I::Item: Clone, { f: F, xs: CachedIterator<I>, x_to_ys: HashMap<I::Item, J>, i: $index_type, data: T, } impl<I: Iterator, J: Iterator, F, T> Iterator for $struct_name<I, J, F, T> where F: Fn(&T, &I::Item) -> J, I::Item: Clone + Eq + Hash, { type Item = (I::Item, J::Item); fn next(&mut self) -> Option<(I::Item, J::Item)> { let xi = $x_index_fn(&self.i); let x = self.xs.get(xi).unwrap(); self.i.increment(); if let Some(ys) = self.x_to_ys.get_mut(&x) { return Some((x, ys.next().unwrap())); } let mut ys = (self.f)(&self.data, &x); let y = ys.next().unwrap(); self.x_to_ys.insert(x.clone(), ys); Some((x, y)) } } pub fn $fn_name<I: Iterator, J: Iterator, F, T>( data: T, xs: I, f: F, ) -> $struct_name<I, J, F, T> where F: Fn(&T, &I::Item) -> J, I::Item: Clone + Eq + Hash, { $struct_name { f, xs: CachedIterator::new(xs), x_to_ys: HashMap::new(), i: $index_ctor, data, } } }; } exhaustive_dependent_pairs!( ExhaustiveDependentPairsInfiniteLog, exhaustive_dependent_pairs_infinite_log, LogPairIndices, LogPairIndices::new(), |i: &LogPairIndices| i.indices().1 ); exhaustive_dependent_pairs!( ExhaustiveDependentPairsInfinite, exhaustive_dependent_pairs_infinite, ZOrderTupleIndices, ZOrderTupleIndices::new(2), |i: &ZOrderTupleIndices| usize::exact_from(i.0[1]) );
RandomDependentPairs
identifier_name
main.rs
// Benchmark testing primitives #![feature(test)] extern crate test; #[macro_use] extern crate maplit; extern crate bufstream; extern crate docopt; extern crate linked_hash_map; extern crate libc; extern crate net2; extern crate rand; extern crate rustc_serialize; extern crate time; mod common; mod metrics; mod options; mod orchestrator; mod platform; mod protocol; mod storage; mod tcp_transport; mod testlib; use common::consts; use options::parse_args; use orchestrator::ListenerTask; fn print_version() { println!("{} {}", consts::APP_NAME, consts::APP_VERSION); } fn main() { print_version(); let opts = parse_args(); if opts.flag_version { // We're done here :) return; } println!("Running tcp server on {} with {}mb capacity...",
opts.get_bind_string(), opts.get_mem_limit()); let mut listener_task = ListenerTask::new(opts.clone()); listener_task.run(); }
random_line_split
main.rs
// Benchmark testing primitives #![feature(test)] extern crate test; #[macro_use] extern crate maplit; extern crate bufstream; extern crate docopt; extern crate linked_hash_map; extern crate libc; extern crate net2; extern crate rand; extern crate rustc_serialize; extern crate time; mod common; mod metrics; mod options; mod orchestrator; mod platform; mod protocol; mod storage; mod tcp_transport; mod testlib; use common::consts; use options::parse_args; use orchestrator::ListenerTask; fn print_version() { println!("{} {}", consts::APP_NAME, consts::APP_VERSION); } fn main() { print_version(); let opts = parse_args(); if opts.flag_version
println!("Running tcp server on {} with {}mb capacity...", opts.get_bind_string(), opts.get_mem_limit()); let mut listener_task = ListenerTask::new(opts.clone()); listener_task.run(); }
{ // We're done here :) return; }
conditional_block
main.rs
// Benchmark testing primitives #![feature(test)] extern crate test; #[macro_use] extern crate maplit; extern crate bufstream; extern crate docopt; extern crate linked_hash_map; extern crate libc; extern crate net2; extern crate rand; extern crate rustc_serialize; extern crate time; mod common; mod metrics; mod options; mod orchestrator; mod platform; mod protocol; mod storage; mod tcp_transport; mod testlib; use common::consts; use options::parse_args; use orchestrator::ListenerTask; fn
() { println!("{} {}", consts::APP_NAME, consts::APP_VERSION); } fn main() { print_version(); let opts = parse_args(); if opts.flag_version { // We're done here :) return; } println!("Running tcp server on {} with {}mb capacity...", opts.get_bind_string(), opts.get_mem_limit()); let mut listener_task = ListenerTask::new(opts.clone()); listener_task.run(); }
print_version
identifier_name
main.rs
// Benchmark testing primitives #![feature(test)] extern crate test; #[macro_use] extern crate maplit; extern crate bufstream; extern crate docopt; extern crate linked_hash_map; extern crate libc; extern crate net2; extern crate rand; extern crate rustc_serialize; extern crate time; mod common; mod metrics; mod options; mod orchestrator; mod platform; mod protocol; mod storage; mod tcp_transport; mod testlib; use common::consts; use options::parse_args; use orchestrator::ListenerTask; fn print_version() { println!("{} {}", consts::APP_NAME, consts::APP_VERSION); } fn main()
{ print_version(); let opts = parse_args(); if opts.flag_version { // We're done here :) return; } println!("Running tcp server on {} with {}mb capacity...", opts.get_bind_string(), opts.get_mem_limit()); let mut listener_task = ListenerTask::new(opts.clone()); listener_task.run(); }
identifier_body
jquery.mobile.js
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); //>>group: exclude define([ "require", "./widgets/loader", "./events/navigate", "./navigation/path", "./navigation/history", "./navigation/navigator", "./navigation/method", "./transitions/handlers", "./transitions/visuals", "./animationComplete", "./navigation", "./degradeInputs", "./widgets/page.dialog", "./widgets/dialog", "./widgets/collapsible", "./widgets/collapsibleSet", "./fieldContain", "./grid", "./widgets/navbar", "./widgets/listview", "./widgets/listview.autodividers", "./widgets/listview.hidedividers", "./nojs", "./widgets/forms/checkboxradio", "./widgets/forms/button", "./widgets/forms/slider", "./widgets/forms/slider.tooltip", "./widgets/forms/flipswitch", "./widgets/forms/rangeslider", "./widgets/forms/textinput", "./widgets/forms/clearButton", "./widgets/forms/autogrow", "./widgets/forms/select.custom", "./widgets/forms/select", "./buttonMarkup", "./widgets/controlgroup",
"./widgets/popup.arrow", "./widgets/panel", "./widgets/table", "./widgets/table.columntoggle", "./widgets/table.reflow", "./widgets/filterable", "./widgets/filterable.backcompat", "./widgets/tabs", "./zoom", "./zoom/iosorientationfix" ], function( require ) { require( [ "./init" ], function() {} ); }); //>>excludeEnd("jqmBuildExclude");
"./links", "./widgets/toolbar", "./widgets/fixedToolbar", "./widgets/fixedToolbar.workarounds", "./widgets/popup",
random_line_split
hsts.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use net_traits::IncludeSubdomains; use rustc_serialize::json::{decode}; use std::net::{Ipv4Addr, Ipv6Addr}; use std::str::{from_utf8}; use time; use url::Url; use util::resource_files::read_resource_file; #[derive(RustcDecodable, RustcEncodable, Clone)] pub struct HSTSEntry { pub host: String, pub include_subdomains: bool, pub max_age: Option<u64>, pub timestamp: Option<u64> } impl HSTSEntry { pub fn new(host: String, subdomains: IncludeSubdomains, max_age: Option<u64>) -> Option<HSTSEntry> { if host.parse::<Ipv4Addr>().is_ok() || host.parse::<Ipv6Addr>().is_ok() { None } else { Some(HSTSEntry { host: host, include_subdomains: (subdomains == IncludeSubdomains::Included), max_age: max_age, timestamp: Some(time::get_time().sec as u64) }) } } pub fn is_expired(&self) -> bool { match (self.max_age, self.timestamp) { (Some(max_age), Some(timestamp)) => { (time::get_time().sec as u64) - timestamp >= max_age }, _ => false } } fn matches_domain(&self, host: &str) -> bool { !self.is_expired() && self.host == host } fn matches_subdomain(&self, host: &str) -> bool { !self.is_expired() && host.ends_with(&format!(".{}", self.host)) } } #[derive(RustcDecodable, RustcEncodable, Clone)] pub struct HSTSList { pub entries: Vec<HSTSEntry> } impl HSTSList { pub fn new() -> HSTSList { HSTSList { entries: vec![] } } pub fn new_from_preload(preload_content: &str) -> Option<HSTSList> { decode(preload_content).ok() } pub fn is_host_secure(&self, host: &str) -> bool { // TODO - Should this be faster than O(n)? The HSTS list is only a few // hundred or maybe thousand entries... // // Could optimise by searching for exact matches first (via a map or // something), then checking for subdomains.
} }) } fn has_domain(&self, host: &str) -> bool { self.entries.iter().any(|e| { e.matches_domain(&host) }) } fn has_subdomain(&self, host: &str) -> bool { self.entries.iter().any(|e| { e.matches_subdomain(host) }) } pub fn push(&mut self, entry: HSTSEntry) { let have_domain = self.has_domain(&entry.host); let have_subdomain = self.has_subdomain(&entry.host); if !have_domain && !have_subdomain { self.entries.push(entry); } else if !have_subdomain { for e in &mut self.entries { if e.matches_domain(&entry.host) { e.include_subdomains = entry.include_subdomains; e.max_age = entry.max_age; } } } } } pub fn preload_hsts_domains() -> Option<HSTSList> { read_resource_file(&["hsts_preload.json"]).ok().and_then(|bytes| { from_utf8(&bytes).ok().and_then(|hsts_preload_content| { HSTSList::new_from_preload(hsts_preload_content) }) }) } pub fn secure_url(url: &Url) -> Url { if &*url.scheme == "http" { let mut secure_url = url.clone(); secure_url.scheme = "https".to_owned(); secure_url.relative_scheme_data_mut() .map(|scheme_data| { scheme_data.default_port = Some(443); }); secure_url } else { url.clone() } }
self.entries.iter().any(|e| { if e.include_subdomains { e.matches_subdomain(host) || e.matches_domain(host) } else { e.matches_domain(host)
random_line_split
hsts.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use net_traits::IncludeSubdomains; use rustc_serialize::json::{decode}; use std::net::{Ipv4Addr, Ipv6Addr}; use std::str::{from_utf8}; use time; use url::Url; use util::resource_files::read_resource_file; #[derive(RustcDecodable, RustcEncodable, Clone)] pub struct HSTSEntry { pub host: String, pub include_subdomains: bool, pub max_age: Option<u64>, pub timestamp: Option<u64> } impl HSTSEntry { pub fn new(host: String, subdomains: IncludeSubdomains, max_age: Option<u64>) -> Option<HSTSEntry> { if host.parse::<Ipv4Addr>().is_ok() || host.parse::<Ipv6Addr>().is_ok() { None } else { Some(HSTSEntry { host: host, include_subdomains: (subdomains == IncludeSubdomains::Included), max_age: max_age, timestamp: Some(time::get_time().sec as u64) }) } } pub fn is_expired(&self) -> bool { match (self.max_age, self.timestamp) { (Some(max_age), Some(timestamp)) => { (time::get_time().sec as u64) - timestamp >= max_age }, _ => false } } fn matches_domain(&self, host: &str) -> bool { !self.is_expired() && self.host == host } fn matches_subdomain(&self, host: &str) -> bool { !self.is_expired() && host.ends_with(&format!(".{}", self.host)) } } #[derive(RustcDecodable, RustcEncodable, Clone)] pub struct HSTSList { pub entries: Vec<HSTSEntry> } impl HSTSList { pub fn new() -> HSTSList { HSTSList { entries: vec![] } } pub fn new_from_preload(preload_content: &str) -> Option<HSTSList> { decode(preload_content).ok() } pub fn is_host_secure(&self, host: &str) -> bool { // TODO - Should this be faster than O(n)? The HSTS list is only a few // hundred or maybe thousand entries... // // Could optimise by searching for exact matches first (via a map or // something), then checking for subdomains. self.entries.iter().any(|e| { if e.include_subdomains { e.matches_subdomain(host) || e.matches_domain(host) } else { e.matches_domain(host) } }) } fn has_domain(&self, host: &str) -> bool { self.entries.iter().any(|e| { e.matches_domain(&host) }) } fn has_subdomain(&self, host: &str) -> bool { self.entries.iter().any(|e| { e.matches_subdomain(host) }) } pub fn push(&mut self, entry: HSTSEntry) { let have_domain = self.has_domain(&entry.host); let have_subdomain = self.has_subdomain(&entry.host); if !have_domain && !have_subdomain
else if !have_subdomain { for e in &mut self.entries { if e.matches_domain(&entry.host) { e.include_subdomains = entry.include_subdomains; e.max_age = entry.max_age; } } } } } pub fn preload_hsts_domains() -> Option<HSTSList> { read_resource_file(&["hsts_preload.json"]).ok().and_then(|bytes| { from_utf8(&bytes).ok().and_then(|hsts_preload_content| { HSTSList::new_from_preload(hsts_preload_content) }) }) } pub fn secure_url(url: &Url) -> Url { if &*url.scheme == "http" { let mut secure_url = url.clone(); secure_url.scheme = "https".to_owned(); secure_url.relative_scheme_data_mut() .map(|scheme_data| { scheme_data.default_port = Some(443); }); secure_url } else { url.clone() } }
{ self.entries.push(entry); }
conditional_block
hsts.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use net_traits::IncludeSubdomains; use rustc_serialize::json::{decode}; use std::net::{Ipv4Addr, Ipv6Addr}; use std::str::{from_utf8}; use time; use url::Url; use util::resource_files::read_resource_file; #[derive(RustcDecodable, RustcEncodable, Clone)] pub struct
{ pub host: String, pub include_subdomains: bool, pub max_age: Option<u64>, pub timestamp: Option<u64> } impl HSTSEntry { pub fn new(host: String, subdomains: IncludeSubdomains, max_age: Option<u64>) -> Option<HSTSEntry> { if host.parse::<Ipv4Addr>().is_ok() || host.parse::<Ipv6Addr>().is_ok() { None } else { Some(HSTSEntry { host: host, include_subdomains: (subdomains == IncludeSubdomains::Included), max_age: max_age, timestamp: Some(time::get_time().sec as u64) }) } } pub fn is_expired(&self) -> bool { match (self.max_age, self.timestamp) { (Some(max_age), Some(timestamp)) => { (time::get_time().sec as u64) - timestamp >= max_age }, _ => false } } fn matches_domain(&self, host: &str) -> bool { !self.is_expired() && self.host == host } fn matches_subdomain(&self, host: &str) -> bool { !self.is_expired() && host.ends_with(&format!(".{}", self.host)) } } #[derive(RustcDecodable, RustcEncodable, Clone)] pub struct HSTSList { pub entries: Vec<HSTSEntry> } impl HSTSList { pub fn new() -> HSTSList { HSTSList { entries: vec![] } } pub fn new_from_preload(preload_content: &str) -> Option<HSTSList> { decode(preload_content).ok() } pub fn is_host_secure(&self, host: &str) -> bool { // TODO - Should this be faster than O(n)? The HSTS list is only a few // hundred or maybe thousand entries... // // Could optimise by searching for exact matches first (via a map or // something), then checking for subdomains. self.entries.iter().any(|e| { if e.include_subdomains { e.matches_subdomain(host) || e.matches_domain(host) } else { e.matches_domain(host) } }) } fn has_domain(&self, host: &str) -> bool { self.entries.iter().any(|e| { e.matches_domain(&host) }) } fn has_subdomain(&self, host: &str) -> bool { self.entries.iter().any(|e| { e.matches_subdomain(host) }) } pub fn push(&mut self, entry: HSTSEntry) { let have_domain = self.has_domain(&entry.host); let have_subdomain = self.has_subdomain(&entry.host); if !have_domain && !have_subdomain { self.entries.push(entry); } else if !have_subdomain { for e in &mut self.entries { if e.matches_domain(&entry.host) { e.include_subdomains = entry.include_subdomains; e.max_age = entry.max_age; } } } } } pub fn preload_hsts_domains() -> Option<HSTSList> { read_resource_file(&["hsts_preload.json"]).ok().and_then(|bytes| { from_utf8(&bytes).ok().and_then(|hsts_preload_content| { HSTSList::new_from_preload(hsts_preload_content) }) }) } pub fn secure_url(url: &Url) -> Url { if &*url.scheme == "http" { let mut secure_url = url.clone(); secure_url.scheme = "https".to_owned(); secure_url.relative_scheme_data_mut() .map(|scheme_data| { scheme_data.default_port = Some(443); }); secure_url } else { url.clone() } }
HSTSEntry
identifier_name
readline.rs
// SairaDB - A distributed database // Copyright (C) 2015 by Siyu Wang // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. use std::ffi::{CStr, CString}; use std::str::from_utf8; use std::io::stdin; #[cfg(unix)] #[link(name = "readline")] extern "C" { #[link_name = "add_history"] fn rl_add_history(line: *const i8); #[link_name = "readline"] fn rl_readline(prompt: *const i8) -> *const i8; } #[cfg(unix)] pub fn push_history(line: &str) { let line = CString::new(line.as_bytes()).unwrap(); unsafe { rl_add_history(line.as_ptr()) }; } #[cfg(unix)] fn read_line_unix(prompt: &str) -> Option<String> { let pr = CString::new(prompt.as_bytes()).unwrap(); let sp = unsafe { rl_readline(pr.as_ptr()) }; if sp.is_null() { None } else { let cs = unsafe { CStr::from_ptr(sp) }; let line = from_utf8(cs.to_bytes()).unwrap(); push_history(&line); Some(line.to_string()) } } pub fn read_line(prompt: &str) -> Option<String> { if cfg!(unix) { read_line_unix(prompt) } else
}
{ let mut s = "".to_string(); print!("{}", prompt); match stdin().read_line(&mut s) { Ok(_) => { s.pop(); // pop '\n' Some(s) } Err(_) => None } }
conditional_block
readline.rs
// SairaDB - A distributed database // Copyright (C) 2015 by Siyu Wang // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. use std::ffi::{CStr, CString}; use std::str::from_utf8; use std::io::stdin; #[cfg(unix)] #[link(name = "readline")] extern "C" { #[link_name = "add_history"] fn rl_add_history(line: *const i8); #[link_name = "readline"] fn rl_readline(prompt: *const i8) -> *const i8; } #[cfg(unix)] pub fn push_history(line: &str) { let line = CString::new(line.as_bytes()).unwrap(); unsafe { rl_add_history(line.as_ptr()) }; } #[cfg(unix)] fn read_line_unix(prompt: &str) -> Option<String>
pub fn read_line(prompt: &str) -> Option<String> { if cfg!(unix) { read_line_unix(prompt) } else { let mut s = "".to_string(); print!("{}", prompt); match stdin().read_line(&mut s) { Ok(_) => { s.pop(); // pop '\n' Some(s) } Err(_) => None } } }
{ let pr = CString::new(prompt.as_bytes()).unwrap(); let sp = unsafe { rl_readline(pr.as_ptr()) }; if sp.is_null() { None } else { let cs = unsafe { CStr::from_ptr(sp) }; let line = from_utf8(cs.to_bytes()).unwrap(); push_history(&line); Some(line.to_string()) } }
identifier_body
readline.rs
// SairaDB - A distributed database // Copyright (C) 2015 by Siyu Wang // // This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. use std::ffi::{CStr, CString}; use std::str::from_utf8; use std::io::stdin; #[cfg(unix)] #[link(name = "readline")] extern "C" { #[link_name = "add_history"] fn rl_add_history(line: *const i8); #[link_name = "readline"] fn rl_readline(prompt: *const i8) -> *const i8; } #[cfg(unix)] pub fn push_history(line: &str) { let line = CString::new(line.as_bytes()).unwrap(); unsafe { rl_add_history(line.as_ptr()) }; } #[cfg(unix)] fn read_line_unix(prompt: &str) -> Option<String> { let pr = CString::new(prompt.as_bytes()).unwrap(); let sp = unsafe { rl_readline(pr.as_ptr()) }; if sp.is_null() { None } else { let cs = unsafe { CStr::from_ptr(sp) }; let line = from_utf8(cs.to_bytes()).unwrap(); push_history(&line); Some(line.to_string()) } } pub fn read_line(prompt: &str) -> Option<String> { if cfg!(unix) { read_line_unix(prompt) } else { let mut s = "".to_string(); print!("{}", prompt); match stdin().read_line(&mut s) { Ok(_) => { s.pop(); // pop '\n' Some(s) } Err(_) => None } } }
random_line_split
readline.rs
// SairaDB - A distributed database // Copyright (C) 2015 by Siyu Wang // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. use std::ffi::{CStr, CString}; use std::str::from_utf8; use std::io::stdin; #[cfg(unix)] #[link(name = "readline")] extern "C" { #[link_name = "add_history"] fn rl_add_history(line: *const i8); #[link_name = "readline"] fn rl_readline(prompt: *const i8) -> *const i8; } #[cfg(unix)] pub fn push_history(line: &str) { let line = CString::new(line.as_bytes()).unwrap(); unsafe { rl_add_history(line.as_ptr()) }; } #[cfg(unix)] fn
(prompt: &str) -> Option<String> { let pr = CString::new(prompt.as_bytes()).unwrap(); let sp = unsafe { rl_readline(pr.as_ptr()) }; if sp.is_null() { None } else { let cs = unsafe { CStr::from_ptr(sp) }; let line = from_utf8(cs.to_bytes()).unwrap(); push_history(&line); Some(line.to_string()) } } pub fn read_line(prompt: &str) -> Option<String> { if cfg!(unix) { read_line_unix(prompt) } else { let mut s = "".to_string(); print!("{}", prompt); match stdin().read_line(&mut s) { Ok(_) => { s.pop(); // pop '\n' Some(s) } Err(_) => None } } }
read_line_unix
identifier_name
BudgetTable.js
import React from 'react'; import { getCategoryGroups } from '../selectors/categoryGroups'; import { getCategoriesByGroupId } from '../selectors/categories'; import { getSelectedMonthBudgetItemsByCategoryId, getBudgetItemsSumUpToSelectedMonthByCategoryId } from '../selectors/budgetItems'; import { getTransactionsSumUpToSelectedMonthByCategoryId, getSelectedMonthActivityByCategoryId } from '../selectors/transactions'; import {connect} from 'react-redux'; import CategoryRow from './CategoryRow'; import CategoryGroupRow from './CategoryGroupRow'; import ui from 'redux-ui'; @ui({ state: {
static propTypes = { categoryGroups: React.PropTypes.array.isRequired, categoriesByGroupId: React.PropTypes.object.isRequired, getSelectedMonthActivityByCategoryId: React.PropTypes.object.isRequired, getSelectedMonthBudgetItemsByCategoryId: React.PropTypes.object.isRequired, transactionsSumUpToSelectedMonthByCategoryId: React.PropTypes.object.isRequired, budgetItemsSumUpToSelectedMonthByCategoryId: React.PropTypes.object.isRequired } render() { const rows = []; this.props.categoryGroups.forEach(cg => { rows.push(<CategoryGroupRow key={"cg"+cg.id} name={cg.name} />); if (this.props.categoriesByGroupId[cg.id]) { this.props.categoriesByGroupId[cg.id].forEach(c => { rows.push(<CategoryRow key={"c"+c.id} category={c} budgetItem={this.props.getSelectedMonthBudgetItemsByCategoryId[c.id]} activity={this.props.getSelectedMonthActivityByCategoryId[c.id]} available={(this.props.budgetItemsSumUpToSelectedMonthByCategoryId[c.id] || 0) + (this.props.transactionsSumUpToSelectedMonthByCategoryId[c.id] || 0)} />); }); } }); return ( <table className="table"> <thead> <tr> <th>Category</th> <th>Budgeted</th> <th>Activity</th> <th>Available</th> </tr> </thead> <tbody> {rows} </tbody> </table> ); } } const mapStateToProps = (state) => ({ categoryGroups: getCategoryGroups(state), categoriesByGroupId: getCategoriesByGroupId(state), getSelectedMonthActivityByCategoryId: getSelectedMonthActivityByCategoryId(state), getSelectedMonthBudgetItemsByCategoryId: getSelectedMonthBudgetItemsByCategoryId(state), transactionsSumUpToSelectedMonthByCategoryId: getTransactionsSumUpToSelectedMonthByCategoryId(state), budgetItemsSumUpToSelectedMonthByCategoryId: getBudgetItemsSumUpToSelectedMonthByCategoryId(state) }); export default connect(mapStateToProps)(BudgetTable);
editingCategoryId: undefined } }) class BudgetTable extends React.Component {
random_line_split
BudgetTable.js
import React from 'react'; import { getCategoryGroups } from '../selectors/categoryGroups'; import { getCategoriesByGroupId } from '../selectors/categories'; import { getSelectedMonthBudgetItemsByCategoryId, getBudgetItemsSumUpToSelectedMonthByCategoryId } from '../selectors/budgetItems'; import { getTransactionsSumUpToSelectedMonthByCategoryId, getSelectedMonthActivityByCategoryId } from '../selectors/transactions'; import {connect} from 'react-redux'; import CategoryRow from './CategoryRow'; import CategoryGroupRow from './CategoryGroupRow'; import ui from 'redux-ui'; @ui({ state: { editingCategoryId: undefined } }) class BudgetTable extends React.Component { static propTypes = { categoryGroups: React.PropTypes.array.isRequired, categoriesByGroupId: React.PropTypes.object.isRequired, getSelectedMonthActivityByCategoryId: React.PropTypes.object.isRequired, getSelectedMonthBudgetItemsByCategoryId: React.PropTypes.object.isRequired, transactionsSumUpToSelectedMonthByCategoryId: React.PropTypes.object.isRequired, budgetItemsSumUpToSelectedMonthByCategoryId: React.PropTypes.object.isRequired }
() { const rows = []; this.props.categoryGroups.forEach(cg => { rows.push(<CategoryGroupRow key={"cg"+cg.id} name={cg.name} />); if (this.props.categoriesByGroupId[cg.id]) { this.props.categoriesByGroupId[cg.id].forEach(c => { rows.push(<CategoryRow key={"c"+c.id} category={c} budgetItem={this.props.getSelectedMonthBudgetItemsByCategoryId[c.id]} activity={this.props.getSelectedMonthActivityByCategoryId[c.id]} available={(this.props.budgetItemsSumUpToSelectedMonthByCategoryId[c.id] || 0) + (this.props.transactionsSumUpToSelectedMonthByCategoryId[c.id] || 0)} />); }); } }); return ( <table className="table"> <thead> <tr> <th>Category</th> <th>Budgeted</th> <th>Activity</th> <th>Available</th> </tr> </thead> <tbody> {rows} </tbody> </table> ); } } const mapStateToProps = (state) => ({ categoryGroups: getCategoryGroups(state), categoriesByGroupId: getCategoriesByGroupId(state), getSelectedMonthActivityByCategoryId: getSelectedMonthActivityByCategoryId(state), getSelectedMonthBudgetItemsByCategoryId: getSelectedMonthBudgetItemsByCategoryId(state), transactionsSumUpToSelectedMonthByCategoryId: getTransactionsSumUpToSelectedMonthByCategoryId(state), budgetItemsSumUpToSelectedMonthByCategoryId: getBudgetItemsSumUpToSelectedMonthByCategoryId(state) }); export default connect(mapStateToProps)(BudgetTable);
render
identifier_name
BudgetTable.js
import React from 'react'; import { getCategoryGroups } from '../selectors/categoryGroups'; import { getCategoriesByGroupId } from '../selectors/categories'; import { getSelectedMonthBudgetItemsByCategoryId, getBudgetItemsSumUpToSelectedMonthByCategoryId } from '../selectors/budgetItems'; import { getTransactionsSumUpToSelectedMonthByCategoryId, getSelectedMonthActivityByCategoryId } from '../selectors/transactions'; import {connect} from 'react-redux'; import CategoryRow from './CategoryRow'; import CategoryGroupRow from './CategoryGroupRow'; import ui from 'redux-ui'; @ui({ state: { editingCategoryId: undefined } }) class BudgetTable extends React.Component { static propTypes = { categoryGroups: React.PropTypes.array.isRequired, categoriesByGroupId: React.PropTypes.object.isRequired, getSelectedMonthActivityByCategoryId: React.PropTypes.object.isRequired, getSelectedMonthBudgetItemsByCategoryId: React.PropTypes.object.isRequired, transactionsSumUpToSelectedMonthByCategoryId: React.PropTypes.object.isRequired, budgetItemsSumUpToSelectedMonthByCategoryId: React.PropTypes.object.isRequired } render() { const rows = []; this.props.categoryGroups.forEach(cg => { rows.push(<CategoryGroupRow key={"cg"+cg.id} name={cg.name} />); if (this.props.categoriesByGroupId[cg.id])
}); return ( <table className="table"> <thead> <tr> <th>Category</th> <th>Budgeted</th> <th>Activity</th> <th>Available</th> </tr> </thead> <tbody> {rows} </tbody> </table> ); } } const mapStateToProps = (state) => ({ categoryGroups: getCategoryGroups(state), categoriesByGroupId: getCategoriesByGroupId(state), getSelectedMonthActivityByCategoryId: getSelectedMonthActivityByCategoryId(state), getSelectedMonthBudgetItemsByCategoryId: getSelectedMonthBudgetItemsByCategoryId(state), transactionsSumUpToSelectedMonthByCategoryId: getTransactionsSumUpToSelectedMonthByCategoryId(state), budgetItemsSumUpToSelectedMonthByCategoryId: getBudgetItemsSumUpToSelectedMonthByCategoryId(state) }); export default connect(mapStateToProps)(BudgetTable);
{ this.props.categoriesByGroupId[cg.id].forEach(c => { rows.push(<CategoryRow key={"c"+c.id} category={c} budgetItem={this.props.getSelectedMonthBudgetItemsByCategoryId[c.id]} activity={this.props.getSelectedMonthActivityByCategoryId[c.id]} available={(this.props.budgetItemsSumUpToSelectedMonthByCategoryId[c.id] || 0) + (this.props.transactionsSumUpToSelectedMonthByCategoryId[c.id] || 0)} />); }); }
conditional_block
math-helper.ts
export class Point { x: number; y: number; constructor(x: number, y: number) { this.x = x; this.y = y; } delta(p: Point): Point { return new Point(this.x + p.x, this.y + p.y); } add(p: Point) { return new Point(this.x + p.x, this.y + p.y); } subtract(p: Point) { return new Point(this.x - p.x, this.y - p.y); } multiply(n: number) { return new Point(this.x * n, this.y * n); } isOnLine(line: Line) { const SELECTION_FUZZINESS = 3; let leftPoint: Point; let rightPoint: Point; // Normalize start/end to left right to make the offset calc simpler. if (line.src.x <= line.dst.x)
else { leftPoint = line.dst; rightPoint = line.src; } // If point is out of bounds, no need to do further checks. if (this.x + SELECTION_FUZZINESS < leftPoint.x || rightPoint.x < this.x - SELECTION_FUZZINESS) return false; else if (this.y + SELECTION_FUZZINESS < Math.min(leftPoint.y, rightPoint.y) || Math.max(leftPoint.y, rightPoint.y) < this.y - SELECTION_FUZZINESS) return false; let deltaX = rightPoint.x - leftPoint.x; let deltaY = rightPoint.y - leftPoint.y; // If the line is straight, the earlier boundary check is enough to determine that the point is on the line. // Also prevents division by zero exceptions. if (deltaX == 0 || deltaY == 0) return true; let slope = deltaY / deltaX; let offset = leftPoint.y - leftPoint.x * slope; let calculatedY = this.x * slope + offset; // Check calculated Y matches the points Y coord with some easing. let lineContains: boolean = this.y - SELECTION_FUZZINESS <= calculatedY && calculatedY <= this.y + SELECTION_FUZZINESS; return lineContains; } distance(p: Point): number { return Math.sqrt( ((p.x - this.x) * (p.x - this.x)) + ((p.y - this.y) * (p.y - this.y)) ); } get negated(): Point { return new Point(-this.x, -this.y); } } export class Line { src: Point; dst: Point; constructor(src: Point, dst: Point) { this.src = src; this.dst = dst; } get pointingLeft(): boolean { return this.src.x > this.dst.x; } get angle(): number { let dy = this.dst.y - this.src.y; let dx = this.dst.x - this.src.x; let theta = Math.atan2(dy, dx); // range (-PI, PI] theta *= 180 / Math.PI; // rads to degs, range (-180, 180] return theta; } } export class Rect { bottom: number; left: number; right: number; top: number; get height(): number { return this.bottom - this.top; } get width(): number { return this.right - this.left; } get center(): Point { return new Point(this.left + this.width / 2, this.top + this.height / 2); } get halfPoint(): Point { return new Point(this.width / 2, this.height / 2); } get topLeft(): Point { return new Point(this.left, this.top); } constructor(rect: ClientRect) { this.top = rect.top; this.bottom = rect.bottom; this.left = rect.left; this.right = rect.right; } get topEdge(): Line { return new Line(new Point(this.left, this.top), new Point(this.right, this.top)); } get bottomEdge(): Line { return new Line(new Point(this.left, this.bottom), new Point(this.right, this.bottom)); } get leftEdge(): Line { return new Line(new Point(this.left, this.top), new Point(this.left, this.bottom)); } get rightEdge(): Line { return new Line(new Point(this.right, this.top), new Point(this.right, this.bottom)); } multiply(n: number) { this.left *= n; this.top *= n; this.right *= n; this.bottom *= n; } offset(p: Point) { this.bottom += p.y; this.top += p.y; this.left += p.x; this.right += p.x; } getPointOfIntersection(line: Line): Point { let edges: Array<Line> = [ this.topEdge, this.bottomEdge, this.leftEdge, this.rightEdge ]; for (let edge of edges) { let denom = (edge.dst.y - edge.src.y) * (line.dst.x - line.src.x) - (edge.dst.x - edge.src.x) * (line.dst.y - line.src.y); if (denom === 0) { continue; } let ua = ((edge.dst.x - edge.src.x) * (line.src.y - edge.src.y) - (edge.dst.y - edge.src.y) * (line.src.x - edge.src.x)) / denom; let ub = ((line.dst.x - line.src.x) * (line.src.y - edge.src.y) - (line.dst.y - line.src.y) * (line.src.x - edge.src.x)) / denom; let seg1 = ua >= 0 && ua <= 1; let seg2 = ub >= 0 && ub <= 1; if (seg1 && seg2) { return new Point(line.src.x + ua * (line.dst.x - line.src.x), line.src.y + ua * (line.dst.y - line.src.y)); } } return null; } }
{ leftPoint = line.src; rightPoint = line.dst; }
conditional_block
math-helper.ts
export class Point { x: number; y: number; constructor(x: number, y: number) { this.x = x; this.y = y; } delta(p: Point): Point { return new Point(this.x + p.x, this.y + p.y); } add(p: Point) { return new Point(this.x + p.x, this.y + p.y); } subtract(p: Point)
multiply(n: number) { return new Point(this.x * n, this.y * n); } isOnLine(line: Line) { const SELECTION_FUZZINESS = 3; let leftPoint: Point; let rightPoint: Point; // Normalize start/end to left right to make the offset calc simpler. if (line.src.x <= line.dst.x) { leftPoint = line.src; rightPoint = line.dst; } else { leftPoint = line.dst; rightPoint = line.src; } // If point is out of bounds, no need to do further checks. if (this.x + SELECTION_FUZZINESS < leftPoint.x || rightPoint.x < this.x - SELECTION_FUZZINESS) return false; else if (this.y + SELECTION_FUZZINESS < Math.min(leftPoint.y, rightPoint.y) || Math.max(leftPoint.y, rightPoint.y) < this.y - SELECTION_FUZZINESS) return false; let deltaX = rightPoint.x - leftPoint.x; let deltaY = rightPoint.y - leftPoint.y; // If the line is straight, the earlier boundary check is enough to determine that the point is on the line. // Also prevents division by zero exceptions. if (deltaX == 0 || deltaY == 0) return true; let slope = deltaY / deltaX; let offset = leftPoint.y - leftPoint.x * slope; let calculatedY = this.x * slope + offset; // Check calculated Y matches the points Y coord with some easing. let lineContains: boolean = this.y - SELECTION_FUZZINESS <= calculatedY && calculatedY <= this.y + SELECTION_FUZZINESS; return lineContains; } distance(p: Point): number { return Math.sqrt( ((p.x - this.x) * (p.x - this.x)) + ((p.y - this.y) * (p.y - this.y)) ); } get negated(): Point { return new Point(-this.x, -this.y); } } export class Line { src: Point; dst: Point; constructor(src: Point, dst: Point) { this.src = src; this.dst = dst; } get pointingLeft(): boolean { return this.src.x > this.dst.x; } get angle(): number { let dy = this.dst.y - this.src.y; let dx = this.dst.x - this.src.x; let theta = Math.atan2(dy, dx); // range (-PI, PI] theta *= 180 / Math.PI; // rads to degs, range (-180, 180] return theta; } } export class Rect { bottom: number; left: number; right: number; top: number; get height(): number { return this.bottom - this.top; } get width(): number { return this.right - this.left; } get center(): Point { return new Point(this.left + this.width / 2, this.top + this.height / 2); } get halfPoint(): Point { return new Point(this.width / 2, this.height / 2); } get topLeft(): Point { return new Point(this.left, this.top); } constructor(rect: ClientRect) { this.top = rect.top; this.bottom = rect.bottom; this.left = rect.left; this.right = rect.right; } get topEdge(): Line { return new Line(new Point(this.left, this.top), new Point(this.right, this.top)); } get bottomEdge(): Line { return new Line(new Point(this.left, this.bottom), new Point(this.right, this.bottom)); } get leftEdge(): Line { return new Line(new Point(this.left, this.top), new Point(this.left, this.bottom)); } get rightEdge(): Line { return new Line(new Point(this.right, this.top), new Point(this.right, this.bottom)); } multiply(n: number) { this.left *= n; this.top *= n; this.right *= n; this.bottom *= n; } offset(p: Point) { this.bottom += p.y; this.top += p.y; this.left += p.x; this.right += p.x; } getPointOfIntersection(line: Line): Point { let edges: Array<Line> = [ this.topEdge, this.bottomEdge, this.leftEdge, this.rightEdge ]; for (let edge of edges) { let denom = (edge.dst.y - edge.src.y) * (line.dst.x - line.src.x) - (edge.dst.x - edge.src.x) * (line.dst.y - line.src.y); if (denom === 0) { continue; } let ua = ((edge.dst.x - edge.src.x) * (line.src.y - edge.src.y) - (edge.dst.y - edge.src.y) * (line.src.x - edge.src.x)) / denom; let ub = ((line.dst.x - line.src.x) * (line.src.y - edge.src.y) - (line.dst.y - line.src.y) * (line.src.x - edge.src.x)) / denom; let seg1 = ua >= 0 && ua <= 1; let seg2 = ub >= 0 && ub <= 1; if (seg1 && seg2) { return new Point(line.src.x + ua * (line.dst.x - line.src.x), line.src.y + ua * (line.dst.y - line.src.y)); } } return null; } }
{ return new Point(this.x - p.x, this.y - p.y); }
identifier_body
math-helper.ts
export class Point { x: number; y: number; constructor(x: number, y: number) { this.x = x; this.y = y; } delta(p: Point): Point { return new Point(this.x + p.x, this.y + p.y); } add(p: Point) { return new Point(this.x + p.x, this.y + p.y); } subtract(p: Point) { return new Point(this.x - p.x, this.y - p.y); } multiply(n: number) { return new Point(this.x * n, this.y * n); } isOnLine(line: Line) { const SELECTION_FUZZINESS = 3; let leftPoint: Point; let rightPoint: Point; // Normalize start/end to left right to make the offset calc simpler. if (line.src.x <= line.dst.x) { leftPoint = line.src; rightPoint = line.dst; } else { leftPoint = line.dst; rightPoint = line.src; } // If point is out of bounds, no need to do further checks. if (this.x + SELECTION_FUZZINESS < leftPoint.x || rightPoint.x < this.x - SELECTION_FUZZINESS) return false; else if (this.y + SELECTION_FUZZINESS < Math.min(leftPoint.y, rightPoint.y) || Math.max(leftPoint.y, rightPoint.y) < this.y - SELECTION_FUZZINESS) return false; let deltaX = rightPoint.x - leftPoint.x; let deltaY = rightPoint.y - leftPoint.y; // If the line is straight, the earlier boundary check is enough to determine that the point is on the line. // Also prevents division by zero exceptions. if (deltaX == 0 || deltaY == 0) return true; let slope = deltaY / deltaX; let offset = leftPoint.y - leftPoint.x * slope; let calculatedY = this.x * slope + offset; // Check calculated Y matches the points Y coord with some easing. let lineContains: boolean = this.y - SELECTION_FUZZINESS <= calculatedY && calculatedY <= this.y + SELECTION_FUZZINESS; return lineContains; } distance(p: Point): number {
} get negated(): Point { return new Point(-this.x, -this.y); } } export class Line { src: Point; dst: Point; constructor(src: Point, dst: Point) { this.src = src; this.dst = dst; } get pointingLeft(): boolean { return this.src.x > this.dst.x; } get angle(): number { let dy = this.dst.y - this.src.y; let dx = this.dst.x - this.src.x; let theta = Math.atan2(dy, dx); // range (-PI, PI] theta *= 180 / Math.PI; // rads to degs, range (-180, 180] return theta; } } export class Rect { bottom: number; left: number; right: number; top: number; get height(): number { return this.bottom - this.top; } get width(): number { return this.right - this.left; } get center(): Point { return new Point(this.left + this.width / 2, this.top + this.height / 2); } get halfPoint(): Point { return new Point(this.width / 2, this.height / 2); } get topLeft(): Point { return new Point(this.left, this.top); } constructor(rect: ClientRect) { this.top = rect.top; this.bottom = rect.bottom; this.left = rect.left; this.right = rect.right; } get topEdge(): Line { return new Line(new Point(this.left, this.top), new Point(this.right, this.top)); } get bottomEdge(): Line { return new Line(new Point(this.left, this.bottom), new Point(this.right, this.bottom)); } get leftEdge(): Line { return new Line(new Point(this.left, this.top), new Point(this.left, this.bottom)); } get rightEdge(): Line { return new Line(new Point(this.right, this.top), new Point(this.right, this.bottom)); } multiply(n: number) { this.left *= n; this.top *= n; this.right *= n; this.bottom *= n; } offset(p: Point) { this.bottom += p.y; this.top += p.y; this.left += p.x; this.right += p.x; } getPointOfIntersection(line: Line): Point { let edges: Array<Line> = [ this.topEdge, this.bottomEdge, this.leftEdge, this.rightEdge ]; for (let edge of edges) { let denom = (edge.dst.y - edge.src.y) * (line.dst.x - line.src.x) - (edge.dst.x - edge.src.x) * (line.dst.y - line.src.y); if (denom === 0) { continue; } let ua = ((edge.dst.x - edge.src.x) * (line.src.y - edge.src.y) - (edge.dst.y - edge.src.y) * (line.src.x - edge.src.x)) / denom; let ub = ((line.dst.x - line.src.x) * (line.src.y - edge.src.y) - (line.dst.y - line.src.y) * (line.src.x - edge.src.x)) / denom; let seg1 = ua >= 0 && ua <= 1; let seg2 = ub >= 0 && ub <= 1; if (seg1 && seg2) { return new Point(line.src.x + ua * (line.dst.x - line.src.x), line.src.y + ua * (line.dst.y - line.src.y)); } } return null; } }
return Math.sqrt( ((p.x - this.x) * (p.x - this.x)) + ((p.y - this.y) * (p.y - this.y)) );
random_line_split
math-helper.ts
export class Point { x: number; y: number; constructor(x: number, y: number) { this.x = x; this.y = y; } delta(p: Point): Point { return new Point(this.x + p.x, this.y + p.y); } add(p: Point) { return new Point(this.x + p.x, this.y + p.y); }
(p: Point) { return new Point(this.x - p.x, this.y - p.y); } multiply(n: number) { return new Point(this.x * n, this.y * n); } isOnLine(line: Line) { const SELECTION_FUZZINESS = 3; let leftPoint: Point; let rightPoint: Point; // Normalize start/end to left right to make the offset calc simpler. if (line.src.x <= line.dst.x) { leftPoint = line.src; rightPoint = line.dst; } else { leftPoint = line.dst; rightPoint = line.src; } // If point is out of bounds, no need to do further checks. if (this.x + SELECTION_FUZZINESS < leftPoint.x || rightPoint.x < this.x - SELECTION_FUZZINESS) return false; else if (this.y + SELECTION_FUZZINESS < Math.min(leftPoint.y, rightPoint.y) || Math.max(leftPoint.y, rightPoint.y) < this.y - SELECTION_FUZZINESS) return false; let deltaX = rightPoint.x - leftPoint.x; let deltaY = rightPoint.y - leftPoint.y; // If the line is straight, the earlier boundary check is enough to determine that the point is on the line. // Also prevents division by zero exceptions. if (deltaX == 0 || deltaY == 0) return true; let slope = deltaY / deltaX; let offset = leftPoint.y - leftPoint.x * slope; let calculatedY = this.x * slope + offset; // Check calculated Y matches the points Y coord with some easing. let lineContains: boolean = this.y - SELECTION_FUZZINESS <= calculatedY && calculatedY <= this.y + SELECTION_FUZZINESS; return lineContains; } distance(p: Point): number { return Math.sqrt( ((p.x - this.x) * (p.x - this.x)) + ((p.y - this.y) * (p.y - this.y)) ); } get negated(): Point { return new Point(-this.x, -this.y); } } export class Line { src: Point; dst: Point; constructor(src: Point, dst: Point) { this.src = src; this.dst = dst; } get pointingLeft(): boolean { return this.src.x > this.dst.x; } get angle(): number { let dy = this.dst.y - this.src.y; let dx = this.dst.x - this.src.x; let theta = Math.atan2(dy, dx); // range (-PI, PI] theta *= 180 / Math.PI; // rads to degs, range (-180, 180] return theta; } } export class Rect { bottom: number; left: number; right: number; top: number; get height(): number { return this.bottom - this.top; } get width(): number { return this.right - this.left; } get center(): Point { return new Point(this.left + this.width / 2, this.top + this.height / 2); } get halfPoint(): Point { return new Point(this.width / 2, this.height / 2); } get topLeft(): Point { return new Point(this.left, this.top); } constructor(rect: ClientRect) { this.top = rect.top; this.bottom = rect.bottom; this.left = rect.left; this.right = rect.right; } get topEdge(): Line { return new Line(new Point(this.left, this.top), new Point(this.right, this.top)); } get bottomEdge(): Line { return new Line(new Point(this.left, this.bottom), new Point(this.right, this.bottom)); } get leftEdge(): Line { return new Line(new Point(this.left, this.top), new Point(this.left, this.bottom)); } get rightEdge(): Line { return new Line(new Point(this.right, this.top), new Point(this.right, this.bottom)); } multiply(n: number) { this.left *= n; this.top *= n; this.right *= n; this.bottom *= n; } offset(p: Point) { this.bottom += p.y; this.top += p.y; this.left += p.x; this.right += p.x; } getPointOfIntersection(line: Line): Point { let edges: Array<Line> = [ this.topEdge, this.bottomEdge, this.leftEdge, this.rightEdge ]; for (let edge of edges) { let denom = (edge.dst.y - edge.src.y) * (line.dst.x - line.src.x) - (edge.dst.x - edge.src.x) * (line.dst.y - line.src.y); if (denom === 0) { continue; } let ua = ((edge.dst.x - edge.src.x) * (line.src.y - edge.src.y) - (edge.dst.y - edge.src.y) * (line.src.x - edge.src.x)) / denom; let ub = ((line.dst.x - line.src.x) * (line.src.y - edge.src.y) - (line.dst.y - line.src.y) * (line.src.x - edge.src.x)) / denom; let seg1 = ua >= 0 && ua <= 1; let seg2 = ub >= 0 && ub <= 1; if (seg1 && seg2) { return new Point(line.src.x + ua * (line.dst.x - line.src.x), line.src.y + ua * (line.dst.y - line.src.y)); } } return null; } }
subtract
identifier_name
script.py
from nider.core import Font from nider.core import Outline from nider.models import Header from nider.models import Paragraph from nider.models import Linkback from nider.models import Content from nider.models import TwitterPost # TODO: change this fontpath to the fontpath on your machine roboto_font_folder = '/home/ovd/.local/share/fonts/Roboto/' outline = Outline(2, '#121212') header = Header(text='Your super interesting title!', font=Font(roboto_font_folder + 'Roboto-Bold.ttf', 30), text_width=40, align='left', color='#ededed' ) para = Paragraph(text='Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.', font=Font(roboto_font_folder + 'Roboto-Medium.ttf', 29), text_width=65, align='left', color='#ededed' ) linkback = Linkback(text='foo.com | @username', font=Font(roboto_font_folder + 'Roboto-Bold.ttf', 24), color='#ededed' ) content = Content(para, header, linkback) img = TwitterPost(content, fullpath='result.png' ) # TODO: change this texture path to the texture path on your machine
img.draw_on_texture('texture.png')
random_line_split
queries.generated.ts
/* eslint-disable */ import * as Types from '../graphqlTypes.generated'; import { gql } from '@apollo/client'; import * as Apollo from '@apollo/client'; const defaultOptions = {} as const; export type EmailRouteFieldsFragment = { __typename: 'EmailRoute', id: string, receiver_address: string, forward_addresses?: Array<string> | null }; export type RootSiteEmailRoutesAdminTableQueryVariables = Types.Exact<{ page?: Types.InputMaybe<Types.Scalars['Int']>; filters?: Types.InputMaybe<Types.EmailRouteFiltersInput>; sort?: Types.InputMaybe<Array<Types.SortInput> | Types.SortInput>; }>; export type RootSiteEmailRoutesAdminTableQueryData = { __typename: 'Query', email_routes_paginated: { __typename: 'EmailRoutesPagination', total_entries: number, total_pages: number, entries: Array<{ __typename: 'EmailRoute', id: string, receiver_address: string, forward_addresses?: Array<string> | null }> } }; export const EmailRouteFieldsFragmentDoc = gql` fragment EmailRouteFields on EmailRoute { id receiver_address forward_addresses } `; export const RootSiteEmailRoutesAdminTableQueryDocument = gql` query RootSiteEmailRoutesAdminTableQuery($page: Int, $filters: EmailRouteFiltersInput, $sort: [SortInput!]) { email_routes_paginated(page: $page, filters: $filters, sort: $sort) { total_entries total_pages entries { id ...EmailRouteFields } } } ${EmailRouteFieldsFragmentDoc}`; /** * __useRootSiteEmailRoutesAdminTableQuery__ * * To run a query within a React component, call `useRootSiteEmailRoutesAdminTableQuery` and pass it any options that fit your needs. * When your component renders, `useRootSiteEmailRoutesAdminTableQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useRootSiteEmailRoutesAdminTableQuery({
* variables: { * page: // value for 'page' * filters: // value for 'filters' * sort: // value for 'sort' * }, * }); */ export function useRootSiteEmailRoutesAdminTableQuery(baseOptions?: Apollo.QueryHookOptions<RootSiteEmailRoutesAdminTableQueryData, RootSiteEmailRoutesAdminTableQueryVariables>) { const options = {...defaultOptions, ...baseOptions} return Apollo.useQuery<RootSiteEmailRoutesAdminTableQueryData, RootSiteEmailRoutesAdminTableQueryVariables>(RootSiteEmailRoutesAdminTableQueryDocument, options); } export function useRootSiteEmailRoutesAdminTableQueryLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<RootSiteEmailRoutesAdminTableQueryData, RootSiteEmailRoutesAdminTableQueryVariables>) { const options = {...defaultOptions, ...baseOptions} return Apollo.useLazyQuery<RootSiteEmailRoutesAdminTableQueryData, RootSiteEmailRoutesAdminTableQueryVariables>(RootSiteEmailRoutesAdminTableQueryDocument, options); } export type RootSiteEmailRoutesAdminTableQueryHookResult = ReturnType<typeof useRootSiteEmailRoutesAdminTableQuery>; export type RootSiteEmailRoutesAdminTableQueryLazyQueryHookResult = ReturnType<typeof useRootSiteEmailRoutesAdminTableQueryLazyQuery>; export type RootSiteEmailRoutesAdminTableQueryQueryResult = Apollo.QueryResult<RootSiteEmailRoutesAdminTableQueryData, RootSiteEmailRoutesAdminTableQueryVariables>;
random_line_split
queries.generated.ts
/* eslint-disable */ import * as Types from '../graphqlTypes.generated'; import { gql } from '@apollo/client'; import * as Apollo from '@apollo/client'; const defaultOptions = {} as const; export type EmailRouteFieldsFragment = { __typename: 'EmailRoute', id: string, receiver_address: string, forward_addresses?: Array<string> | null }; export type RootSiteEmailRoutesAdminTableQueryVariables = Types.Exact<{ page?: Types.InputMaybe<Types.Scalars['Int']>; filters?: Types.InputMaybe<Types.EmailRouteFiltersInput>; sort?: Types.InputMaybe<Array<Types.SortInput> | Types.SortInput>; }>; export type RootSiteEmailRoutesAdminTableQueryData = { __typename: 'Query', email_routes_paginated: { __typename: 'EmailRoutesPagination', total_entries: number, total_pages: number, entries: Array<{ __typename: 'EmailRoute', id: string, receiver_address: string, forward_addresses?: Array<string> | null }> } }; export const EmailRouteFieldsFragmentDoc = gql` fragment EmailRouteFields on EmailRoute { id receiver_address forward_addresses } `; export const RootSiteEmailRoutesAdminTableQueryDocument = gql` query RootSiteEmailRoutesAdminTableQuery($page: Int, $filters: EmailRouteFiltersInput, $sort: [SortInput!]) { email_routes_paginated(page: $page, filters: $filters, sort: $sort) { total_entries total_pages entries { id ...EmailRouteFields } } } ${EmailRouteFieldsFragmentDoc}`; /** * __useRootSiteEmailRoutesAdminTableQuery__ * * To run a query within a React component, call `useRootSiteEmailRoutesAdminTableQuery` and pass it any options that fit your needs. * When your component renders, `useRootSiteEmailRoutesAdminTableQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useRootSiteEmailRoutesAdminTableQuery({ * variables: { * page: // value for 'page' * filters: // value for 'filters' * sort: // value for 'sort' * }, * }); */ export function useRootSiteEmailRoutesAdminTableQuery(baseOptions?: Apollo.QueryHookOptions<RootSiteEmailRoutesAdminTableQueryData, RootSiteEmailRoutesAdminTableQueryVariables>) { const options = {...defaultOptions, ...baseOptions} return Apollo.useQuery<RootSiteEmailRoutesAdminTableQueryData, RootSiteEmailRoutesAdminTableQueryVariables>(RootSiteEmailRoutesAdminTableQueryDocument, options); } export function
(baseOptions?: Apollo.LazyQueryHookOptions<RootSiteEmailRoutesAdminTableQueryData, RootSiteEmailRoutesAdminTableQueryVariables>) { const options = {...defaultOptions, ...baseOptions} return Apollo.useLazyQuery<RootSiteEmailRoutesAdminTableQueryData, RootSiteEmailRoutesAdminTableQueryVariables>(RootSiteEmailRoutesAdminTableQueryDocument, options); } export type RootSiteEmailRoutesAdminTableQueryHookResult = ReturnType<typeof useRootSiteEmailRoutesAdminTableQuery>; export type RootSiteEmailRoutesAdminTableQueryLazyQueryHookResult = ReturnType<typeof useRootSiteEmailRoutesAdminTableQueryLazyQuery>; export type RootSiteEmailRoutesAdminTableQueryQueryResult = Apollo.QueryResult<RootSiteEmailRoutesAdminTableQueryData, RootSiteEmailRoutesAdminTableQueryVariables>;
useRootSiteEmailRoutesAdminTableQueryLazyQuery
identifier_name
queries.generated.ts
/* eslint-disable */ import * as Types from '../graphqlTypes.generated'; import { gql } from '@apollo/client'; import * as Apollo from '@apollo/client'; const defaultOptions = {} as const; export type EmailRouteFieldsFragment = { __typename: 'EmailRoute', id: string, receiver_address: string, forward_addresses?: Array<string> | null }; export type RootSiteEmailRoutesAdminTableQueryVariables = Types.Exact<{ page?: Types.InputMaybe<Types.Scalars['Int']>; filters?: Types.InputMaybe<Types.EmailRouteFiltersInput>; sort?: Types.InputMaybe<Array<Types.SortInput> | Types.SortInput>; }>; export type RootSiteEmailRoutesAdminTableQueryData = { __typename: 'Query', email_routes_paginated: { __typename: 'EmailRoutesPagination', total_entries: number, total_pages: number, entries: Array<{ __typename: 'EmailRoute', id: string, receiver_address: string, forward_addresses?: Array<string> | null }> } }; export const EmailRouteFieldsFragmentDoc = gql` fragment EmailRouteFields on EmailRoute { id receiver_address forward_addresses } `; export const RootSiteEmailRoutesAdminTableQueryDocument = gql` query RootSiteEmailRoutesAdminTableQuery($page: Int, $filters: EmailRouteFiltersInput, $sort: [SortInput!]) { email_routes_paginated(page: $page, filters: $filters, sort: $sort) { total_entries total_pages entries { id ...EmailRouteFields } } } ${EmailRouteFieldsFragmentDoc}`; /** * __useRootSiteEmailRoutesAdminTableQuery__ * * To run a query within a React component, call `useRootSiteEmailRoutesAdminTableQuery` and pass it any options that fit your needs. * When your component renders, `useRootSiteEmailRoutesAdminTableQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useRootSiteEmailRoutesAdminTableQuery({ * variables: { * page: // value for 'page' * filters: // value for 'filters' * sort: // value for 'sort' * }, * }); */ export function useRootSiteEmailRoutesAdminTableQuery(baseOptions?: Apollo.QueryHookOptions<RootSiteEmailRoutesAdminTableQueryData, RootSiteEmailRoutesAdminTableQueryVariables>)
export function useRootSiteEmailRoutesAdminTableQueryLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<RootSiteEmailRoutesAdminTableQueryData, RootSiteEmailRoutesAdminTableQueryVariables>) { const options = {...defaultOptions, ...baseOptions} return Apollo.useLazyQuery<RootSiteEmailRoutesAdminTableQueryData, RootSiteEmailRoutesAdminTableQueryVariables>(RootSiteEmailRoutesAdminTableQueryDocument, options); } export type RootSiteEmailRoutesAdminTableQueryHookResult = ReturnType<typeof useRootSiteEmailRoutesAdminTableQuery>; export type RootSiteEmailRoutesAdminTableQueryLazyQueryHookResult = ReturnType<typeof useRootSiteEmailRoutesAdminTableQueryLazyQuery>; export type RootSiteEmailRoutesAdminTableQueryQueryResult = Apollo.QueryResult<RootSiteEmailRoutesAdminTableQueryData, RootSiteEmailRoutesAdminTableQueryVariables>;
{ const options = {...defaultOptions, ...baseOptions} return Apollo.useQuery<RootSiteEmailRoutesAdminTableQueryData, RootSiteEmailRoutesAdminTableQueryVariables>(RootSiteEmailRoutesAdminTableQueryDocument, options); }
identifier_body
multiple_tpus_test.py
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import threading import unittest from . import test_utils from edgetpu.basic import edgetpu_utils from edgetpu.classification.engine import BasicEngine from edgetpu.classification.engine import ClassificationEngine from edgetpu.detection.engine import DetectionEngine import numpy as np class MultipleTpusTest(unittest.TestCase): def test_create_basic_engine_with_specific_path(self):
def test_run_classification_and_detection_engine(self): def classification_task(num_inferences): tid = threading.get_ident() print('Thread: %d, %d inferences for classification task' % (tid, num_inferences)) labels = test_utils.read_label_file( test_utils.test_data_path('imagenet_labels.txt')) model_name = 'mobilenet_v1_1.0_224_quant_edgetpu.tflite' engine = ClassificationEngine(test_utils.test_data_path(model_name)) print('Thread: %d, using device %s' % (tid, engine.device_path())) with test_utils.test_image('cat.bmp') as img: for _ in range(num_inferences): ret = engine.classify_with_image(img, top_k=1) self.assertEqual(len(ret), 1) self.assertEqual(labels[ret[0][0]], 'Egyptian cat') print('Thread: %d, done classification task' % tid) def detection_task(num_inferences): tid = threading.get_ident() print('Thread: %d, %d inferences for detection task' % (tid, num_inferences)) model_name = 'ssd_mobilenet_v1_coco_quant_postprocess_edgetpu.tflite' engine = DetectionEngine(test_utils.test_data_path(model_name)) print('Thread: %d, using device %s' % (tid, engine.device_path())) with test_utils.test_image('cat.bmp') as img: for _ in range(num_inferences): ret = engine.detect_with_image(img, top_k=1) self.assertEqual(len(ret), 1) self.assertEqual(ret[0].label_id, 16) # cat self.assertGreater(ret[0].score, 0.7) self.assertGreater( test_utils.iou( np.array([[0.1, 0.1], [0.7, 1.0]]), ret[0].bounding_box), 0.88) print('Thread: %d, done detection task' % tid) num_inferences = 2000 t1 = threading.Thread(target=classification_task, args=(num_inferences,)) t2 = threading.Thread(target=detection_task, args=(num_inferences,)) t1.start() t2.start() t1.join() t2.join() if __name__ == '__main__': unittest.main()
edge_tpus = edgetpu_utils.ListEdgeTpuPaths( edgetpu_utils.EDGE_TPU_STATE_UNASSIGNED) self.assertGreater(len(edge_tpus), 0) model_path = test_utils.test_data_path( 'mobilenet_v1_1.0_224_quant_edgetpu.tflite') basic_engine = BasicEngine(model_path, edge_tpus[0]) self.assertEqual(edge_tpus[0], basic_engine.device_path())
identifier_body
multiple_tpus_test.py
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import threading import unittest from . import test_utils from edgetpu.basic import edgetpu_utils from edgetpu.classification.engine import BasicEngine from edgetpu.classification.engine import ClassificationEngine from edgetpu.detection.engine import DetectionEngine import numpy as np class MultipleTpusTest(unittest.TestCase): def test_create_basic_engine_with_specific_path(self): edge_tpus = edgetpu_utils.ListEdgeTpuPaths( edgetpu_utils.EDGE_TPU_STATE_UNASSIGNED) self.assertGreater(len(edge_tpus), 0)
model_path = test_utils.test_data_path( 'mobilenet_v1_1.0_224_quant_edgetpu.tflite') basic_engine = BasicEngine(model_path, edge_tpus[0]) self.assertEqual(edge_tpus[0], basic_engine.device_path()) def test_run_classification_and_detection_engine(self): def classification_task(num_inferences): tid = threading.get_ident() print('Thread: %d, %d inferences for classification task' % (tid, num_inferences)) labels = test_utils.read_label_file( test_utils.test_data_path('imagenet_labels.txt')) model_name = 'mobilenet_v1_1.0_224_quant_edgetpu.tflite' engine = ClassificationEngine(test_utils.test_data_path(model_name)) print('Thread: %d, using device %s' % (tid, engine.device_path())) with test_utils.test_image('cat.bmp') as img: for _ in range(num_inferences): ret = engine.classify_with_image(img, top_k=1) self.assertEqual(len(ret), 1) self.assertEqual(labels[ret[0][0]], 'Egyptian cat') print('Thread: %d, done classification task' % tid) def detection_task(num_inferences): tid = threading.get_ident() print('Thread: %d, %d inferences for detection task' % (tid, num_inferences)) model_name = 'ssd_mobilenet_v1_coco_quant_postprocess_edgetpu.tflite' engine = DetectionEngine(test_utils.test_data_path(model_name)) print('Thread: %d, using device %s' % (tid, engine.device_path())) with test_utils.test_image('cat.bmp') as img: for _ in range(num_inferences): ret = engine.detect_with_image(img, top_k=1) self.assertEqual(len(ret), 1) self.assertEqual(ret[0].label_id, 16) # cat self.assertGreater(ret[0].score, 0.7) self.assertGreater( test_utils.iou( np.array([[0.1, 0.1], [0.7, 1.0]]), ret[0].bounding_box), 0.88) print('Thread: %d, done detection task' % tid) num_inferences = 2000 t1 = threading.Thread(target=classification_task, args=(num_inferences,)) t2 = threading.Thread(target=detection_task, args=(num_inferences,)) t1.start() t2.start() t1.join() t2.join() if __name__ == '__main__': unittest.main()
random_line_split
multiple_tpus_test.py
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import threading import unittest from . import test_utils from edgetpu.basic import edgetpu_utils from edgetpu.classification.engine import BasicEngine from edgetpu.classification.engine import ClassificationEngine from edgetpu.detection.engine import DetectionEngine import numpy as np class MultipleTpusTest(unittest.TestCase): def test_create_basic_engine_with_specific_path(self): edge_tpus = edgetpu_utils.ListEdgeTpuPaths( edgetpu_utils.EDGE_TPU_STATE_UNASSIGNED) self.assertGreater(len(edge_tpus), 0) model_path = test_utils.test_data_path( 'mobilenet_v1_1.0_224_quant_edgetpu.tflite') basic_engine = BasicEngine(model_path, edge_tpus[0]) self.assertEqual(edge_tpus[0], basic_engine.device_path()) def test_run_classification_and_detection_engine(self): def classification_task(num_inferences): tid = threading.get_ident() print('Thread: %d, %d inferences for classification task' % (tid, num_inferences)) labels = test_utils.read_label_file( test_utils.test_data_path('imagenet_labels.txt')) model_name = 'mobilenet_v1_1.0_224_quant_edgetpu.tflite' engine = ClassificationEngine(test_utils.test_data_path(model_name)) print('Thread: %d, using device %s' % (tid, engine.device_path())) with test_utils.test_image('cat.bmp') as img: for _ in range(num_inferences):
print('Thread: %d, done classification task' % tid) def detection_task(num_inferences): tid = threading.get_ident() print('Thread: %d, %d inferences for detection task' % (tid, num_inferences)) model_name = 'ssd_mobilenet_v1_coco_quant_postprocess_edgetpu.tflite' engine = DetectionEngine(test_utils.test_data_path(model_name)) print('Thread: %d, using device %s' % (tid, engine.device_path())) with test_utils.test_image('cat.bmp') as img: for _ in range(num_inferences): ret = engine.detect_with_image(img, top_k=1) self.assertEqual(len(ret), 1) self.assertEqual(ret[0].label_id, 16) # cat self.assertGreater(ret[0].score, 0.7) self.assertGreater( test_utils.iou( np.array([[0.1, 0.1], [0.7, 1.0]]), ret[0].bounding_box), 0.88) print('Thread: %d, done detection task' % tid) num_inferences = 2000 t1 = threading.Thread(target=classification_task, args=(num_inferences,)) t2 = threading.Thread(target=detection_task, args=(num_inferences,)) t1.start() t2.start() t1.join() t2.join() if __name__ == '__main__': unittest.main()
ret = engine.classify_with_image(img, top_k=1) self.assertEqual(len(ret), 1) self.assertEqual(labels[ret[0][0]], 'Egyptian cat')
conditional_block
multiple_tpus_test.py
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import threading import unittest from . import test_utils from edgetpu.basic import edgetpu_utils from edgetpu.classification.engine import BasicEngine from edgetpu.classification.engine import ClassificationEngine from edgetpu.detection.engine import DetectionEngine import numpy as np class MultipleTpusTest(unittest.TestCase): def test_create_basic_engine_with_specific_path(self): edge_tpus = edgetpu_utils.ListEdgeTpuPaths( edgetpu_utils.EDGE_TPU_STATE_UNASSIGNED) self.assertGreater(len(edge_tpus), 0) model_path = test_utils.test_data_path( 'mobilenet_v1_1.0_224_quant_edgetpu.tflite') basic_engine = BasicEngine(model_path, edge_tpus[0]) self.assertEqual(edge_tpus[0], basic_engine.device_path()) def
(self): def classification_task(num_inferences): tid = threading.get_ident() print('Thread: %d, %d inferences for classification task' % (tid, num_inferences)) labels = test_utils.read_label_file( test_utils.test_data_path('imagenet_labels.txt')) model_name = 'mobilenet_v1_1.0_224_quant_edgetpu.tflite' engine = ClassificationEngine(test_utils.test_data_path(model_name)) print('Thread: %d, using device %s' % (tid, engine.device_path())) with test_utils.test_image('cat.bmp') as img: for _ in range(num_inferences): ret = engine.classify_with_image(img, top_k=1) self.assertEqual(len(ret), 1) self.assertEqual(labels[ret[0][0]], 'Egyptian cat') print('Thread: %d, done classification task' % tid) def detection_task(num_inferences): tid = threading.get_ident() print('Thread: %d, %d inferences for detection task' % (tid, num_inferences)) model_name = 'ssd_mobilenet_v1_coco_quant_postprocess_edgetpu.tflite' engine = DetectionEngine(test_utils.test_data_path(model_name)) print('Thread: %d, using device %s' % (tid, engine.device_path())) with test_utils.test_image('cat.bmp') as img: for _ in range(num_inferences): ret = engine.detect_with_image(img, top_k=1) self.assertEqual(len(ret), 1) self.assertEqual(ret[0].label_id, 16) # cat self.assertGreater(ret[0].score, 0.7) self.assertGreater( test_utils.iou( np.array([[0.1, 0.1], [0.7, 1.0]]), ret[0].bounding_box), 0.88) print('Thread: %d, done detection task' % tid) num_inferences = 2000 t1 = threading.Thread(target=classification_task, args=(num_inferences,)) t2 = threading.Thread(target=detection_task, args=(num_inferences,)) t1.start() t2.start() t1.join() t2.join() if __name__ == '__main__': unittest.main()
test_run_classification_and_detection_engine
identifier_name
Line.ts
import { Attribute, Class } from '../decorators'; import { Element } from '../models'; import { Point } from './Point'; @Class('Line', Element) export class Line extends Element { private _from = new Point(); private _to = new Point(); @Attribute({ type: Point }) get from(): Point { return this._from; } set from(value: Point) { this._from = value; } @Attribute({ type: Point }) get to(): Point { return this._to; } set to(value: Point) { this._to = value; }
} get x1(): number { return this._from.x; } get y1(): number { return this._from.y; } get x2(): number { return this._to.x; } get y2(): number { return this._to.y; } get dy(): number { return this._to.y - this._from.y; } get angle(): number { return Math.atan2(this.dy, this.dx); } get length(): number { return Math.hypot(this.dx, this.dy); } constructor(x1?: number, y1?: number, x2?: number, y2?: number) { super(); if (typeof x1 === 'number' && typeof y1 === 'number' && typeof x2 === 'number' && typeof y2 === 'number') { this._from = new Point(x1, y1); this._to = new Point(x2, y2); } } static fromCoordinates({ x1, y1, x2, y2 }: { x1: number, y1: number, x2: number, y2: number }): Line { const result = new Line(); result.from.x = x1; result.from.y = y1; result.to.x = x2; result.to.y = y2; return result; } static fromTwoPoints(p1: Point, p2: Point): Line { const result = new Line(); result.from = p1; result.to = p2; return result; } /** * Returns the line's coordinates */ getCoordinates(): { x1: number, y1: number, x2: number, y2: number } { const [x1, y1] = this._from.getTuple(); const [x2, y2] = this._to.getTuple(); return { x1, y1, x2, y2 }; } /** * Calculates the distance if a point to this line */ calculateDistanceToPoint(point: Point): number { const { length, x1, y1, x2, y2, dx, dy } = this; if (Math.hypot(point.x - x1, point.y - y1) > length || Math.hypot(point.x - x2, point.y - y2) > length) return Infinity; return Math.abs(dy * point.x - dx * point.y + x2 * y1 - y2 * x1) / length; } /** * Calculates a point on the line. * Offset 0 is the starting point, offset 1 is the ending point. * * @param offset * @param inPixels If true, the offset is given in pixels * @returns a new point instance */ calculatePointBetween(offset: number, inPixels: boolean = false): Point { const { _from, dx, dy } = this; if (inPixels) offset /= this.length; return new Point(_from.x + dx * offset, _from.y + dy * offset); } }
get dx(): number { return this._to.x - this._from.x;
random_line_split
Line.ts
import { Attribute, Class } from '../decorators'; import { Element } from '../models'; import { Point } from './Point'; @Class('Line', Element) export class Line extends Element { private _from = new Point(); private _to = new Point(); @Attribute({ type: Point }) get from(): Point { return this._from; } set from(value: Point)
@Attribute({ type: Point }) get to(): Point { return this._to; } set to(value: Point) { this._to = value; } get dx(): number { return this._to.x - this._from.x; } get x1(): number { return this._from.x; } get y1(): number { return this._from.y; } get x2(): number { return this._to.x; } get y2(): number { return this._to.y; } get dy(): number { return this._to.y - this._from.y; } get angle(): number { return Math.atan2(this.dy, this.dx); } get length(): number { return Math.hypot(this.dx, this.dy); } constructor(x1?: number, y1?: number, x2?: number, y2?: number) { super(); if (typeof x1 === 'number' && typeof y1 === 'number' && typeof x2 === 'number' && typeof y2 === 'number') { this._from = new Point(x1, y1); this._to = new Point(x2, y2); } } static fromCoordinates({ x1, y1, x2, y2 }: { x1: number, y1: number, x2: number, y2: number }): Line { const result = new Line(); result.from.x = x1; result.from.y = y1; result.to.x = x2; result.to.y = y2; return result; } static fromTwoPoints(p1: Point, p2: Point): Line { const result = new Line(); result.from = p1; result.to = p2; return result; } /** * Returns the line's coordinates */ getCoordinates(): { x1: number, y1: number, x2: number, y2: number } { const [x1, y1] = this._from.getTuple(); const [x2, y2] = this._to.getTuple(); return { x1, y1, x2, y2 }; } /** * Calculates the distance if a point to this line */ calculateDistanceToPoint(point: Point): number { const { length, x1, y1, x2, y2, dx, dy } = this; if (Math.hypot(point.x - x1, point.y - y1) > length || Math.hypot(point.x - x2, point.y - y2) > length) return Infinity; return Math.abs(dy * point.x - dx * point.y + x2 * y1 - y2 * x1) / length; } /** * Calculates a point on the line. * Offset 0 is the starting point, offset 1 is the ending point. * * @param offset * @param inPixels If true, the offset is given in pixels * @returns a new point instance */ calculatePointBetween(offset: number, inPixels: boolean = false): Point { const { _from, dx, dy } = this; if (inPixels) offset /= this.length; return new Point(_from.x + dx * offset, _from.y + dy * offset); } }
{ this._from = value; }
identifier_body