idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
3,900
def rebin_scale ( a , scale = 1 ) : newshape = tuple ( ( side * scale ) for side in a . shape ) return rebin ( a , newshape )
Scale an array to a new shape .
39
8
3,901
def rebin ( a , newshape ) : slices = [ slice ( 0 , old , float ( old ) / new ) for old , new in zip ( a . shape , newshape ) ] coordinates = numpy . mgrid [ slices ] # choose the biggest smaller integer index indices = coordinates . astype ( 'i' ) return a [ tuple ( indices ) ]
Rebin an array to a new shape .
77
9
3,902
def fixpix ( data , mask , kind = 'linear' ) : if data . shape != mask . shape : raise ValueError if not numpy . any ( mask ) : return data x = numpy . arange ( 0 , data . shape [ 0 ] ) for row , mrow in zip ( data , mask ) : if numpy . any ( mrow ) : # Interpolate if there's some pixel missing valid = ( mrow == numpy . False_ ) invalid = ( mrow == numpy . True_ ) itp = interp1d ( x [ valid ] , row [ valid ] , kind = kind , copy = False ) row [ invalid ] = itp ( x [ invalid ] ) . astype ( row . dtype ) return data
Interpolate 2D array data in rows
164
9
3,903
def fixpix2 ( data , mask , iterations = 3 , out = None ) : out = out if out is not None else data . copy ( ) # A binary mask, regions are ones binry = mask != 0 # Label regions in the binary mask lblarr , labl = ndimage . label ( binry ) # Structure for dilation is 8-way stct = ndimage . generate_binary_structure ( 2 , 2 ) # Pixels in the background back = lblarr == 0 # For each object for idx in range ( 1 , labl + 1 ) : # Pixels of the object segm = lblarr == idx # Pixels of the object or the background # dilation will only touch these pixels dilmask = numpy . logical_or ( back , segm ) # Dilation 3 times more = ndimage . binary_dilation ( segm , stct , iterations = iterations , mask = dilmask ) # Border pixels # Pixels in the border around the object are # more and (not segm) border = numpy . logical_and ( more , numpy . logical_not ( segm ) ) # Pixels in the border xi , yi = border . nonzero ( ) # Bilinear leastsq calculator calc = FitOne ( xi , yi , out [ xi , yi ] ) # Pixels in the region xi , yi = segm . nonzero ( ) # Value is obtained from the fit out [ segm ] = calc ( xi , yi ) return out
Substitute pixels in mask by a bilinear least square fitting .
336
15
3,904
def numberarray ( x , shape ) : try : iter ( x ) except TypeError : return numpy . ones ( shape ) * x else : return x
Return x if it is an array or create an array and fill it with x .
33
17
3,905
def get_token ( request ) : if ( not request . META . get ( header_name_to_django ( auth_token_settings . HEADER_NAME ) ) and config . CHAMBER_MULTIDOMAINS_OVERTAKER_AUTH_COOKIE_NAME ) : ovetaker_auth_token = request . COOKIES . get ( config . CHAMBER_MULTIDOMAINS_OVERTAKER_AUTH_COOKIE_NAME ) token = get_object_or_none ( Token , key = ovetaker_auth_token , is_active = True ) if utils . get_user_from_token ( token ) . is_authenticated ( ) : return token return utils . get_token ( request )
Returns the token model instance associated with the given request token key . If no user is retrieved AnonymousToken is returned .
171
23
3,906
def process_request ( self , request ) : request . token = get_token ( request ) request . user = SimpleLazyObject ( lambda : get_user ( request ) ) request . _dont_enforce_csrf_checks = dont_enforce_csrf_checks ( request )
Lazy set user and token
64
6
3,907
def ximplotxy_jupyter ( x , y , fmt = None , * * args ) : using_jupyter = True if fmt is None : return ximplotxy ( x , y , using_jupyter = using_jupyter , * * args ) else : return ximplotxy ( x , y , fmt , using_jupyter = using_jupyter , * * args )
Auxiliary function to call ximplotxy from a jupyter notebook .
97
18
3,908
def atomic ( func ) : try : from reversion . revisions import create_revision return transaction . atomic ( create_revision ( ) ( func ) ) except ImportError : return transaction . atomic ( func )
Decorator helper that overrides django atomic decorator and automatically adds create revision .
44
18
3,909
def atomic_with_signals ( func ) : try : from reversion . revisions import create_revision return transaction . atomic ( create_revision ( ) ( transaction_signals ( func ) ) ) except ImportError : return transaction . atomic ( transaction_signals ( func ) )
Atomic decorator with transaction signals .
61
8
3,910
def parse_from_file ( root_processor , # type: RootProcessor xml_file_path , # type: Text encoding = 'utf-8' # type: Text ) : # type: (...) -> Any with open ( xml_file_path , 'r' , encoding = encoding ) as xml_file : xml_string = xml_file . read ( ) parsed_value = parse_from_string ( root_processor , xml_string ) return parsed_value
Parse the XML file using the processor starting from the root of the document .
102
16
3,911
def parse_from_string ( root_processor , # type: RootProcessor xml_string # type: Text ) : # type: (...) -> Any if not _is_valid_root_processor ( root_processor ) : raise InvalidRootProcessor ( 'Invalid root processor' ) parseable_xml_string = xml_string # type: Union[Text, bytes] if _PY2 and isinstance ( xml_string , Text ) : parseable_xml_string = xml_string . encode ( 'utf-8' ) root = ET . fromstring ( parseable_xml_string ) _xml_namespace_strip ( root ) state = _ProcessorState ( ) state . push_location ( root_processor . element_path ) return root_processor . parse_at_root ( root , state )
Parse the XML string using the processor starting from the root of the document .
176
16
3,912
def serialize_to_file ( root_processor , # type: RootProcessor value , # type: Any xml_file_path , # type: Text encoding = 'utf-8' , # type: Text indent = None # type: Optional[Text] ) : # type: (...) -> None serialized_value = serialize_to_string ( root_processor , value , indent ) with open ( xml_file_path , 'w' , encoding = encoding ) as xml_file : xml_file . write ( serialized_value )
Serialize the value to an XML file using the root processor .
118
13
3,913
def serialize_to_string ( root_processor , # type: RootProcessor value , # type: Any indent = None # type: Optional[Text] ) : # type: (...) -> Text if not _is_valid_root_processor ( root_processor ) : raise InvalidRootProcessor ( 'Invalid root processor' ) state = _ProcessorState ( ) state . push_location ( root_processor . element_path ) root = root_processor . serialize ( value , state ) state . pop_location ( ) # Always encode to UTF-8 because element tree does not support other # encodings in earlier Python versions. See: https://bugs.python.org/issue1767933 serialized_value = ET . tostring ( root , encoding = 'utf-8' ) # Since element tree does not support pretty printing XML, we use minidom to do the pretty # printing if indent : serialized_value = minidom . parseString ( serialized_value ) . toprettyxml ( indent = indent , encoding = 'utf-8' ) return serialized_value . decode ( 'utf-8' )
Serialize the value to an XML string using the root processor .
243
13
3,914
def array ( item_processor , # type: Processor alias = None , # type: Optional[Text] nested = None , # type: Optional[Text] omit_empty = False , # type: bool hooks = None # type: Optional[Hooks] ) : # type: (...) -> RootProcessor processor = _Array ( item_processor , alias , nested , omit_empty ) return _processor_wrap_if_hooks ( processor , hooks )
Create an array processor that can be used to parse and serialize array data .
97
16
3,915
def boolean ( element_name , # type: Text attribute = None , # type: Optional[Text] required = True , # type: bool alias = None , # type: Optional[Text] default = False , # type: Optional[bool] omit_empty = False , # type: bool hooks = None # type: Optional[Hooks] ) : # type: (...) -> Processor return _PrimitiveValue ( element_name , _parse_boolean , attribute , required , alias , default , omit_empty , hooks )
Create a processor for boolean values .
112
7
3,916
def dictionary ( element_name , # type: Text children , # type: List[Processor] required = True , # type: bool alias = None , # type: Optional[Text] hooks = None # type: Optional[Hooks] ) : # type: (...) -> RootProcessor processor = _Dictionary ( element_name , children , required , alias ) return _processor_wrap_if_hooks ( processor , hooks )
Create a processor for dictionary values .
93
7
3,917
def floating_point ( element_name , # type: Text attribute = None , # type: Optional[Text] required = True , # type: bool alias = None , # type: Optional[Text] default = 0.0 , # type: Optional[float] omit_empty = False , # type: bool hooks = None # type: Optional[Hooks] ) : # type: (...) -> Processor value_parser = _number_parser ( float ) return _PrimitiveValue ( element_name , value_parser , attribute , required , alias , default , omit_empty , hooks )
Create a processor for floating point values .
125
8
3,918
def integer ( element_name , # type: Text attribute = None , # type: Optional[Text] required = True , # type: bool alias = None , # type: Optional[Text] default = 0 , # type: Optional[int] omit_empty = False , # type: bool hooks = None # type: Optional[Hooks] ) : # type: (...) -> Processor value_parser = _number_parser ( int ) return _PrimitiveValue ( element_name , value_parser , attribute , required , alias , default , omit_empty , hooks )
Create a processor for integer values .
121
7
3,919
def named_tuple ( element_name , # type: Text tuple_type , # type: Type[Tuple] child_processors , # type: List[Processor] required = True , # type: bool alias = None , # type: Optional[Text] hooks = None # type: Optional[Hooks] ) : # type: (...) -> RootProcessor converter = _named_tuple_converter ( tuple_type ) processor = _Aggregate ( element_name , converter , child_processors , required , alias ) return _processor_wrap_if_hooks ( processor , hooks )
Create a processor for namedtuple values .
132
9
3,920
def string ( element_name , # type: Text attribute = None , # type: Optional[Text] required = True , # type: bool alias = None , # type: Optional[Text] default = '' , # type: Optional[Text] omit_empty = False , # type: bool strip_whitespace = True , # type: bool hooks = None # type: Optional[Hooks] ) : # type: (...) -> Processor value_parser = _string_parser ( strip_whitespace ) return _PrimitiveValue ( element_name , value_parser , attribute , required , alias , default , omit_empty , hooks )
Create a processor for string values .
137
7
3,921
def user_object ( element_name , # type: Text cls , # type: Type[Any] child_processors , # type: List[Processor] required = True , # type: bool alias = None , # type: Optional[Text] hooks = None # type: Optional[Hooks] ) : # type: (...) -> RootProcessor converter = _user_object_converter ( cls ) processor = _Aggregate ( element_name , converter , child_processors , required , alias ) return _processor_wrap_if_hooks ( processor , hooks )
Create a processor for user objects .
127
7
3,922
def _element_append_path ( start_element , # type: ET.Element element_names # type: Iterable[Text] ) : # type: (...) -> ET.Element end_element = start_element for element_name in element_names : new_element = ET . Element ( element_name ) end_element . append ( new_element ) end_element = new_element return end_element
Append the list of element names as a path to the provided start element .
89
16
3,923
def _element_find_from_root ( root , # type: ET.Element element_path # type: Text ) : # type: (...) -> Optional[ET.Element] element = None element_names = element_path . split ( '/' ) if element_names [ 0 ] == root . tag : if len ( element_names ) > 1 : element = root . find ( '/' . join ( element_names [ 1 : ] ) ) else : element = root return element
Find the element specified by the given path starting from the root element of the document .
104
17
3,924
def _element_get_or_add_from_parent ( parent , # type: ET.Element element_path # type: Text ) : # type: (...) -> ET.Element element_names = element_path . split ( '/' ) # Starting from the parent, walk the element path until we find the first element in the path # that does not exist. Create that element and all the elements following it in the path. If # all elements along the path exist, then we will simply walk the full path to the final # element we want to return. existing_element = None previous_element = parent for i , element_name in enumerate ( element_names ) : existing_element = previous_element . find ( element_name ) if existing_element is None : existing_element = _element_append_path ( previous_element , element_names [ i : ] ) break previous_element = existing_element assert existing_element is not None return existing_element
Ensure all elements specified in the given path relative to the provided parent element exist .
206
17
3,925
def _element_path_create_new ( element_path ) : # type: (Text) -> Tuple[ET.Element, ET.Element] element_names = element_path . split ( '/' ) start_element = ET . Element ( element_names [ 0 ] ) end_element = _element_append_path ( start_element , element_names [ 1 : ] ) return start_element , end_element
Create an entirely new element path .
92
7
3,926
def _hooks_apply_after_parse ( hooks , # type: Optional[Hooks] state , # type: _ProcessorState value # type: Any ) : # type: (...) -> Any if hooks and hooks . after_parse : return hooks . after_parse ( ProcessorStateView ( state ) , value ) return value
Apply the after parse hook .
71
6
3,927
def _hooks_apply_before_serialize ( hooks , # type: Optional[Hooks] state , # type: _ProcessorState value # type: Any ) : # type: (...) -> Any if hooks and hooks . before_serialize : return hooks . before_serialize ( ProcessorStateView ( state ) , value ) return value
Apply the before serialize hook .
74
7
3,928
def _named_tuple_converter ( tuple_type ) : # type: (Type[Tuple]) -> _AggregateConverter def _from_dict ( dict_value ) : if dict_value : return tuple_type ( * * dict_value ) # Cannot construct a namedtuple value from an empty dictionary return None def _to_dict ( value ) : if value : return value . _asdict ( ) return { } converter = _AggregateConverter ( from_dict = _from_dict , to_dict = _to_dict ) return converter
Return an _AggregateConverter for named tuples of the given type .
125
17
3,929
def _number_parser ( str_to_number_func ) : def _parse_number_value ( element_text , state ) : value = None try : value = str_to_number_func ( element_text ) except ( ValueError , TypeError ) : state . raise_error ( InvalidPrimitiveValue , 'Invalid numeric value "{}"' . format ( element_text ) ) return value return _parse_number_value
Return a function to parse numbers .
93
7
3,930
def _parse_boolean ( element_text , state ) : value = None lowered_text = element_text . lower ( ) if lowered_text == 'true' : value = True elif lowered_text == 'false' : value = False else : state . raise_error ( InvalidPrimitiveValue , 'Invalid boolean value "{}"' . format ( element_text ) ) return value
Parse the raw XML string as a boolean value .
83
11
3,931
def _string_parser ( strip_whitespace ) : def _parse_string_value ( element_text , _state ) : if element_text is None : value = '' elif strip_whitespace : value = element_text . strip ( ) else : value = element_text return value return _parse_string_value
Return a parser function for parsing string values .
72
9
3,932
def _user_object_converter ( cls ) : # type: (Type[Any]) -> _AggregateConverter def _from_dict ( dict_value ) : try : object_value = cls ( * * dict_value ) except TypeError : # Constructor does not support keyword arguments, try setting each # field individually. object_value = cls ( ) for field_name , field_value in dict_value . items ( ) : setattr ( object_value , field_name , field_value ) return object_value def _to_dict ( value ) : if value : return value . __dict__ return { } return _AggregateConverter ( from_dict = _from_dict , to_dict = _to_dict )
Return an _AggregateConverter for a user object of the given class .
166
17
3,933
def _xml_namespace_strip ( root ) : # type: (ET.Element) -> None if '}' not in root . tag : return # Nothing to do, no namespace present for element in root . iter ( ) : if '}' in element . tag : element . tag = element . tag . split ( '}' ) [ 1 ] else : # pragma: no cover # We should never get here. If there is a namespace, then the namespace should be # included in all elements. pass
Strip the XML namespace prefix from all element tags under the given root Element .
109
16
3,934
def parse_at_element ( self , element , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any parsed_dict = self . _dictionary . parse_at_element ( element , state ) return self . _converter . from_dict ( parsed_dict )
Parse the provided element as an aggregate .
70
9
3,935
def parse_at_root ( self , root , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any parsed_dict = self . _dictionary . parse_at_root ( root , state ) return self . _converter . from_dict ( parsed_dict )
Parse the root XML element as an aggregate .
70
10
3,936
def parse_from_parent ( self , parent , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any parsed_dict = self . _dictionary . parse_from_parent ( parent , state ) return self . _converter . from_dict ( parsed_dict )
Parse the aggregate from the provided parent XML element .
70
11
3,937
def serialize ( self , value , # type: Any state # type: _ProcessorState ) : # type: (...) -> ET.Element dict_value = self . _converter . to_dict ( value ) return self . _dictionary . serialize ( dict_value , state )
Serialize the value to a new element and returns the element .
64
13
3,938
def serialize_on_parent ( self , parent , # type: ET.Element value , # type: Any state # type: _ProcessorState ) : # type: (...) -> None dict_value = self . _converter . to_dict ( value ) self . _dictionary . serialize_on_parent ( parent , dict_value , state )
Serialize the value and adds it to the parent .
79
11
3,939
def parse_at_element ( self , element , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any item_iter = element . findall ( self . _item_processor . element_path ) return self . _parse ( item_iter , state )
Parse the provided element as an array .
66
9
3,940
def parse_at_root ( self , root , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any if not self . _nested : raise InvalidRootProcessor ( 'Non-nested array "{}" cannot be root element' . format ( self . alias ) ) parsed_array = [ ] # type: List array_element = _element_find_from_root ( root , self . _nested ) if array_element is not None : parsed_array = self . parse_at_element ( array_element , state ) elif self . required : raise MissingValue ( 'Missing required array at root: "{}"' . format ( self . _nested ) ) return parsed_array
Parse the root XML element as an array .
160
10
3,941
def parse_from_parent ( self , parent , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any item_iter = parent . findall ( self . _item_path ) return self . _parse ( item_iter , state )
Parse the array data from the provided parent XML element .
62
12
3,942
def serialize ( self , value , # type: Any state # type: _ProcessorState ) : # type: (...) -> ET.Element if self . _nested is None : state . raise_error ( InvalidRootProcessor , 'Cannot directly serialize a non-nested array "{}"' . format ( self . alias ) ) if not value and self . required : state . raise_error ( MissingValue , 'Missing required array: "{}"' . format ( self . alias ) ) start_element , end_element = _element_path_create_new ( self . _nested ) self . _serialize ( end_element , value , state ) return start_element
Serialize the value into a new Element object and return it .
148
13
3,943
def serialize_on_parent ( self , parent , # type: ET.Element value , # type: Any state # type: _ProcessorState ) : # type: (...) -> None if not value and self . required : state . raise_error ( MissingValue , 'Missing required array: "{}"' . format ( self . alias ) ) if not value and self . omit_empty : return # Do nothing if self . _nested is not None : array_parent = _element_get_or_add_from_parent ( parent , self . _nested ) else : # Embedded array has all items serialized directly on the parent. array_parent = parent self . _serialize ( array_parent , value , state )
Serialize the value and append it to the parent element .
158
12
3,944
def _parse ( self , item_iter , # type: Iterable[ET.Element] state # type: _ProcessorState ) : # type: (...) -> List parsed_array = [ ] for i , item in enumerate ( item_iter ) : state . push_location ( self . _item_processor . element_path , i ) parsed_array . append ( self . _item_processor . parse_at_element ( item , state ) ) state . pop_location ( ) if not parsed_array and self . required : state . raise_error ( MissingValue , 'Missing required array "{}"' . format ( self . alias ) ) return parsed_array
Parse the array data using the provided iterator of XML elements .
144
13
3,945
def _serialize ( self , array_parent , # type: ET.Element value , # type: List state # type: _ProcessorState ) : # type: (...) -> None if not value : # Nothing to do. Avoid attempting to iterate over a possibly # None value. return for i , item_value in enumerate ( value ) : state . push_location ( self . _item_processor . element_path , i ) item_element = self . _item_processor . serialize ( item_value , state ) array_parent . append ( item_element ) state . pop_location ( )
Serialize the array value and add it to the array parent element .
131
14
3,946
def parse_at_element ( self , element , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any parsed_dict = { } for child in self . _child_processors : state . push_location ( child . element_path ) parsed_dict [ child . alias ] = child . parse_from_parent ( element , state ) state . pop_location ( ) return parsed_dict
Parse the provided element as a dictionary .
95
9
3,947
def parse_at_root ( self , root , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any parsed_dict = { } # type: Dict dict_element = _element_find_from_root ( root , self . element_path ) if dict_element is not None : parsed_dict = self . parse_at_element ( dict_element , state ) elif self . required : raise MissingValue ( 'Missing required root aggregate "{}"' . format ( self . element_path ) ) return parsed_dict
Parse the root XML element as a dictionary .
124
10
3,948
def serialize ( self , value , # type: Any state # type: _ProcessorState ) : # type: (...) -> ET.Element if not value and self . required : state . raise_error ( MissingValue , 'Missing required aggregate "{}"' . format ( self . element_path ) ) start_element , end_element = _element_path_create_new ( self . element_path ) self . _serialize ( end_element , value , state ) return start_element
Serialize the value to a new element and return the element .
106
13
3,949
def _serialize ( self , element , # type: ET.Element value , # type: Dict state # type: _ProcessorState ) : # type: (...) -> None for child in self . _child_processors : state . push_location ( child . element_path ) child_value = value . get ( child . alias ) child . serialize_on_parent ( element , child_value , state ) state . pop_location ( )
Serialize the dictionary and append all serialized children to the element .
98
14
3,950
def parse_at_element ( self , element , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any xml_value = self . _processor . parse_at_element ( element , state ) return _hooks_apply_after_parse ( self . _hooks , state , xml_value )
Parse the given element .
76
6
3,951
def parse_at_root ( self , root , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any xml_value = self . _processor . parse_at_root ( root , state ) return _hooks_apply_after_parse ( self . _hooks , state , xml_value )
Parse the given element as the root of the document .
76
12
3,952
def parse_from_parent ( self , parent , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any xml_value = self . _processor . parse_from_parent ( parent , state ) return _hooks_apply_after_parse ( self . _hooks , state , xml_value )
Parse the element from the given parent element .
76
10
3,953
def serialize ( self , value , # type: Any state # type: _ProcessorState ) : # type: (...) -> ET.Element xml_value = _hooks_apply_before_serialize ( self . _hooks , state , value ) return self . _processor . serialize ( xml_value , state )
Serialize the value and returns it .
71
8
3,954
def serialize_on_parent ( self , parent , # type: ET.Element value , # type: Any state # type: _ProcessorState ) : # type: (...) -> None xml_value = _hooks_apply_before_serialize ( self . _hooks , state , value ) self . _processor . serialize_on_parent ( parent , xml_value , state )
Serialize the value directory on the parent .
86
9
3,955
def parse_at_element ( self , element , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any if self . _attribute : parsed_value = self . _parse_attribute ( element , self . _attribute , state ) else : parsed_value = self . _parser_func ( element . text , state ) return _hooks_apply_after_parse ( self . _hooks , state , parsed_value )
Parse the primitive value at the XML element .
102
10
3,956
def parse_from_parent ( self , parent , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any element = parent . find ( self . element_path ) if element is None and self . required : state . raise_error ( MissingValue , 'Missing required element "{}"' . format ( self . element_path ) ) elif element is not None : return self . parse_at_element ( element , state ) return _hooks_apply_after_parse ( self . _hooks , state , self . _default )
Parse the primitive value under the parent XML element .
125
11
3,957
def serialize ( self , value , # type: Any state # type: _ProcessorState ) : # type: (...) -> ET.Element # For primitive values, this is only called when the value is part of an array, # in which case we do not need to check for missing or omitted values. start_element , end_element = _element_path_create_new ( self . element_path ) self . _serialize ( end_element , value , state ) return start_element
Serialize the value into a new element object and return the element .
106
14
3,958
def serialize_on_parent ( self , parent , # type: ET.Element value , # type: Any state # type: _ProcessorState ) : # type: (...) -> None # Note that falsey values are not treated as missing, but they may be omitted. if value is None and self . required : state . raise_error ( MissingValue , self . _missing_value_message ( parent ) ) if not value and self . omit_empty : return # Do Nothing element = _element_get_or_add_from_parent ( parent , self . element_path ) self . _serialize ( element , value , state )
Serialize the value and add it to the parent element .
138
12
3,959
def _missing_value_message ( self , parent ) : # type: (ET.Element) -> Text if self . _attribute is None : message = 'Missing required value for element "{}"' . format ( self . element_path ) else : if self . element_path == '.' : parent_name = parent . tag else : parent_name = self . element_path message = 'Missing required value for attribute "{}" on element "{}"' . format ( self . _attribute , parent_name ) return message
Return the message to report that the value needed for serialization is missing .
110
15
3,960
def _parse_attribute ( self , element , # type: ET.Element attribute , # type: Text state # type: _ProcessorState ) : # type: (...) -> Any parsed_value = self . _default attribute_value = element . get ( attribute , None ) if attribute_value is not None : parsed_value = self . _parser_func ( attribute_value , state ) elif self . required : state . raise_error ( MissingValue , 'Missing required attribute "{}" on element "{}"' . format ( self . _attribute , element . tag ) ) return parsed_value
Parse the primitive value within the XML element s attribute .
127
12
3,961
def _serialize ( self , element , # type: ET.Element value , # type: Any state # type: _ProcessorState ) : # type: (...) -> None xml_value = _hooks_apply_before_serialize ( self . _hooks , state , value ) # A value is only considered missing, and hence eligible to be replaced by its # default only if it is None. Falsey values are not considered missing and are # not replaced by the default. if xml_value is None : if self . _default is None : serialized_value = Text ( '' ) else : serialized_value = Text ( self . _default ) else : serialized_value = Text ( xml_value ) if self . _attribute : element . set ( self . _attribute , serialized_value ) else : element . text = serialized_value
Serialize the value to the element .
184
8
3,962
def push_location ( self , element_path , # type: Text array_index = None # type: Optional[int] ) : # type: (...) -> None location = ProcessorLocation ( element_path = element_path , array_index = array_index ) self . _locations . append ( location )
Push an item onto the state s stack of locations .
67
11
3,963
def raise_error ( self , exception_type , # type: Type[Exception] message # type: Text ) : # type: (...) -> NoReturn error_message = '{} at {}' . format ( message , repr ( self ) ) raise exception_type ( error_message )
Raise an exception with the current parser state information and error message .
62
14
3,964
def export_partlist_to_file ( input , output , timeout = 20 , showgui = False ) : input = norm_path ( input ) output = norm_path ( output ) commands = export_command ( output = output , output_type = 'partlist' ) command_eagle ( input = input , timeout = timeout , commands = commands , showgui = showgui )
call eagle and export sch or brd to partlist text file
82
13
3,965
def parse_partlist ( str ) : lines = str . strip ( ) . splitlines ( ) lines = filter ( len , lines ) hind = header_index ( lines ) if hind is None : log . debug ( 'empty partlist found' ) return ( [ ] , [ ] ) header_line = lines [ hind ] header = header_line . split ( ' ' ) header = filter ( len , header ) positions = [ header_line . index ( x ) for x in header ] header = [ x . strip ( ) . split ( ) [ 0 ] . lower ( ) for x in header ] data_lines = lines [ hind + 1 : ] def parse_data_line ( line ) : y = [ ( h , line [ pos1 : pos2 ] . strip ( ) ) for h , pos1 , pos2 in zip ( header , positions , positions [ 1 : ] + [ 1000 ] ) ] return dict ( y ) data = [ parse_data_line ( x ) for x in data_lines ] return ( header , data )
parse partlist text delivered by eagle .
223
8
3,966
def raw_partlist ( input , timeout = 20 , showgui = False ) : output = tempfile . NamedTemporaryFile ( prefix = 'eagexp_' , suffix = '.partlist' , delete = 0 ) . name export_partlist_to_file ( input = input , output = output , timeout = timeout , showgui = showgui ) s = Path ( output ) . text ( encoding = 'latin1' ) os . remove ( output ) return s
export partlist by eagle then return it
102
8
3,967
def structured_partlist ( input , timeout = 20 , showgui = False ) : s = raw_partlist ( input = input , timeout = timeout , showgui = showgui ) return parse_partlist ( s )
export partlist by eagle then parse it
47
8
3,968
def print_partlist ( input , timeout = 20 , showgui = False ) : print raw_partlist ( input = input , timeout = timeout , showgui = showgui )
print partlist text delivered by eagle
38
7
3,969
def bitset ( bs , member_label = None , filename = None , directory = None , format = None , render = False , view = False ) : if member_label is None : member_label = MEMBER_LABEL if filename is None : kind = 'members' if member_label else 'bits' filename = FILENAME % ( bs . __name__ , kind ) dot = graphviz . Digraph ( name = bs . __name__ , comment = repr ( bs ) , filename = filename , directory = directory , format = format , edge_attr = { 'dir' : 'none' } ) node_name = NAME_GETTERS [ 0 ] if callable ( member_label ) : node_label = member_label else : node_label = LABEL_GETTERS [ member_label ] for i in range ( bs . supremum + 1 ) : b = bs . fromint ( i ) name = node_name ( b ) dot . node ( name , node_label ( b ) ) dot . edges ( ( name , node_name ( b & ~ a ) ) for a in b . atoms ( reverse = True ) ) if render or view : dot . render ( view = view ) # pragma: no cover return dot
Graphviz source for the Hasse diagram of the domains Boolean algebra .
277
15
3,970
def _get_field_method ( self , tp ) : method = self . field_constructor . get ( tp ) if method and hasattr ( self , method . __name__ ) : return getattr ( self , method . __name__ ) return method
Returns a reference to the form element s constructor method .
57
11
3,971
def _create_plain_field ( self , attr , options ) : method = self . _get_field_method ( attr . py_type ) or self . _create_other_field klass , options = method ( attr , options ) if attr . is_unique : options [ 'validators' ] . append ( validators . UniqueEntityValidator ( attr . entity ) ) return klass , options
Creates the form element .
92
6
3,972
def _create_relational_field ( self , attr , options ) : options [ 'entity_class' ] = attr . py_type options [ 'allow_empty' ] = not attr . is_required return EntityField , options
Creates the form element for working with entity relationships .
53
11
3,973
def add ( self , attr , field_class = None , * * options ) : # print(attr.name, attr.py_type, getattr(attr, 'set', None)) # print(dir(attr)) # print(attr, attr.is_relation, attr.is_collection) # print(attr.is_pk, attr.auto, attr.is_unique, attr.is_part_of_unique_index, attr.composite_keys) def add ( klass , options ) : if klass : self . _fields [ attr . name ] = field_class ( * * options ) if field_class else klass ( * * options ) return self kwargs = { 'label' : attr . name , 'default' : attr . default , 'validators' : [ ] , } kwargs . update ( options ) if attr . is_pk : return add ( * self . _create_pk_field ( attr , kwargs ) ) if attr . is_collection : return add ( * self . _create_collection_field ( attr , kwargs ) ) validator = wtf_validators . InputRequired ( ) if attr . is_required and not attr . is_pk else wtf_validators . Optional ( ) kwargs [ 'validators' ] . insert ( 0 , validator ) if attr . is_relation : return add ( * self . _create_relational_field ( attr , kwargs ) ) return add ( * self . _create_plain_field ( attr , kwargs ) )
Adds an element to the form based on the entity attribute .
366
12
3,974
def add_button ( self , name , button_class = wtf_fields . SubmitField , * * options ) : self . _buttons [ name ] = button_class ( * * options )
Adds a button to the form .
43
7
3,975
def field_uuid ( self , attr , options ) : options [ 'validators' ] . append ( validators . UUIDValidator ( attr . entity ) ) return wtf_fields . StringField , options
Creates a form element for the UUID type .
48
11
3,976
def runm ( ) : signal . signal ( signal . SIGINT , signal_handler ) count = int ( sys . argv . pop ( 1 ) ) processes = [ Process ( target = run , args = ( ) ) for x in range ( count ) ] try : for p in processes : p . start ( ) except KeyError : # Not sure why we see a keyerror here. Weird. pass finally : for p in processes : p . join ( )
This is super minimal and pretty hacky but it counts as a first pass .
97
16
3,977
def identify ( self , request ) : token = self . get_jwt ( request ) if token is None : return NO_IDENTITY try : claims_set = self . decode_jwt ( token ) except ( DecodeError , ExpiredSignatureError ) : return NO_IDENTITY userid = self . get_userid ( claims_set ) if userid is None : return NO_IDENTITY extra_claims = self . get_extra_claims ( claims_set ) if extra_claims is not None : return Identity ( userid = userid , * * extra_claims ) else : return Identity ( userid = userid )
Establish what identity this user claims to have from request .
141
12
3,978
def remember ( self , response , request , identity ) : claims = identity . as_dict ( ) userid = claims . pop ( 'userid' ) claims_set = self . create_claims_set ( request , userid , claims ) token = self . encode_jwt ( claims_set ) response . headers [ 'Authorization' ] = '%s %s' % ( self . auth_header_prefix , token )
Remember identity on response .
94
5
3,979
def decode_jwt ( self , token , verify_expiration = True ) : options = { 'verify_exp' : verify_expiration , } return jwt . decode ( token , self . public_key , algorithms = [ self . algorithm ] , options = options , leeway = self . leeway , issuer = self . issuer )
Decode a JWTAuth token into its claims set .
74
13
3,980
def create_claims_set ( self , request , userid , extra_claims = None ) : claims_set = { self . userid_claim : userid } now = timegm ( datetime . utcnow ( ) . utctimetuple ( ) ) if self . expiration_delta is not None : claims_set [ 'exp' ] = now + self . expiration_delta if self . issuer is not None : claims_set [ 'iss' ] = self . issuer if self . allow_refresh : if self . refresh_delta is not None : claims_set [ 'refresh_until' ] = now + self . refresh_delta if self . refresh_nonce_handler is not None : claims_set [ 'nonce' ] = self . refresh_nonce_handler ( request , userid ) if extra_claims is not None : claims_set . update ( extra_claims ) return claims_set
Create the claims set based on the userid of the claimed identity the settings and the extra_claims dictionary .
207
23
3,981
def encode_jwt ( self , claims_set ) : token = jwt . encode ( claims_set , self . private_key , self . algorithm ) if PY3 : token = token . decode ( encoding = 'UTF-8' ) return token
Encode a JWT token based on the claims_set and the settings .
55
16
3,982
def get_extra_claims ( self , claims_set ) : reserved_claims = ( self . userid_claim , "iss" , "aud" , "exp" , "nbf" , "iat" , "jti" , "refresh_until" , "nonce" ) extra_claims = { } for claim in claims_set : if claim not in reserved_claims : extra_claims [ claim ] = claims_set [ claim ] if not extra_claims : return None return extra_claims
Get claims holding extra identity info from the claims set .
117
11
3,983
def get_jwt ( self , request ) : try : authorization = request . authorization except ValueError : return None if authorization is None : return None authtype , token = authorization if authtype . lower ( ) != self . auth_header_prefix . lower ( ) : return None return token
Extract the JWT token from the authorisation header of the request .
61
15
3,984
def verify_refresh ( self , request ) : if not self . allow_refresh : raise InvalidTokenError ( 'Token refresh is disabled' ) token = self . get_jwt ( request ) if token is None : raise InvalidTokenError ( 'Token not found' ) try : claims_set = self . decode_jwt ( token , self . verify_expiration_on_refresh ) # reraise the exceptions to change the error messages except DecodeError : raise DecodeError ( 'Token could not be decoded' ) except ExpiredSignatureError : raise ExpiredSignatureError ( 'Token has expired' ) userid = self . get_userid ( claims_set ) if userid is None : raise MissingRequiredClaimError ( self . userid_claim ) if self . refresh_nonce_handler is not None : if 'nonce' not in claims_set : raise MissingRequiredClaimError ( 'nonce' ) if self . refresh_nonce_handler ( request , userid ) != claims_set [ 'nonce' ] : raise InvalidTokenError ( 'Refresh nonce is not valid' ) if self . refresh_delta is not None : if 'refresh_until' not in claims_set : raise MissingRequiredClaimError ( 'refresh_until' ) now = timegm ( datetime . utcnow ( ) . utctimetuple ( ) ) refresh_until = int ( claims_set [ 'refresh_until' ] ) if refresh_until < ( now - self . leeway ) : raise ExpiredSignatureError ( 'Refresh nonce has expired' ) return userid
Verify if the request to refresh the token is valid . If valid it returns the userid which can be used to create an updated identity with remember_identity . Otherwise it raises an exception based on InvalidTokenError .
353
45
3,985
def fit_theil_sen ( x , y ) : xx = numpy . asarray ( x ) y1 = numpy . asarray ( y ) n = len ( xx ) if n < 5 : raise ValueError ( 'Number of points < 5' ) if xx . ndim != 1 : raise ValueError ( 'Input arrays have unexpected dimensions' ) if y1 . ndim == 1 : if len ( y1 ) != n : raise ValueError ( 'X and Y arrays have different sizes' ) yy = y1 [ numpy . newaxis , : ] elif y1 . ndim == 2 : if n != y1 . shape [ 0 ] : raise ValueError ( 'Y-array size in the fitting direction is different to the X-array size' ) yy = y1 . T else : raise ValueError ( 'Input arrays have unexpected dimensions' ) nmed = n // 2 iextra = nmed if ( n % 2 ) == 0 else nmed + 1 deltx = xx [ iextra : ] - xx [ : nmed ] delty = yy [ : , iextra : ] - yy [ : , : nmed ] allslopes = delty / deltx slopes = numpy . median ( allslopes , axis = 1 ) allinters = yy - slopes [ : , numpy . newaxis ] * x inters = numpy . median ( allinters , axis = 1 ) coeff = numpy . array ( [ inters , slopes ] ) return numpy . squeeze ( coeff )
Compute a robust linear fit using the Theil - Sen method .
334
14
3,986
def process_unknown_arguments ( unknowns ) : result = argparse . Namespace ( ) result . extra_control = { } # It would be interesting to use argparse internal # machinery for this for unknown in unknowns : # Check prefixes prefix = '--parameter-' if unknown . startswith ( prefix ) : # process '=' values = unknown . split ( '=' ) if len ( values ) == 2 : key = values [ 0 ] [ len ( prefix ) : ] val = values [ 1 ] if key : result . extra_control [ key ] = val return result
Process arguments unknown to the parser
125
6
3,987
def get_fd ( file_or_fd , default = None ) : fd = file_or_fd if fd is None : fd = default if hasattr ( fd , "fileno" ) : fd = fd . fileno ( ) return fd
Helper function for getting a file descriptor .
60
8
3,988
def forkexec_pty ( argv , env = None , size = None ) : child_pid , child_fd = pty . fork ( ) if child_pid == 0 : os . closerange ( 3 , MAXFD ) environ = os . environ . copy ( ) if env is not None : environ . update ( env ) os . execve ( argv [ 0 ] , argv , environ ) if size is None : try : size = get_terminal_size ( 1 ) except Exception : size = ( 80 , 24 ) set_terminal_size ( child_fd , size ) return child_pid , child_fd
Fork a child process attached to a pty .
141
11
3,989
def get_ancestor_processes ( ) : if not _ANCESTOR_PROCESSES and psutil is not None : proc = psutil . Process ( os . getpid ( ) ) while proc . parent ( ) is not None : try : _ANCESTOR_PROCESSES . append ( proc . parent ( ) . exe ( ) ) proc = proc . parent ( ) except psutil . Error : break return _ANCESTOR_PROCESSES
Get a list of the executables of all ancestor processes .
103
12
3,990
def get_default_shell ( environ = None , fallback = _UNSPECIFIED ) : if environ is None : environ = os . environ # If the option is specified in the environment, respect it. if "PIAS_OPT_SHELL" in environ : return environ [ "PIAS_OPT_SHELL" ] # Find all candiate shell programs. shells = [ ] for filename in ( environ . get ( "SHELL" ) , "bash" , "sh" ) : if filename is not None : filepath = find_executable ( filename , environ ) if filepath is not None : shells . append ( filepath ) # If one of them is an ancestor process, use that. for ancestor in get_ancestor_processes ( ) : if ancestor in shells : return ancestor # Otherwise use the first option that we found. for shell in shells : return shell # Use an explicit fallback option if given. if fallback is not _UNSPECIFIED : return fallback raise ValueError ( "Could not find a shell" )
Get the user s default shell program .
232
8
3,991
def get_default_terminal ( environ = None , fallback = _UNSPECIFIED ) : if environ is None : environ = os . environ # If the option is specified in the environment, respect it. if "PIAS_OPT_TERMINAL" in environ : return environ [ "PIAS_OPT_TERMINAL" ] # Find all candiate terminal programs. terminals = [ ] colorterm = environ . get ( "COLORTERM" ) for filename in ( colorterm , "gnome-terminal" , "konsole" , "xterm" ) : if filename is not None : filepath = find_executable ( filename , environ ) if filepath is not None : terminals . append ( filepath ) # If one of them is an ancestor process, use that. for ancestor in get_ancestor_processes ( ) : if ancestor in terminals : return ancestor # Otherwise use the first option that we found. for term in terminals : return term # Use an explicit fallback option if given. if fallback is not _UNSPECIFIED : return fallback raise ValueError ( "Could not find a terminal" )
Get the user s default terminal program .
252
8
3,992
def get_pias_script ( environ = None ) : if os . path . basename ( sys . argv [ 0 ] ) == "pias" : return sys . argv [ 0 ] filepath = find_executable ( "pias" , environ ) if filepath is not None : return filepath filepath = os . path . join ( os . path . dirname ( __file__ ) , "__main__.py" ) # XXX TODO: check if executable if os . path . exists ( filepath ) : return filepath raise RuntimeError ( "Could not locate the pias script." )
Get the path to the playitagainsam command - line script .
135
15
3,993
def airwires ( board , showgui = 0 ) : board = Path ( board ) . expand ( ) . abspath ( ) file_out = tempfile . NamedTemporaryFile ( suffix = '.txt' , delete = 0 ) file_out . close ( ) ulp = ulp_templ . replace ( 'FILE_NAME' , file_out . name ) file_ulp = tempfile . NamedTemporaryFile ( suffix = '.ulp' , delete = 0 ) file_ulp . write ( ulp . encode ( 'utf-8' ) ) file_ulp . close ( ) commands = [ 'run ' + file_ulp . name , 'quit' , ] command_eagle ( board , commands = commands , showgui = showgui ) n = int ( Path ( file_out . name ) . text ( ) ) Path ( file_out . name ) . remove ( ) Path ( file_ulp . name ) . remove ( ) return n
search for airwires in eagle board
205
8
3,994
def _initialize ( self , con ) : if self . initialized : return SQLite3Database ( ) . _initialize ( con ) # ASE db initialization cur = con . execute ( 'SELECT COUNT(*) FROM sqlite_master WHERE name="reaction"' ) if cur . fetchone ( ) [ 0 ] == 0 : # no reaction table for init_command in init_commands : con . execute ( init_command ) # Create tables con . commit ( ) self . initialized = True
Set up tables in SQL
106
5
3,995
def write_publication ( self , values ) : con = self . connection or self . _connect ( ) self . _initialize ( con ) cur = con . cursor ( ) values = ( values [ 'pub_id' ] , values [ 'title' ] , json . dumps ( values [ 'authors' ] ) , values [ 'journal' ] , values [ 'volume' ] , values [ 'number' ] , values [ 'pages' ] , values [ 'year' ] , values [ 'publisher' ] , values [ 'doi' ] , json . dumps ( values [ 'tags' ] ) ) q = self . default + ',' + ', ' . join ( '?' * len ( values ) ) cur . execute ( 'INSERT OR IGNORE INTO publication VALUES ({})' . format ( q ) , values ) pid = self . get_last_id ( cur , table = 'publication' ) if self . connection is None : con . commit ( ) con . close ( ) return pid
Write publication info to db
216
5
3,996
def write ( self , values , data = None ) : con = self . connection or self . _connect ( ) self . _initialize ( con ) cur = con . cursor ( ) pub_id = values [ 'pub_id' ] ase_ids = values [ 'ase_ids' ] energy_corrections = values [ 'energy_corrections' ] if ase_ids is not None : check_ase_ids ( values , ase_ids ) else : ase_ids = { } values = ( values [ 'chemical_composition' ] , values [ 'surface_composition' ] , values [ 'facet' ] , json . dumps ( values [ 'sites' ] ) , json . dumps ( values [ 'coverages' ] ) , json . dumps ( values [ 'reactants' ] ) , json . dumps ( values [ 'products' ] ) , values [ 'reaction_energy' ] , values [ 'activation_energy' ] , values [ 'dft_code' ] , values [ 'dft_functional' ] , values [ 'username' ] , values [ 'pub_id' ] ) """ Write to reaction table""" q = self . default + ',' + ', ' . join ( '?' * len ( values ) ) cur . execute ( 'INSERT INTO reaction VALUES ({})' . format ( q ) , values ) id = self . get_last_id ( cur ) reaction_structure_values = [ ] """ Write to publication_system and reaction_system tables""" for name , ase_id in ase_ids . items ( ) : if name in energy_corrections : energy_correction = energy_corrections [ name ] else : energy_correction = 0 reaction_structure_values . append ( [ name , energy_correction , ase_id , id ] ) insert_statement = """INSERT OR IGNORE INTO publication_system(ase_id, pub_id) VALUES (?, ?)""" cur . execute ( insert_statement , [ ase_id , pub_id ] ) cur . executemany ( 'INSERT INTO reaction_system VALUES (?, ?, ?, ?)' , reaction_structure_values ) if self . connection is None : con . commit ( ) con . close ( ) return id
Write reaction info to db file
494
6
3,997
def update ( self , id , values , key_names = 'all' ) : con = self . connection or self . _connect ( ) self . _initialize ( con ) cur = con . cursor ( ) pub_id = values [ 'pub_id' ] ase_ids = values [ 'ase_ids' ] energy_corrections = values [ 'energy_corrections' ] if ase_ids is not None : check_ase_ids ( values , ase_ids ) else : ase_ids = { } key_list , value_list = get_key_value_list ( key_names , values ) N_keys = len ( key_list ) value_strlist = get_value_strlist ( value_list ) execute_str = ', ' . join ( '{}={}' . format ( key_list [ i ] , value_strlist [ i ] ) for i in range ( N_keys ) ) update_command = 'UPDATE reaction SET {} WHERE id = {};' . format ( execute_str , id ) cur . execute ( update_command ) delete_command = 'DELETE from reaction_system WHERE id = {}' . format ( id ) cur . execute ( delete_command ) reaction_structure_values = [ ] for name , ase_id in ase_ids . items ( ) : reaction_structure_values . append ( [ name , energy_corrections . get ( name ) , ase_id , id ] ) insert_statement = """INSERT OR IGNORE INTO publication_system(ase_id, pub_id) VALUES (?, ?)""" cur . execute ( insert_statement , [ ase_id , pub_id ] ) cur . executemany ( 'INSERT INTO reaction_system VALUES (?, ?, ?, ?)' , reaction_structure_values ) if self . connection is None : con . commit ( ) con . close ( ) return id
Update reaction info for a selected row
420
7
3,998
def get_last_id ( self , cur , table = 'reaction' ) : cur . execute ( "SELECT seq FROM sqlite_sequence WHERE name='{0}'" . format ( table ) ) result = cur . fetchone ( ) if result is not None : id = result [ 0 ] else : id = 0 return id
Get the id of the last written row in table
71
10
3,999
def read_wv_master_from_array ( master_table , lines = 'brightest' , debugplot = 0 ) : # protection if lines not in [ 'brightest' , 'all' ] : raise ValueError ( 'Unexpected lines=' + str ( lines ) ) # determine wavelengths according to the number of columns if master_table . ndim == 1 : wv_master = master_table else : wv_master_all = master_table [ : , 0 ] if master_table . shape [ 1 ] == 2 : # assume old format wv_master = np . copy ( wv_master_all ) elif master_table . shape [ 1 ] == 3 : # assume new format if lines == 'brightest' : wv_flag = master_table [ : , 1 ] wv_master = wv_master_all [ np . where ( wv_flag == 1 ) ] else : wv_master = np . copy ( wv_master_all ) else : raise ValueError ( 'Lines_catalog file does not have the ' 'expected number of columns' ) if abs ( debugplot ) >= 10 : print ( "Reading master table from numpy array" ) print ( "wv_master:\n" , wv_master ) return wv_master
read arc line wavelengths from numpy array
284
8