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 ( cell... | 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 . ap... | 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_rul... | 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 un... | 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.... | 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'' ... | 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 rea... | 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_u... | 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_m... | 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" ) ... | 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 ) wi... | 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 = fac... | 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_funct... | 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 ( * [ ... | 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 = cs... | 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 exce... | 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_p... | 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 <=... | 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 . po... | 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 = ... | 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 ) seg... | 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... | 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 ( delt... | 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 gro... | 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.e... | 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_... | 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 : g... | 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 :... | 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 ValueE... | 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 : ... | 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 ... | 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... | 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' +... | 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 ... | 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... | 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 reso... | 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 ... | 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 . add... | 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... | 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 ( ) ) ex... | 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 = s... | 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... | 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 )... | 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." )... | 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 ... | 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 ... | 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... | 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... | 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... | 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... | 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 .... | 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' : retu... | 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... | 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.