idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
11,100 | def min_pixels ( self , value : float ) -> 'Size' : raise_not_number ( value ) self . minimum = '{}px' . format ( value ) return self | Set the minimum size in pixels . |
11,101 | def ems ( self , value : float ) -> 'Size' : raise_not_number ( value ) self . maximum = '{}em' . format ( value ) return self | Set the size in ems . |
11,102 | def min_ems ( self , value : float ) -> 'Size' : raise_not_number ( value ) self . minimum = '{}em' . format ( value ) return self | Set the minimum size in ems . |
11,103 | def fraction ( self , value : float ) -> 'Size' : raise_not_number ( value ) self . maximum = '{}fr' . format ( value ) return self | Set the fraction of free space to use . |
11,104 | def percent ( self , value : float ) -> 'Size' : raise_not_number ( value ) self . maximum = '{}%' . format ( value ) return self | Set the percentage of free space to use . |
11,105 | def min_percent ( self , value : float ) -> 'Size' : raise_not_number ( value ) self . minimum = '{}%' . format ( value ) return self | Set the minimum percentage of free space to use . |
11,106 | def pixels ( self , value : int ) -> 'Gap' : raise_not_number ( value ) self . gap = '{}px' . format ( value ) return self | Set the margin in pixels . |
11,107 | def ems ( self , value : int ) -> 'Gap' : raise_not_number ( value ) self . gap = '{}em' . format ( value ) return self | Set the margin in ems . |
11,108 | def percent ( self , value ) -> 'Gap' : raise_not_number ( value ) self . gap = '{}%' . format ( value ) return self | Set the margin as a percentage . |
11,109 | def add ( self , component : Union [ Component , Sequence [ Component ] ] ) -> None : try : self [ Span ( * self . _available_cell ( ) ) ] = component except NoUnusedCellsError : span = list ( self . _spans . keys ( ) ) [ - 1 ] self . _spans [ span ] += component | Add a widget to the grid in the next available cell . |
11,110 | def _available_cell ( self ) -> Tuple [ int , int ] : cells = set ( itertools . product ( range ( len ( self . rows ) ) , range ( len ( self . columns ) ) ) ) for span in self . _spans : for cell in span . cells : cells . remove ( cell ) if not cells : raise NoUnusedCellsError ( 'No available cells' ) return min ( cells ) | Find next available cell first by row then column . |
11,111 | def add_sidebar ( self , component : Component ) -> None : if not self . sidebar : raise NoSidebarError ( 'Set `sidebar=True` if you want to use the sidebar.' ) if not isinstance ( component , Component ) : raise ValueError ( 'component must be Component type, found {}' . format ( component ) ) self . _controllers . append ( component ) | Add a widget to the sidebar . |
11,112 | def add_route ( self , view : View , path : str , exact : bool = True ) -> None : if path [ 0 ] != '/' : path = '/' + path for route in self . _routes : assert path != route . path , 'Cannot use the same path twice' self . _routes . append ( Route ( view = view , path = path , exact = exact ) ) self . app . add_url_rule ( path , path [ 1 : ] , lambda : render_template ( 'bowtie.html' , title = self . title ) ) | Add a view to the app . |
11,113 | def subscribe ( self , * events : Union [ Event , Pager ] ) -> Callable : try : first_event = events [ 0 ] except IndexError : raise IndexError ( 'Must subscribe to at least one event.' ) if len ( events ) != len ( set ( events ) ) : raise ValueError ( 'Subscribed to the same event multiple times. All events must be unique.' ) if len ( events ) > 1 : for event in events : if isinstance ( event , Pager ) : raise NotStatefulEvent ( 'Pagers must be subscribed by itself.' ) if event . getter is None : raise NotStatefulEvent ( f'{event.uuid}.on_{event.name} is not a stateful event. ' 'It must be used alone.' ) def decorator ( func : Callable ) -> Callable : if isinstance ( first_event , Pager ) : self . _pages [ first_event ] = func elif first_event . name == 'upload' : if first_event . uuid in self . _uploads : warnings . warn ( ( 'Overwriting function "{func1}" with function ' '"{func2}" for upload object "{obj}".' ) . format ( func1 = self . _uploads [ first_event . uuid ] , func2 = func . __name__ , obj = COMPONENT_REGISTRY [ first_event . uuid ] ) , Warning ) self . _uploads [ first_event . uuid ] = func else : for event in events : self . _subscriptions [ event ] . append ( ( events , func ) ) return func return decorator | Call a function in response to an event . |
11,114 | def schedule ( self , seconds : float ) : def wrap ( func : Callable ) : self . _schedules . append ( Scheduler ( self . app , seconds , func ) ) return wrap | Call a function periodically . |
11,115 | def _build ( self , notebook : Optional [ str ] = None ) -> None : if node_version ( ) < _MIN_NODE_VERSION : raise WebpackError ( f'Webpack requires at least version {_MIN_NODE_VERSION} of Node, ' f'found version {node_version}.' ) packages = self . _write_templates ( ) for filename in [ 'package.json' , 'webpack.prod.js' , 'webpack.dev.js' ] : if not ( self . _build_dir / filename ) . is_file ( ) : sourcefile = self . _package_dir / 'src' / filename shutil . copy ( sourcefile , self . _build_dir ) if self . _run ( [ 'yarn' , '--ignore-engines' , 'install' ] , notebook = notebook ) > 1 : raise YarnError ( 'Error installing node packages' ) if packages : installed = self . _installed_packages ( ) new_packages = [ x for x in packages if x . split ( '@' ) [ 0 ] not in installed ] if new_packages : retval = self . _run ( [ 'yarn' , '--ignore-engines' , 'add' ] + new_packages , notebook = notebook ) if retval > 1 : raise YarnError ( 'Error installing node packages' ) elif retval == 1 : print ( 'Yarn error but trying to continue build' ) retval = self . _run ( [ _WEBPACK , '--config' , 'webpack.dev.js' ] , notebook = notebook ) if retval != 0 : raise WebpackError ( 'Error building with webpack' ) | Compile the Bowtie application . |
11,116 | def _installed_packages ( self ) -> Generator [ str , None , None ] : with ( self . _build_dir / 'package.json' ) . open ( 'r' ) as f : packages = json . load ( f ) yield from packages [ 'dependencies' ] . keys ( ) | Extract installed packages as list from package . json . |
11,117 | def _create_jspath ( self ) -> Path : src = self . _build_dir / 'bowtiejs' os . makedirs ( src , exist_ok = True ) return src | Create the source directory for the build . |
11,118 | def _run ( self , command : List [ str ] , notebook : Optional [ str ] = None ) -> int : if notebook is None : return Popen ( command , cwd = self . _build_dir ) . wait ( ) cmd = Popen ( command , cwd = self . _build_dir , stdout = PIPE , stderr = STDOUT ) while True : line = cmd . stdout . readline ( ) if line == b'' and cmd . poll ( ) is not None : return cmd . poll ( ) print ( line . decode ( 'utf-8' ) , end = '' ) raise Exception ( ) | Run command from terminal and notebook and view output from subprocess . |
11,119 | def before_request ( self ) -> Optional [ Response ] : auth = request . authorization if not auth or not self . _check_auth ( auth . username , auth . password ) : return Response ( 'Could not verify your access level for that URL.\n' 'You have to login with proper credentials' , 401 , { 'WWW-Authenticate' : 'Basic realm="Login Required"' } ) session [ 'logged_in' ] = auth . username return None | Determine if a user is allowed to view this route . |
11,120 | def load_notebook ( fullname : str ) : shell = InteractiveShell . instance ( ) path = fullname with open ( path , 'r' , encoding = 'utf-8' ) as f : notebook = read ( f , 4 ) mod = types . ModuleType ( fullname ) mod . __file__ = path mod . __dict__ [ 'get_ipython' ] = get_ipython sys . modules [ fullname ] = mod save_user_ns = shell . user_ns shell . user_ns = mod . __dict__ try : for cell in notebook . cells : if cell . cell_type == 'code' : try : ast . parse ( cell . source ) except SyntaxError : continue try : exec ( cell . source , mod . __dict__ ) except NameError : print ( cell . source ) raise finally : shell . user_ns = save_user_ns return mod | Import a notebook as a module . |
11,121 | def _message ( status , content ) : event = f'message.{status}' if flask . has_request_context ( ) : emit ( event , dict ( data = pack ( content ) ) ) else : sio = flask . current_app . extensions [ 'socketio' ] sio . emit ( event , dict ( data = pack ( content ) ) ) eventlet . sleep ( ) | Send message interface . |
11,122 | def _make_columns ( columns : List [ Union [ int , str ] ] ) -> List [ Dict ] : return [ dict ( title = str ( c ) , dataIndex = str ( c ) , key = str ( c ) ) for c in columns ] | Transform list of columns into AntTable format . |
11,123 | def _make_data ( data ) -> Tuple [ List [ Dict ] , List [ Dict ] ] : jsdata = [ ] for idx , row in data . iterrows ( ) : row . index = row . index . astype ( str ) rdict = row . to_dict ( ) rdict . update ( dict ( key = str ( idx ) ) ) jsdata . append ( rdict ) return jsdata , Table . _make_columns ( data . columns ) | Transform table data into JSON . |
11,124 | def toParallelTargets ( suite , targets ) : targets = filter ( lambda x : x != '.' , targets ) proto_test_list = toProtoTestList ( suite ) modules = set ( [ x . module for x in proto_test_list ] ) non_module_targets = [ ] for target in targets : if not list ( filter ( None , [ target in x for x in modules ] ) ) : non_module_targets . append ( target ) parallel_targets = [ ] for test in proto_test_list : found = False for target in non_module_targets : if ( target in test . dotted_name ) : if target not in parallel_targets : parallel_targets . append ( target ) found = True break if found : continue if test . module not in parallel_targets : parallel_targets . append ( test . module ) return parallel_targets | Produce a list of targets which should be tested in parallel . |
11,125 | def getConfig ( filepath = None ) : parser = configparser . ConfigParser ( ) filepaths = [ ] home = os . getenv ( "HOME" ) if home : default_filepath = os . path . join ( home , ".green" ) if os . path . isfile ( default_filepath ) : filepaths . append ( default_filepath ) env_filepath = os . getenv ( "GREEN_CONFIG" ) if env_filepath and os . path . isfile ( env_filepath ) : filepaths . append ( env_filepath ) for cfg_file in ( "setup.cfg" , ".green" ) : cwd_filepath = os . path . join ( os . getcwd ( ) , cfg_file ) if os . path . isfile ( cwd_filepath ) : filepaths . append ( cwd_filepath ) if filepath and os . path . isfile ( filepath ) : filepaths . append ( filepath ) if filepaths : global files_loaded files_loaded = filepaths read_func = getattr ( parser , 'read_file' , getattr ( parser , 'readfp' ) ) for filepath in filepaths : if filepath . endswith ( 'setup.cfg' ) : with open ( filepath ) as f : read_func ( f ) else : read_func ( ConfigFile ( filepath ) ) return parser | Get the Green config file settings . |
11,126 | def debug ( message , level = 1 ) : if level <= debug_level : logging . debug ( ' ' * ( level - 1 ) * 2 + str ( message ) ) | So we can tune how much debug output we get when we turn it on . |
11,127 | def run ( suite , stream , args , testing = False ) : if not issubclass ( GreenStream , type ( stream ) ) : stream = GreenStream ( stream , disable_windows = args . disable_windows , disable_unidecode = args . disable_unidecode ) result = GreenTestResult ( args , stream ) installHandler ( ) registerResult ( result ) with warnings . catch_warnings ( ) : if args . warnings : warnings . simplefilter ( args . warnings ) if args . warnings in [ 'default' , 'always' ] : warnings . filterwarnings ( 'module' , category = DeprecationWarning , message = 'Please use assert\w+ instead.' ) result . startTestRun ( ) pool = LoggingDaemonlessPool ( processes = args . processes or None , initializer = InitializerOrFinalizer ( args . initializer ) , finalizer = InitializerOrFinalizer ( args . finalizer ) ) manager = multiprocessing . Manager ( ) targets = [ ( target , manager . Queue ( ) ) for target in toParallelTargets ( suite , args . targets ) ] if targets : for index , ( target , queue ) in enumerate ( targets ) : if args . run_coverage : coverage_number = index + 1 else : coverage_number = None debug ( "Sending {} to runner {}" . format ( target , poolRunner ) ) pool . apply_async ( poolRunner , ( target , queue , coverage_number , args . omit_patterns , args . cov_config_file ) ) pool . close ( ) for target , queue in targets : abort = False while True : msg = queue . get ( ) if not msg : break else : result . startTest ( msg ) proto_test_result = queue . get ( ) result . addProtoTestResult ( proto_test_result ) if result . shouldStop : abort = True break if abort : break pool . close ( ) pool . join ( ) result . stopTestRun ( ) removeResult ( result ) return result | Run the given test case or test suite with the specified arguments . |
11,128 | def solve_kkt_ir ( Q , D , G , A , rx , rs , rz , ry , niter = 1 ) : nineq , nz , neq , nBatch = get_sizes ( G , A ) eps = 1e-7 Q_tilde = Q + eps * torch . eye ( nz ) . type_as ( Q ) . repeat ( nBatch , 1 , 1 ) D_tilde = D + eps * torch . eye ( nineq ) . type_as ( Q ) . repeat ( nBatch , 1 , 1 ) dx , ds , dz , dy = factor_solve_kkt_reg ( Q_tilde , D_tilde , G , A , rx , rs , rz , ry , eps ) res = kkt_resid_reg ( Q , D , G , A , eps , dx , ds , dz , dy , rx , rs , rz , ry ) resx , ress , resz , resy = res res = resx for k in range ( niter ) : ddx , dds , ddz , ddy = factor_solve_kkt_reg ( Q_tilde , D_tilde , G , A , - resx , - ress , - resz , - resy if resy is not None else None , eps ) dx , ds , dz , dy = [ v + dv if v is not None else None for v , dv in zip ( ( dx , ds , dz , dy ) , ( ddx , dds , ddz , ddy ) ) ] res = kkt_resid_reg ( Q , D , G , A , eps , dx , ds , dz , dy , rx , rs , rz , ry ) resx , ress , resz , resy = res res = resx return dx , ds , dz , dy | Inefficient iterative refinement . |
11,129 | def timeout ( seconds = None , use_signals = True , timeout_exception = TimeoutError , exception_message = None ) : def decorate ( function ) : if not seconds : return function if use_signals : def handler ( signum , frame ) : _raise_exception ( timeout_exception , exception_message ) @ wraps ( function ) def new_function ( * args , ** kwargs ) : new_seconds = kwargs . pop ( 'timeout' , seconds ) if new_seconds : old = signal . signal ( signal . SIGALRM , handler ) signal . setitimer ( signal . ITIMER_REAL , new_seconds ) try : return function ( * args , ** kwargs ) finally : if new_seconds : signal . setitimer ( signal . ITIMER_REAL , 0 ) signal . signal ( signal . SIGALRM , old ) return new_function else : @ wraps ( function ) def new_function ( * args , ** kwargs ) : timeout_wrapper = _Timeout ( function , timeout_exception , exception_message , seconds ) return timeout_wrapper ( * args , ** kwargs ) return new_function return decorate | Add a timeout parameter to a function and return it . |
11,130 | def _target ( queue , function , * args , ** kwargs ) : try : queue . put ( ( True , function ( * args , ** kwargs ) ) ) except : queue . put ( ( False , sys . exc_info ( ) [ 1 ] ) ) | Run a function with arguments and return output via a queue . |
11,131 | def cancel ( self ) : if self . __process . is_alive ( ) : self . __process . terminate ( ) _raise_exception ( self . __timeout_exception , self . __exception_message ) | Terminate any possible execution of the embedded function . |
11,132 | def ready ( self ) : if self . __timeout < time . time ( ) : self . cancel ( ) return self . __queue . full ( ) and not self . __queue . empty ( ) | Read - only property indicating status of value property . |
11,133 | def value ( self ) : if self . ready is True : flag , load = self . __queue . get ( ) if flag : return load raise load | Read - only property containing data returned from function . |
11,134 | def bbox2path ( xmin , xmax , ymin , ymax ) : b = Line ( xmin + 1j * ymin , xmax + 1j * ymin ) t = Line ( xmin + 1j * ymax , xmax + 1j * ymax ) r = Line ( xmax + 1j * ymin , xmax + 1j * ymax ) l = Line ( xmin + 1j * ymin , xmin + 1j * ymax ) return Path ( b , r , t . reversed ( ) , l . reversed ( ) ) | Converts a bounding box 4 - tuple to a Path object . |
11,135 | def transform ( curve , tf ) : def to_point ( p ) : return np . array ( [ [ p . real ] , [ p . imag ] , [ 1.0 ] ] ) def to_vector ( z ) : return np . array ( [ [ z . real ] , [ z . imag ] , [ 0.0 ] ] ) def to_complex ( v ) : return v . item ( 0 ) + 1j * v . item ( 1 ) if isinstance ( curve , Path ) : return Path ( * [ transform ( segment , tf ) for segment in curve ] ) elif is_bezier_segment ( curve ) : return bpoints2bezier ( [ to_complex ( tf . dot ( to_point ( p ) ) ) for p in curve . bpoints ( ) ] ) elif isinstance ( curve , Arc ) : new_start = to_complex ( tf . dot ( to_point ( curve . start ) ) ) new_end = to_complex ( tf . dot ( to_point ( curve . end ) ) ) new_radius = to_complex ( tf . dot ( to_vector ( curve . radius ) ) ) return Arc ( new_start , radius = new_radius , rotation = curve . rotation , large_arc = curve . large_arc , sweep = curve . sweep , end = new_end ) else : raise TypeError ( "Input `curve` should be a Path, Line, " "QuadraticBezier, CubicBezier, or Arc object." ) | Transforms the curve by the homogeneous transformation matrix tf |
11,136 | def bezier_unit_tangent ( seg , t ) : assert 0 <= t <= 1 dseg = seg . derivative ( t ) try : unit_tangent = dseg / abs ( dseg ) except ( ZeroDivisionError , FloatingPointError ) : dseg_poly = seg . poly ( ) . deriv ( ) dseg_abs_squared_poly = ( real ( dseg_poly ) ** 2 + imag ( dseg_poly ) ** 2 ) try : unit_tangent = csqrt ( rational_limit ( dseg_poly ** 2 , dseg_abs_squared_poly , t ) ) except ValueError : bef = seg . poly ( ) . deriv ( ) ( t - 1e-4 ) aft = seg . poly ( ) . deriv ( ) ( t + 1e-4 ) mes = ( "Unit tangent appears to not be well-defined at " "t = {}, \n" . format ( t ) + "seg.poly().deriv()(t - 1e-4) = {}\n" . format ( bef ) + "seg.poly().deriv()(t + 1e-4) = {}" . format ( aft ) ) raise ValueError ( mes ) return unit_tangent | Returns the unit tangent of the segment at t . |
11,137 | def segment_curvature ( self , t , use_inf = False ) : dz = self . derivative ( t ) ddz = self . derivative ( t , n = 2 ) dx , dy = dz . real , dz . imag ddx , ddy = ddz . real , ddz . imag old_np_seterr = np . seterr ( invalid = 'raise' ) try : kappa = abs ( dx * ddy - dy * ddx ) / sqrt ( dx * dx + dy * dy ) ** 3 except ( ZeroDivisionError , FloatingPointError ) : p = self . poly ( ) dp = p . deriv ( ) ddp = dp . deriv ( ) dx , dy = real ( dp ) , imag ( dp ) ddx , ddy = real ( ddp ) , imag ( ddp ) f2 = ( dx * ddy - dy * ddx ) ** 2 g2 = ( dx * dx + dy * dy ) ** 3 lim2 = rational_limit ( f2 , g2 , t ) if lim2 < 0 : return 0 kappa = sqrt ( lim2 ) finally : np . seterr ( ** old_np_seterr ) return kappa | returns the curvature of the segment at t . |
11,138 | def segment_length ( curve , start , end , start_point , end_point , error = LENGTH_ERROR , min_depth = LENGTH_MIN_DEPTH , depth = 0 ) : mid = ( start + end ) / 2 mid_point = curve . point ( mid ) length = abs ( end_point - start_point ) first_half = abs ( mid_point - start_point ) second_half = abs ( end_point - mid_point ) length2 = first_half + second_half if ( length2 - length > error ) or ( depth < min_depth ) : depth += 1 return ( segment_length ( curve , start , mid , start_point , mid_point , error , min_depth , depth ) + segment_length ( curve , mid , end , mid_point , end_point , error , min_depth , depth ) ) return length2 | Recursively approximates the length by straight lines |
11,139 | def length ( self , t0 = 0 , t1 = 1 , error = None , min_depth = None ) : return abs ( self . end - self . start ) * ( t1 - t0 ) | returns the length of the line segment between t0 and t1 . |
11,140 | def unit_tangent ( self , t = None ) : assert self . end != self . start dseg = self . end - self . start return dseg / abs ( dseg ) | returns the unit tangent of the segment at t . |
11,141 | def point_to_t ( self , point ) : if np . isclose ( point , self . start , rtol = 0 , atol = 1e-6 ) : return 0.0 elif np . isclose ( point , self . end , rtol = 0 , atol = 1e-6 ) : return 1.0 p = self . poly ( ) t = ( point - p [ 0 ] ) / p [ 1 ] if np . isclose ( t . imag , 0 ) and ( t . real >= 0.0 ) and ( t . real <= 1.0 ) : return t . real return None | If the point lies on the Line returns its t parameter . If the point does not lie on the Line returns None . |
11,142 | def scaled ( self , sx , sy = None , origin = 0j ) : return scale ( self , sx = sx , sy = sy , origin = origin ) | Scale transform . See scale function for further explanation . |
11,143 | def poly ( self , return_coeffs = False ) : p = self . bpoints ( ) coeffs = ( p [ 0 ] - 2 * p [ 1 ] + p [ 2 ] , 2 * ( p [ 1 ] - p [ 0 ] ) , p [ 0 ] ) if return_coeffs : return coeffs else : return np . poly1d ( coeffs ) | returns the quadratic as a Polynomial object . |
11,144 | def reversed ( self ) : new_quad = QuadraticBezier ( self . end , self . control , self . start ) if self . _length_info [ 'length' ] : new_quad . _length_info = self . _length_info new_quad . _length_info [ 'bpoints' ] = ( self . end , self . control , self . start ) return new_quad | returns a copy of the QuadraticBezier object with its orientation reversed . |
11,145 | def point ( self , t ) : return self . start + t * ( 3 * ( self . control1 - self . start ) + t * ( 3 * ( self . start + self . control2 ) - 6 * self . control1 + t * ( - self . start + 3 * ( self . control1 - self . control2 ) + self . end ) ) ) | Evaluate the cubic Bezier curve at t using Horner s rule . |
11,146 | def bpoints ( self ) : return self . start , self . control1 , self . control2 , self . end | returns the Bezier control points of the segment . |
11,147 | def reversed ( self ) : new_cub = CubicBezier ( self . end , self . control2 , self . control1 , self . start ) if self . _length_info [ 'length' ] : new_cub . _length_info = self . _length_info new_cub . _length_info [ 'bpoints' ] = ( self . end , self . control2 , self . control1 , self . start ) return new_cub | returns a copy of the CubicBezier object with its orientation reversed . |
11,148 | def length ( self , t0 = 0 , t1 = 1 , error = LENGTH_ERROR , min_depth = LENGTH_MIN_DEPTH ) : assert 0 <= t0 <= 1 and 0 <= t1 <= 1 if _quad_available : return quad ( lambda tau : abs ( self . derivative ( tau ) ) , t0 , t1 , epsabs = error , limit = 1000 ) [ 0 ] else : return segment_length ( self , t0 , t1 , self . point ( t0 ) , self . point ( t1 ) , error , min_depth , 0 ) | The length of an elliptical large_arc segment requires numerical integration and in that case it s simpler to just do a geometric approximation as for cubic bezier curves . |
11,149 | def reversed ( self ) : return Arc ( self . end , self . radius , self . rotation , self . large_arc , not self . sweep , self . start ) | returns a copy of the Arc object with its orientation reversed . |
11,150 | def reversed ( self ) : newpath = [ seg . reversed ( ) for seg in self ] newpath . reverse ( ) return Path ( * newpath ) | returns a copy of the Path object with its orientation reversed . |
11,151 | def iscontinuous ( self ) : return all ( self [ i ] . end == self [ i + 1 ] . start for i in range ( len ( self ) - 1 ) ) | Checks if a path is continuous with respect to its parameterization . |
11,152 | def isclosed ( self ) : assert len ( self ) != 0 assert self . iscontinuous ( ) return self . start == self . end | This function determines if a connected path is closed . |
11,153 | def d ( self , useSandT = False , use_closed_attrib = False ) : if use_closed_attrib : self_closed = self . closed ( warning_on = False ) if self_closed : segments = self [ : - 1 ] else : segments = self [ : ] else : self_closed = False segments = self [ : ] current_pos = None parts = [ ] previous_segment = None end = self [ - 1 ] . end for segment in segments : seg_start = segment . start if current_pos != seg_start or ( self_closed and seg_start == end and use_closed_attrib ) : parts . append ( 'M {},{}' . format ( seg_start . real , seg_start . imag ) ) if isinstance ( segment , Line ) : args = segment . end . real , segment . end . imag parts . append ( 'L {},{}' . format ( * args ) ) elif isinstance ( segment , CubicBezier ) : if useSandT and segment . is_smooth_from ( previous_segment , warning_on = False ) : args = ( segment . control2 . real , segment . control2 . imag , segment . end . real , segment . end . imag ) parts . append ( 'S {},{} {},{}' . format ( * args ) ) else : args = ( segment . control1 . real , segment . control1 . imag , segment . control2 . real , segment . control2 . imag , segment . end . real , segment . end . imag ) parts . append ( 'C {},{} {},{} {},{}' . format ( * args ) ) elif isinstance ( segment , QuadraticBezier ) : if useSandT and segment . is_smooth_from ( previous_segment , warning_on = False ) : args = segment . end . real , segment . end . imag parts . append ( 'T {},{}' . format ( * args ) ) else : args = ( segment . control . real , segment . control . imag , segment . end . real , segment . end . imag ) parts . append ( 'Q {},{} {},{}' . format ( * args ) ) elif isinstance ( segment , Arc ) : args = ( segment . radius . real , segment . radius . imag , segment . rotation , int ( segment . large_arc ) , int ( segment . sweep ) , segment . end . real , segment . end . imag ) parts . append ( 'A {},{} {} {:d},{:d} {},{}' . format ( * args ) ) current_pos = segment . end previous_segment = segment if self_closed : parts . append ( 'Z' ) return ' ' . join ( parts ) | Returns a path d - string for the path object . For an explanation of useSandT and use_closed_attrib see the compatibility notes in the README . |
11,154 | def cropped ( self , T0 , T1 ) : assert 0 <= T0 <= 1 and 0 <= T1 <= 1 assert T0 != T1 assert not ( T0 == 1 and T1 == 0 ) if T0 == 1 and 0 < T1 < 1 and self . isclosed ( ) : return self . cropped ( 0 , T1 ) if T1 == 1 : seg1 = self [ - 1 ] t_seg1 = 1 i1 = len ( self ) - 1 else : seg1_idx , t_seg1 = self . T2t ( T1 ) seg1 = self [ seg1_idx ] if np . isclose ( t_seg1 , 0 ) : i1 = ( self . index ( seg1 ) - 1 ) % len ( self ) seg1 = self [ i1 ] t_seg1 = 1 else : i1 = self . index ( seg1 ) if T0 == 0 : seg0 = self [ 0 ] t_seg0 = 0 i0 = 0 else : seg0_idx , t_seg0 = self . T2t ( T0 ) seg0 = self [ seg0_idx ] if np . isclose ( t_seg0 , 1 ) : i0 = ( self . index ( seg0 ) + 1 ) % len ( self ) seg0 = self [ i0 ] t_seg0 = 0 else : i0 = self . index ( seg0 ) if T0 < T1 and i0 == i1 : new_path = Path ( seg0 . cropped ( t_seg0 , t_seg1 ) ) else : new_path = Path ( seg0 . cropped ( t_seg0 , 1 ) ) if T1 < T0 : if not self . isclosed ( ) : raise ValueError ( "This path is not closed, thus T0 must " "be less than T1." ) else : for i in range ( i0 + 1 , len ( self ) ) : new_path . append ( self [ i ] ) for i in range ( 0 , i1 ) : new_path . append ( self [ i ] ) else : for i in range ( i0 + 1 , i1 ) : new_path . append ( self [ i ] ) if t_seg1 != 0 : new_path . append ( seg1 . cropped ( 0 , t_seg1 ) ) return new_path | returns a cropped copy of the path . |
11,155 | def split_bezier ( bpoints , t ) : def split_bezier_recursion ( bpoints_left_ , bpoints_right_ , bpoints_ , t_ ) : if len ( bpoints_ ) == 1 : bpoints_left_ . append ( bpoints_ [ 0 ] ) bpoints_right_ . append ( bpoints_ [ 0 ] ) else : new_points = [ None ] * ( len ( bpoints_ ) - 1 ) bpoints_left_ . append ( bpoints_ [ 0 ] ) bpoints_right_ . append ( bpoints_ [ - 1 ] ) for i in range ( len ( bpoints_ ) - 1 ) : new_points [ i ] = ( 1 - t_ ) * bpoints_ [ i ] + t_ * bpoints_ [ i + 1 ] bpoints_left_ , bpoints_right_ = split_bezier_recursion ( bpoints_left_ , bpoints_right_ , new_points , t_ ) return bpoints_left_ , bpoints_right_ bpoints_left = [ ] bpoints_right = [ ] bpoints_left , bpoints_right = split_bezier_recursion ( bpoints_left , bpoints_right , bpoints , t ) bpoints_right . reverse ( ) return bpoints_left , bpoints_right | Uses deCasteljau s recursion to split the Bezier curve at t into two Bezier curves of the same order . |
11,156 | def bezier_real_minmax ( p ) : local_extremizers = [ 0 , 1 ] if len ( p ) == 4 : a = [ p . real for p in p ] denom = a [ 0 ] - 3 * a [ 1 ] + 3 * a [ 2 ] - a [ 3 ] if denom != 0 : delta = a [ 1 ] ** 2 - ( a [ 0 ] + a [ 1 ] ) * a [ 2 ] + a [ 2 ] ** 2 + ( a [ 0 ] - a [ 1 ] ) * a [ 3 ] if delta >= 0 : sqdelta = sqrt ( delta ) tau = a [ 0 ] - 2 * a [ 1 ] + a [ 2 ] r1 = ( tau + sqdelta ) / denom r2 = ( tau - sqdelta ) / denom if 0 < r1 < 1 : local_extremizers . append ( r1 ) if 0 < r2 < 1 : local_extremizers . append ( r2 ) local_extrema = [ bezier_point ( a , t ) for t in local_extremizers ] return min ( local_extrema ) , max ( local_extrema ) dcoeffs = bezier2polynomial ( a , return_poly1d = True ) . deriv ( ) . coeffs local_extremizers += polyroots01 ( dcoeffs ) local_extrema = [ bezier_point ( a , t ) for t in local_extremizers ] return min ( local_extrema ) , max ( local_extrema ) | returns the minimum and maximum for any real cubic bezier |
11,157 | def flatten_group ( group_to_flatten , root , recursive = True , group_filter = lambda x : True , path_filter = lambda x : True , path_conversions = CONVERSIONS , group_search_xpath = SVG_GROUP_TAG ) : if not any ( group_to_flatten is descendant for descendant in root . iter ( ) ) : warnings . warn ( 'The requested group_to_flatten is not a ' 'descendant of root' ) return [ ] desired_groups = set ( ) if recursive : for group in group_to_flatten . iter ( ) : desired_groups . add ( id ( group ) ) else : desired_groups . add ( id ( group_to_flatten ) ) def desired_group_filter ( x ) : return ( id ( x ) in desired_groups ) and group_filter ( x ) return flatten_all_paths ( root , desired_group_filter , path_filter , path_conversions , group_search_xpath ) | Flatten all the paths in a specific group . |
11,158 | def flatten_all_paths ( self , group_filter = lambda x : True , path_filter = lambda x : True , path_conversions = CONVERSIONS ) : return flatten_all_paths ( self . tree . getroot ( ) , group_filter , path_filter , path_conversions ) | Forward the tree of this document into the more general flatten_all_paths function and return the result . |
11,159 | def add_path ( self , path , attribs = None , group = None ) : if group is None : group = self . tree . getroot ( ) elif all ( isinstance ( elem , str ) for elem in group ) : group = self . get_or_add_group ( group ) elif not isinstance ( group , Element ) : raise TypeError ( 'Must provide a list of strings or an xml.etree.Element ' 'object. Instead you provided {0}' . format ( group ) ) else : if not self . contains_group ( group ) : warnings . warn ( 'The requested group does not belong to ' 'this Document' ) if isinstance ( path , Path ) : path_svg = path . d ( ) elif is_path_segment ( path ) : path_svg = Path ( path ) . d ( ) elif isinstance ( path , str ) : path_svg = path else : raise TypeError ( 'Must provide a Path, a path segment type, or a valid ' 'SVG path d-string. Instead you provided {0}' . format ( path ) ) if attribs is None : attribs = { } else : attribs = attribs . copy ( ) attribs [ 'd' ] = path_svg return SubElement ( group , 'path' , attribs ) | Add a new path to the SVG . |
11,160 | def get_or_add_group ( self , nested_names , name_attr = 'id' ) : group = self . tree . getroot ( ) while len ( nested_names ) : prev_group = group next_name = nested_names . pop ( 0 ) for elem in group . iterfind ( SVG_GROUP_TAG , SVG_NAMESPACE ) : if elem . get ( name_attr ) == next_name : group = elem break if prev_group is group : nested_names . insert ( 0 , next_name ) while nested_names : next_name = nested_names . pop ( 0 ) group = self . add_group ( { 'id' : next_name } , group ) return group | Get a group from the tree or add a new one with the given name structure . |
11,161 | def add_group ( self , group_attribs = None , parent = None ) : if parent is None : parent = self . tree . getroot ( ) elif not self . contains_group ( parent ) : warnings . warn ( 'The requested group {0} does not belong to ' 'this Document' . format ( parent ) ) if group_attribs is None : group_attribs = { } else : group_attribs = group_attribs . copy ( ) return SubElement ( parent , '{{{0}}}g' . format ( SVG_NAMESPACE [ 'svg' ] ) , group_attribs ) | Add an empty group element to the SVG . |
11,162 | def parse_transform ( transform_str ) : if not transform_str : return np . identity ( 3 ) elif not isinstance ( transform_str , str ) : raise TypeError ( 'Must provide a string to parse' ) total_transform = np . identity ( 3 ) transform_substrs = transform_str . split ( ')' ) [ : - 1 ] for substr in transform_substrs : total_transform = total_transform . dot ( _parse_transform_substr ( substr ) ) return total_transform | Converts a valid SVG transformation string into a 3x3 matrix . If the string is empty or null this returns a 3x3 identity matrix |
11,163 | def kinks ( path , tol = 1e-8 ) : kink_list = [ ] for idx in range ( len ( path ) ) : if idx == 0 and not path . isclosed ( ) : continue try : u = path [ ( idx - 1 ) % len ( path ) ] . unit_tangent ( 1 ) v = path [ idx ] . unit_tangent ( 0 ) u_dot_v = u . real * v . real + u . imag * v . imag flag = False except ValueError : flag = True if flag or abs ( u_dot_v - 1 ) > tol : kink_list . append ( idx ) return kink_list | returns indices of segments that start on a non - differentiable joint . |
11,164 | def smoothed_path ( path , maxjointsize = 3 , tightness = 1.99 , ignore_unfixable_kinks = False ) : if len ( path ) == 1 : return path assert path . iscontinuous ( ) sharp_kinks = [ ] new_path = [ path [ 0 ] ] for idx in range ( len ( path ) ) : if idx == len ( path ) - 1 : if not path . isclosed ( ) : continue else : seg1 = new_path [ 0 ] else : seg1 = path [ idx + 1 ] seg0 = new_path [ - 1 ] try : unit_tangent0 = seg0 . unit_tangent ( 1 ) unit_tangent1 = seg1 . unit_tangent ( 0 ) flag = False except ValueError : flag = True if not flag and isclose ( unit_tangent0 , unit_tangent1 ) : if idx != len ( path ) - 1 : new_path . append ( seg1 ) continue else : kink_idx = ( idx + 1 ) % len ( path ) if not flag and isclose ( - unit_tangent0 , unit_tangent1 ) : new_path . append ( seg1 ) sharp_kinks . append ( kink_idx ) else : args = ( seg0 , seg1 , maxjointsize , tightness ) new_seg0 , elbow_segs , new_seg1 = smoothed_joint ( * args ) new_path [ - 1 ] = new_seg0 new_path += elbow_segs if idx == len ( path ) - 1 : new_path [ 0 ] = new_seg1 else : new_path . append ( new_seg1 ) if sharp_kinks and not ignore_unfixable_kinks : _report_unfixable_kinks ( path , sharp_kinks ) return Path ( * new_path ) | returns a path with no non - differentiable joints . |
11,165 | def hex2rgb ( value ) : value = value . lstrip ( '#' ) lv = len ( value ) return tuple ( int ( value [ i : i + lv // 3 ] , 16 ) for i in range ( 0 , lv , lv // 3 ) ) | Converts a hexadeximal color string to an RGB 3 - tuple |
11,166 | def isclose ( a , b , rtol = 1e-5 , atol = 1e-8 ) : return abs ( a - b ) < ( atol + rtol * abs ( b ) ) | This is essentially np . isclose but slightly faster . |
11,167 | def open_in_browser ( file_location ) : if not os . path . isfile ( file_location ) : file_location = os . path . join ( os . getcwd ( ) , file_location ) if not os . path . isfile ( file_location ) : raise IOError ( "\n\nFile not found." ) if sys . platform == "darwin" : file_location = "file:///" + file_location new = 2 webbrowser . get ( ) . open ( file_location , new = new ) | Attempt to open file located at file_location in the default web browser . |
11,168 | def ellipse2pathd ( ellipse ) : cx = ellipse . get ( 'cx' , 0 ) cy = ellipse . get ( 'cy' , 0 ) rx = ellipse . get ( 'rx' , None ) ry = ellipse . get ( 'ry' , None ) r = ellipse . get ( 'r' , None ) if r is not None : rx = ry = float ( r ) else : rx = float ( rx ) ry = float ( ry ) cx = float ( cx ) cy = float ( cy ) d = '' d += 'M' + str ( cx - rx ) + ',' + str ( cy ) d += 'a' + str ( rx ) + ',' + str ( ry ) + ' 0 1,0 ' + str ( 2 * rx ) + ',0' d += 'a' + str ( rx ) + ',' + str ( ry ) + ' 0 1,0 ' + str ( - 2 * rx ) + ',0' return d | converts the parameters from an ellipse or a circle to a string for a Path object d - attribute |
11,169 | def polyline2pathd ( polyline_d , is_polygon = False ) : points = COORD_PAIR_TMPLT . findall ( polyline_d ) closed = ( float ( points [ 0 ] [ 0 ] ) == float ( points [ - 1 ] [ 0 ] ) and float ( points [ 0 ] [ 1 ] ) == float ( points [ - 1 ] [ 1 ] ) ) if is_polygon and closed : points . append ( points [ 0 ] ) d = 'M' + 'L' . join ( '{0} {1}' . format ( x , y ) for x , y in points ) if is_polygon or closed : d += 'z' return d | converts the string from a polyline points - attribute to a string for a Path object d - attribute |
11,170 | def svg2paths ( svg_file_location , return_svg_attributes = False , convert_circles_to_paths = True , convert_ellipses_to_paths = True , convert_lines_to_paths = True , convert_polylines_to_paths = True , convert_polygons_to_paths = True , convert_rectangles_to_paths = True ) : if os_path . dirname ( svg_file_location ) == '' : svg_file_location = os_path . join ( getcwd ( ) , svg_file_location ) doc = parse ( svg_file_location ) def dom2dict ( element ) : keys = list ( element . attributes . keys ( ) ) values = [ val . value for val in list ( element . attributes . values ( ) ) ] return dict ( list ( zip ( keys , values ) ) ) paths = [ dom2dict ( el ) for el in doc . getElementsByTagName ( 'path' ) ] d_strings = [ el [ 'd' ] for el in paths ] attribute_dictionary_list = paths if convert_polylines_to_paths : plins = [ dom2dict ( el ) for el in doc . getElementsByTagName ( 'polyline' ) ] d_strings += [ polyline2pathd ( pl [ 'points' ] ) for pl in plins ] attribute_dictionary_list += plins if convert_polygons_to_paths : pgons = [ dom2dict ( el ) for el in doc . getElementsByTagName ( 'polygon' ) ] d_strings += [ polygon2pathd ( pg [ 'points' ] ) for pg in pgons ] attribute_dictionary_list += pgons if convert_lines_to_paths : lines = [ dom2dict ( el ) for el in doc . getElementsByTagName ( 'line' ) ] d_strings += [ ( 'M' + l [ 'x1' ] + ' ' + l [ 'y1' ] + 'L' + l [ 'x2' ] + ' ' + l [ 'y2' ] ) for l in lines ] attribute_dictionary_list += lines if convert_ellipses_to_paths : ellipses = [ dom2dict ( el ) for el in doc . getElementsByTagName ( 'ellipse' ) ] d_strings += [ ellipse2pathd ( e ) for e in ellipses ] attribute_dictionary_list += ellipses if convert_circles_to_paths : circles = [ dom2dict ( el ) for el in doc . getElementsByTagName ( 'circle' ) ] d_strings += [ ellipse2pathd ( c ) for c in circles ] attribute_dictionary_list += circles if convert_rectangles_to_paths : rectangles = [ dom2dict ( el ) for el in doc . getElementsByTagName ( 'rect' ) ] d_strings += [ rect2pathd ( r ) for r in rectangles ] attribute_dictionary_list += rectangles if return_svg_attributes : svg_attributes = dom2dict ( doc . getElementsByTagName ( 'svg' ) [ 0 ] ) doc . unlink ( ) path_list = [ parse_path ( d ) for d in d_strings ] return path_list , attribute_dictionary_list , svg_attributes else : doc . unlink ( ) path_list = [ parse_path ( d ) for d in d_strings ] return path_list , attribute_dictionary_list | Converts an SVG into a list of Path objects and attribute dictionaries . |
11,171 | def dtype_to_matlab_class ( dtype ) : if dtype . str in [ '<f8' ] : return 'double' elif dtype . str in [ '<f4' ] : return 'single' elif dtype . str in [ '<i8' ] : return 'int64' elif dtype . str in [ '<u8' ] : return 'uint64' elif dtype . str in [ '<i4' ] : return 'int32' elif dtype . str in [ '<u4' ] : return 'uint32' elif dtype . str in [ '<i2' ] : return 'int16' elif dtype . str in [ '<u2' ] : return 'uint16' elif dtype . str in [ '|i1' ] : return 'int8' elif dtype . str in [ '|u1' ] : return 'uint8' | convert dtype to matlab class string |
11,172 | def connect ( self ) : if not driver_ok : logger . error ( "Visa driver NOT ok" ) return False visa_backend = '@py' if hasattr ( settings , 'VISA_BACKEND' ) : visa_backend = settings . VISA_BACKEND try : self . rm = visa . ResourceManager ( visa_backend ) except : logger . error ( "Visa ResourceManager cannot load resources : %s" % self ) return False try : resource_prefix = self . _device . visadevice . resource_name . split ( '::' ) [ 0 ] extras = { } if hasattr ( settings , 'VISA_DEVICE_SETTINGS' ) : if resource_prefix in settings . VISA_DEVICE_SETTINGS : extras = settings . VISA_DEVICE_SETTINGS [ resource_prefix ] logger . debug ( 'VISA_DEVICE_SETTINGS for %s: %r' % ( resource_prefix , extras ) ) self . inst = self . rm . open_resource ( self . _device . visadevice . resource_name , ** extras ) except : logger . error ( "Visa ResourceManager cannot open resource : %s" % self . _device . visadevice . resource_name ) return False logger . debug ( 'connected visa device' ) return True | establish a connection to the Instrument |
11,173 | def decode_bcd ( values ) : bin_str_out = '' if isinstance ( values , integer_types ) : bin_str_out = bin ( values ) [ 2 : ] . zfill ( 16 ) bin_str_out = bin_str_out [ : : - 1 ] else : for value in values : bin_str = bin ( value ) [ 2 : ] . zfill ( 16 ) bin_str = bin_str [ : : - 1 ] bin_str_out = bin_str + bin_str_out dec_num = 0 for i in range ( len ( bin_str_out ) / 4 ) : bcd_num = int ( bin_str_out [ ( i * 4 ) : ( i + 1 ) * 4 ] [ : : - 1 ] , 2 ) if bcd_num > 9 : dec_num = - dec_num else : dec_num = dec_num + ( bcd_num * pow ( 10 , i ) ) return dec_num | decode bcd as int to dec |
11,174 | def find_gap ( l , value ) : for index in range ( len ( l ) ) : if l [ index ] == value : return None if l [ index ] > value : return index | try to find a address gap in the list of modbus registers |
11,175 | def write_data ( self , variable_id , value , task ) : if variable_id not in self . variables : return False if not self . variables [ variable_id ] . writeable : return False if self . variables [ variable_id ] . modbusvariable . function_code_read == 3 : if 0 <= self . variables [ variable_id ] . modbusvariable . address <= 65535 : if self . _connect ( ) : if self . variables [ variable_id ] . get_bits_by_class ( ) / 16 == 1 : self . slave . write_register ( self . variables [ variable_id ] . modbusvariable . address , int ( value ) , unit = self . _unit_id ) else : self . slave . write_registers ( self . variables [ variable_id ] . modbusvariable . address , list ( self . variables [ variable_id ] . encode_value ( value ) ) , unit = self . _unit_id ) self . _disconnect ( ) return True else : logger . info ( "device with id: %d is now accessible" % self . device . pk ) return False else : logger . error ( 'Modbus Address %d out of range' % self . variables [ variable_id ] . modbusvariable . address ) return False elif self . variables [ variable_id ] . modbusvariable . function_code_read == 1 : if 0 <= self . variables [ variable_id ] . modbusvariable . address <= 65535 : if self . _connect ( ) : self . slave . write_coil ( self . variables [ variable_id ] . modbusvariable . address , bool ( value ) , unit = self . _unit_id ) self . _disconnect ( ) return True else : logger . info ( "device with id: %d is now accessible" % self . device . pk ) return False else : logger . error ( 'Modbus Address %d out of range' % self . variables [ variable_id ] . modbusvariable . address ) else : logger . error ( 'wrong type of function code %d' % self . variables [ variable_id ] . modbusvariable . function_code_read ) return False | write value to single modbus register or coil |
11,176 | def demonize ( self ) : if access ( self . pid_file_name , F_OK ) : pid = self . read_pid ( ) try : kill ( pid , 0 ) self . stderr . write ( "process is already running\n" ) return False except OSError as e : if e . errno == errno . ESRCH : self . delete_pid ( force_del = True ) else : self . stderr . write ( "demonize failed, something went wrong: %d (%s)\n" % ( e . errno , e . strerror ) ) return False try : pid = fork ( ) if pid > 0 : timeout = time ( ) + 60 while self . read_pid ( ) is None : self . stderr . write ( "waiting for pid..\n" ) sleep ( 0.5 ) if time ( ) > timeout : break self . stderr . write ( "pid is %d\n" % self . read_pid ( ) ) sys . exit ( 0 ) except OSError as e : self . stderr . write ( "demonize failed in 1. Fork: %d (%s)\n" % ( e . errno , e . strerror ) ) sys . exit ( 1 ) setsid ( ) umask ( 0 ) try : pid = fork ( ) if pid > 0 : sys . exit ( 0 ) except OSError as e : self . stderr . write ( "demonize failed in 2. Fork: %d (%s)\n" % ( e . errno , e . strerror ) ) sys . exit ( 1 ) self . write_pid ( ) return True | do the double fork magic |
11,177 | def delete_pid ( self , force_del = False ) : pid = self . read_pid ( ) if pid != getpid ( ) or force_del : logger . debug ( 'process %d tried to delete pid' % getpid ( ) ) return False if access ( self . pid_file_name , F_OK ) : try : remove ( self . pid_file_name ) logger . debug ( 'delete pid (%d)' % getpid ( ) ) except : logger . debug ( "can't delete pid file" ) | delete the pid file |
11,178 | def start ( self ) : if self . run_as_daemon : if not self . demonize ( ) : self . delete_pid ( ) sys . exit ( 0 ) if connection . connection is not None : connection . connection . close ( ) connection . connection = None master_process = BackgroundProcess . objects . filter ( parent_process__isnull = True , label = self . label , enabled = True ) . first ( ) self . pid = getpid ( ) if not master_process : self . delete_pid ( force_del = True ) logger . debug ( 'no such process in BackgroundProcesses\n' ) sys . exit ( 0 ) self . process_id = master_process . pk master_process . pid = self . pid master_process . last_update = now ( ) master_process . running_since = now ( ) master_process . done = False master_process . failed = False master_process . message = 'init master process' master_process . save ( ) BackgroundProcess . objects . filter ( parent_process__pk = self . process_id , done = False ) . update ( message = 'stopped' ) for parent_process in BackgroundProcess . objects . filter ( parent_process__pk = self . process_id , done = False ) : for process in BackgroundProcess . objects . filter ( parent_process__pk = parent_process . pk , done = False ) : try : kill ( process . pid , 0 ) except OSError as e : if e . errno == errno . ESRCH : process . delete ( ) continue logger . debug ( 'process %d is alive' % process . pk ) process . stop ( ) BackgroundProcess . objects . filter ( parent_process__pk = parent_process . pk , done = False ) . delete ( ) [ signal . signal ( s , self . signal ) for s in self . SIGNALS ] self . run ( ) self . delete_pid ( ) sys . exit ( 0 ) | start the scheduler |
11,179 | def run ( self ) : try : master_process = BackgroundProcess . objects . filter ( pk = self . process_id ) . first ( ) if master_process : master_process . last_update = now ( ) master_process . message = 'init child processes' master_process . save ( ) else : self . delete_pid ( force_del = True ) self . stderr . write ( "no such process in BackgroundProcesses" ) sys . exit ( 0 ) self . manage_processes ( ) while True : sig = self . SIG_QUEUE . pop ( 0 ) if len ( self . SIG_QUEUE ) else None check_db_connection ( ) BackgroundProcess . objects . filter ( pk = self . process_id ) . update ( last_update = now ( ) , message = 'running..' ) if sig is None : self . manage_processes ( ) elif sig not in self . SIGNALS : logger . error ( '%s, unhandled signal %d' % ( self . label , sig ) ) continue elif sig == signal . SIGTERM : logger . debug ( '%s, termination signal' % self . label ) raise StopIteration elif sig == signal . SIGHUP : pass elif sig == signal . SIGUSR1 : logger . debug ( 'PID %d, processed SIGUSR1 (%d) signal' % ( self . pid , sig ) ) self . restart ( ) elif sig == signal . SIGUSR2 : self . status ( ) pass sleep ( 5 ) except StopIteration : self . stop ( ) self . delete_pid ( ) sys . exit ( 0 ) except SystemExit : raise except : logger . error ( '%s(%d), unhandled exception\n%s' % ( self . label , getpid ( ) , traceback . format_exc ( ) ) ) | the main loop |
11,180 | def restart ( self ) : BackgroundProcess . objects . filter ( pk = self . process_id ) . update ( last_update = now ( ) , message = 'restarting..' ) timeout = time ( ) + 60 self . kill_processes ( signal . SIGTERM ) while self . PROCESSES and time ( ) < timeout : sleep ( 0.1 ) self . kill_processes ( signal . SIGKILL ) self . manage_processes ( ) logger . debug ( 'BD %d: restarted' % self . process_id ) | restart all child processes |
11,181 | def stop ( self , sig = signal . SIGTERM ) : if self . pid is None : self . pid = self . read_pid ( ) if self . pid is None : sp = BackgroundProcess . objects . filter ( pk = 1 ) . first ( ) if sp : self . pid = sp . pid if self . pid is None or self . pid == 0 : logger . error ( "can't determine process id exiting." ) return False if self . pid != getpid ( ) : logger . debug ( 'send sigterm to daemon' ) try : kill ( self . pid , sig ) return True except OSError as e : if e . errno == errno . ESRCH : return False else : return False logger . debug ( 'start termination of the daemon' ) BackgroundProcess . objects . filter ( pk = self . process_id ) . update ( last_update = now ( ) , message = 'stopping..' ) timeout = time ( ) + 60 self . kill_processes ( signal . SIGTERM ) while self . PROCESSES and time ( ) < timeout : self . kill_processes ( signal . SIGTERM ) sleep ( 1 ) self . kill_processes ( signal . SIGKILL ) BackgroundProcess . objects . filter ( pk = self . process_id ) . update ( last_update = now ( ) , message = 'stopped' ) logger . debug ( 'termination of the daemon done' ) return True | stop the scheduler and stop all processes |
11,182 | def spawn_process ( self , process = None ) : if process is None : return False pid = fork ( ) if pid != 0 : process . pid = pid self . PROCESSES [ process . process_id ] = process connections . close_all ( ) return True process . pid = getpid ( ) process . pre_init_process ( ) process . init_process ( ) process . run ( ) sys . exit ( 0 ) | spawn a new process |
11,183 | def status ( self ) : if self . pid is None : self . pid = self . read_pid ( ) if self . pid is None : sp = BackgroundProcess . objects . filter ( pk = 1 ) . first ( ) if sp : self . pid = sp . pid if self . pid is None or self . pid == 0 : self . stderr . write ( "%s: can't determine process id exiting.\n" % datetime . now ( ) . isoformat ( ' ' ) ) return False if self . pid != getpid ( ) : try : kill ( self . pid , signal . SIGUSR2 ) return True except OSError as e : if e . errno == errno . ESRCH : return False else : return False process_list = [ ] for process in BackgroundProcess . objects . filter ( parent_process__pk = self . process_id ) : process_list . append ( process ) process_list += list ( process . backgroundprocess_set . filter ( ) ) for process in process_list : logger . debug ( '%s, parrent process_id %d' % ( self . label , process . parent_process . pk ) ) logger . debug ( '%s, process_id %d' % ( self . label , self . process_id ) ) | write the current daemon status to stdout |
11,184 | def pre_init_process ( self ) : db . connections . close_all ( ) BackgroundProcess . objects . filter ( pk = self . process_id ) . update ( pid = self . pid , last_update = now ( ) , running_since = now ( ) , done = False , failed = False , message = 'init process..' , ) [ signal . signal ( s , signal . SIG_DFL ) for s in self . SIGNALS ] [ signal . signal ( s , self . signal ) for s in self . SIGNALS ] | will be executed after process fork |
11,185 | def stop ( self , signum = None , frame = None ) : BackgroundProcess . objects . filter ( pk = self . process_id ) . update ( pid = 0 , last_update = now ( ) , message = 'stopping..' ) self . cleanup ( ) BackgroundProcess . objects . filter ( pk = self . process_id ) . update ( pid = 0 , last_update = now ( ) , message = 'stopped' ) | handel s a termination signal |
11,186 | def init_process ( self ) : self . device = Device . objects . filter ( protocol__daq_daemon = 1 , active = 1 , id = self . device_id ) . first ( ) if not self . device : logger . error ( "Error init_process for %s" % self . device_id ) return False self . dt_set = min ( self . dt_set , self . device . polling_interval ) self . dt_query_data = self . device . polling_interval try : self . device = self . device . get_device_instance ( ) except : var = traceback . format_exc ( ) logger . error ( "exception while initialisation of DAQ Process for Device %d %s %s" % ( self . device_id , linesep , var ) ) return True | init a standard daq process for a single device |
11,187 | def init_process ( self ) : for item in Device . objects . filter ( protocol__daq_daemon = 1 , active = 1 , id__in = self . device_ids ) : try : tmp_device = item . get_device_instance ( ) if tmp_device is not None : self . devices [ item . pk ] = tmp_device self . dt_set = min ( self . dt_set , item . polling_interval ) self . dt_query_data = min ( self . dt_query_data , item . polling_interval ) except : var = traceback . format_exc ( ) logger . error ( "exception while initialisation of DAQ Process for Device %d %s %s" % ( item . pk , linesep , var ) ) return True | init a standard daq process for multiple devices |
11,188 | def _delete_widget_content ( sender , instance , ** kwargs ) : if not issubclass ( sender , WidgetContentModel ) : return wcs = WidgetContent . objects . filter ( content_pk = instance . pk , content_model = ( '%s' % instance . __class__ ) . replace ( "<class '" , '' ) . replace ( "'>" , '' ) ) for wc in wcs : logger . debug ( 'delete wc %r' % wc ) wc . delete ( ) | delete the widget content instance when a WidgetContentModel is deleted |
11,189 | def _create_widget_content ( sender , instance , created = False , ** kwargs ) : if not issubclass ( sender , WidgetContentModel ) : return if created : instance . create_widget_content_entry ( ) return | create a widget content instance when a WidgetContentModel is deleted |
11,190 | def _cast_value ( value , _type ) : if _type . upper ( ) == 'FLOAT64' : return float64 ( value ) elif _type . upper ( ) == 'FLOAT32' : return float32 ( value ) elif _type . upper ( ) == 'INT32' : return int32 ( value ) elif _type . upper ( ) == 'UINT16' : return uint16 ( value ) elif _type . upper ( ) == 'INT16' : return int16 ( value ) elif _type . upper ( ) == 'BOOLEAN' : return uint8 ( value ) else : return float64 ( value ) | cast value to _type |
11,191 | def loop ( self ) : for mail in Mail . objects . filter ( done = False , send_fail_count__lt = 3 ) : mail . send_mail ( ) for mail in Mail . objects . filter ( done = True , timestamp__lt = time ( ) - 60 * 60 * 24 * 7 ) : mail . delete ( ) return 1 , None | check for mails and send them |
11,192 | def normalize ( l ) : s = float ( sum ( l ) ) if s == 0 : raise ValueError ( "Cannot normalize list with sum 0" ) return [ x / s for x in l ] | Normalizes input list . |
11,193 | def simplex_iterator ( scale , boundary = True ) : start = 0 if not boundary : start = 1 for i in range ( start , scale + ( 1 - start ) ) : for j in range ( start , scale + ( 1 - start ) - i ) : k = scale - i - j yield ( i , j , k ) | Systematically iterates through a lattice of points on the 2 - simplex . |
11,194 | def permute_point ( p , permutation = None ) : if not permutation : return p return [ p [ int ( permutation [ i ] ) ] for i in range ( len ( p ) ) ] | Permutes the point according to the permutation keyword argument . The default permutation is 012 which does not change the order of the coordinate . To rotate counterclockwise use 120 and to rotate clockwise use 201 . |
11,195 | def project_sequence ( s , permutation = None ) : xs , ys = unzip ( [ project_point ( p , permutation = permutation ) for p in s ] ) return xs , ys | Projects a point or sequence of points using project_point to lists xs ys for plotting with Matplotlib . |
11,196 | def convert_coordinates ( q , conversion , axisorder ) : p = [ ] for k in range ( 3 ) : p . append ( conversion [ axisorder [ k ] ] ( q [ k ] ) ) return tuple ( p ) | Convert a 3 - tuple in data coordinates into to simplex data coordinates for plotting . |
11,197 | def get_conversion ( scale , limits ) : fb = float ( scale ) / float ( limits [ 'b' ] [ 1 ] - limits [ 'b' ] [ 0 ] ) fl = float ( scale ) / float ( limits [ 'l' ] [ 1 ] - limits [ 'l' ] [ 0 ] ) fr = float ( scale ) / float ( limits [ 'r' ] [ 1 ] - limits [ 'r' ] [ 0 ] ) conversion = { "b" : lambda x : ( x - limits [ 'b' ] [ 0 ] ) * fb , "l" : lambda x : ( x - limits [ 'l' ] [ 0 ] ) * fl , "r" : lambda x : ( x - limits [ 'r' ] [ 0 ] ) * fr } return conversion | Get the conversion equations for each axis . |
11,198 | def convert_coordinates_sequence ( qs , scale , limits , axisorder ) : conversion = get_conversion ( scale , limits ) return [ convert_coordinates ( q , conversion , axisorder ) for q in qs ] | Take a sequence of 3 - tuples in data coordinates and convert them to simplex coordinates for plotting . This is needed for custom plots where the scale of the simplex axes is set within limits rather than being defined by the scale parameter . |
11,199 | def resize_drawing_canvas ( ax , scale = 1. ) : ax . set_ylim ( ( - 0.10 * scale , .90 * scale ) ) ax . set_xlim ( ( - 0.05 * scale , 1.05 * scale ) ) | Makes sure the drawing surface is large enough to display projected content . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.