query stringlengths 5 1.23k | positive stringlengths 53 15.2k | id_ int64 0 252k | task_name stringlengths 87 242 | negative listlengths 20 553 |
|---|---|---|---|---|
Memorizes a global variable | def _onGlobal ( self , name , line , pos , absPosition , level ) : # level is ignored for item in self . globals : if item . name == name : return self . globals . append ( Global ( name , line , pos , absPosition ) ) | 6,300 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/cdmpyparser.py#L492-L498 | [
"def",
"read",
"(",
"self",
",",
"document",
",",
"iface",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"document",
"=",
"IReadableDocument",
"(",
"document",
")",
"mime_type",
"=",
"document",
".",
"mime_type",
"reader",
"=",
"self",
".",
"lookup_reader",
"(",
"mime_type",
",",
"iface",
")",
"if",
"not",
"reader",
":",
"msg",
"=",
"(",
"\"No adapter found to read object %s from %s document\"",
"%",
"(",
"iface",
".",
"__class__",
".",
"__name__",
",",
"mime_type",
")",
")",
"raise",
"NoReaderFoundError",
"(",
"msg",
")",
"return",
"reader",
".",
"read",
"(",
"document",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
":",
"return",
"defer",
".",
"fail",
"(",
"Failure",
"(",
")",
")"
] |
Memorizes a class | def _onClass ( self , name , line , pos , absPosition , keywordLine , keywordPos , colonLine , colonPos , level ) : self . __flushLevel ( level ) c = Class ( name , line , pos , absPosition , keywordLine , keywordPos , colonLine , colonPos ) if self . __lastDecorators is not None : c . decorators = self . __lastDecorators self . __lastDecorators = None self . objectsStack . append ( c ) | 6,301 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/cdmpyparser.py#L500-L510 | [
"def",
"ends_with_path_separator",
"(",
"self",
",",
"file_path",
")",
":",
"if",
"is_int_type",
"(",
"file_path",
")",
":",
"return",
"False",
"file_path",
"=",
"make_string_path",
"(",
"file_path",
")",
"return",
"(",
"file_path",
"and",
"file_path",
"not",
"in",
"(",
"self",
".",
"path_separator",
",",
"self",
".",
"alternative_path_separator",
")",
"and",
"(",
"file_path",
".",
"endswith",
"(",
"self",
".",
"_path_separator",
"(",
"file_path",
")",
")",
"or",
"self",
".",
"alternative_path_separator",
"is",
"not",
"None",
"and",
"file_path",
".",
"endswith",
"(",
"self",
".",
"_alternative_path_separator",
"(",
"file_path",
")",
")",
")",
")"
] |
Memorizes an imported item | def _onWhat ( self , name , line , pos , absPosition ) : self . __lastImport . what . append ( ImportWhat ( name , line , pos , absPosition ) ) | 6,302 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/cdmpyparser.py#L538-L540 | [
"def",
"main",
"(",
")",
":",
"try",
":",
"# Retrieve the first USB device",
"device",
"=",
"AlarmDecoder",
"(",
"SerialDevice",
"(",
"interface",
"=",
"SERIAL_DEVICE",
")",
")",
"# Set up an event handler and open the device",
"device",
".",
"on_rfx_message",
"+=",
"handle_rfx",
"with",
"device",
".",
"open",
"(",
"baudrate",
"=",
"BAUDRATE",
")",
":",
"while",
"True",
":",
"time",
".",
"sleep",
"(",
"1",
")",
"except",
"Exception",
"as",
"ex",
":",
"print",
"(",
"'Exception:'",
",",
"ex",
")"
] |
Memorizes a class attribute | def _onClassAttribute ( self , name , line , pos , absPosition , level ) : # A class must be on the top of the stack attributes = self . objectsStack [ level ] . classAttributes for item in attributes : if item . name == name : return attributes . append ( ClassAttribute ( name , line , pos , absPosition ) ) | 6,303 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/cdmpyparser.py#L542-L549 | [
"def",
"_comparable",
"(",
"self",
")",
":",
"return",
"self",
".",
"_replace",
"(",
"name",
"=",
"''",
"if",
"self",
".",
"name",
"is",
"None",
"else",
"self",
".",
"name",
",",
"wavelength",
"=",
"tuple",
"(",
")",
"if",
"self",
".",
"wavelength",
"is",
"None",
"else",
"self",
".",
"wavelength",
",",
"resolution",
"=",
"0",
"if",
"self",
".",
"resolution",
"is",
"None",
"else",
"self",
".",
"resolution",
",",
"polarization",
"=",
"''",
"if",
"self",
".",
"polarization",
"is",
"None",
"else",
"self",
".",
"polarization",
",",
"calibration",
"=",
"''",
"if",
"self",
".",
"calibration",
"is",
"None",
"else",
"self",
".",
"calibration",
",",
")"
] |
Memorizes a class instance attribute | def _onInstanceAttribute ( self , name , line , pos , absPosition , level ) : # Instance attributes may appear in member functions only so we already # have a function on the stack of objects. To get the class object one # more step is required so we -1 here. attributes = self . objectsStack [ level - 1 ] . instanceAttributes for item in attributes : if item . name == name : return attributes . append ( InstanceAttribute ( name , line , pos , absPosition ) ) | 6,304 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/cdmpyparser.py#L551-L560 | [
"def",
"_comparable",
"(",
"self",
")",
":",
"return",
"self",
".",
"_replace",
"(",
"name",
"=",
"''",
"if",
"self",
".",
"name",
"is",
"None",
"else",
"self",
".",
"name",
",",
"wavelength",
"=",
"tuple",
"(",
")",
"if",
"self",
".",
"wavelength",
"is",
"None",
"else",
"self",
".",
"wavelength",
",",
"resolution",
"=",
"0",
"if",
"self",
".",
"resolution",
"is",
"None",
"else",
"self",
".",
"resolution",
",",
"polarization",
"=",
"''",
"if",
"self",
".",
"polarization",
"is",
"None",
"else",
"self",
".",
"polarization",
",",
"calibration",
"=",
"''",
"if",
"self",
".",
"calibration",
"is",
"None",
"else",
"self",
".",
"calibration",
",",
")"
] |
Memorizes a function argument | def _onArgument ( self , name , annotation ) : self . objectsStack [ - 1 ] . arguments . append ( Argument ( name , annotation ) ) | 6,305 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/cdmpyparser.py#L583-L585 | [
"def",
"_openResources",
"(",
"self",
")",
":",
"try",
":",
"rate",
",",
"data",
"=",
"scipy",
".",
"io",
".",
"wavfile",
".",
"read",
"(",
"self",
".",
"_fileName",
",",
"mmap",
"=",
"True",
")",
"except",
"Exception",
"as",
"ex",
":",
"logger",
".",
"warning",
"(",
"ex",
")",
"logger",
".",
"warning",
"(",
"\"Unable to read wav with memmory mapping. Trying without now.\"",
")",
"rate",
",",
"data",
"=",
"scipy",
".",
"io",
".",
"wavfile",
".",
"read",
"(",
"self",
".",
"_fileName",
",",
"mmap",
"=",
"False",
")",
"self",
".",
"_array",
"=",
"data",
"self",
".",
"attributes",
"[",
"'rate'",
"]",
"=",
"rate"
] |
Memorizies a parser error message | def _onError ( self , message ) : self . isOK = False if message . strip ( ) != "" : self . errors . append ( message ) | 6,306 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/cdmpyparser.py#L596-L600 | [
"def",
"adc",
"(",
"self",
",",
"other",
":",
"'BitVector'",
",",
"carry",
":",
"Bit",
")",
"->",
"tp",
".",
"Tuple",
"[",
"'BitVector'",
",",
"Bit",
"]",
":",
"T",
"=",
"type",
"(",
"self",
")",
"other",
"=",
"_coerce",
"(",
"T",
",",
"other",
")",
"carry",
"=",
"_coerce",
"(",
"T",
".",
"unsized_t",
"[",
"1",
"]",
",",
"carry",
")",
"a",
"=",
"self",
".",
"zext",
"(",
"1",
")",
"b",
"=",
"other",
".",
"zext",
"(",
"1",
")",
"c",
"=",
"carry",
".",
"zext",
"(",
"T",
".",
"size",
")",
"res",
"=",
"a",
"+",
"b",
"+",
"c",
"return",
"res",
"[",
"0",
":",
"-",
"1",
"]",
",",
"res",
"[",
"-",
"1",
"]"
] |
Memorizes a lexer error message | def _onLexerError ( self , message ) : self . isOK = False if message . strip ( ) != "" : self . lexerErrors . append ( message ) | 6,307 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/cdmpyparser.py#L602-L606 | [
"def",
"_GetPathSegmentIndexForOccurrenceWeights",
"(",
"self",
",",
"occurrence_weights",
",",
"value_weights",
")",
":",
"largest_weight",
"=",
"occurrence_weights",
".",
"GetLargestWeight",
"(",
")",
"if",
"largest_weight",
">",
"0",
":",
"occurrence_weight_indexes",
"=",
"occurrence_weights",
".",
"GetIndexesForWeight",
"(",
"largest_weight",
")",
"number_of_occurrence_indexes",
"=",
"len",
"(",
"occurrence_weight_indexes",
")",
"else",
":",
"number_of_occurrence_indexes",
"=",
"0",
"path_segment_index",
"=",
"None",
"if",
"number_of_occurrence_indexes",
"==",
"0",
":",
"path_segment_index",
"=",
"self",
".",
"_GetPathSegmentIndexForValueWeights",
"(",
"value_weights",
")",
"elif",
"number_of_occurrence_indexes",
"==",
"1",
":",
"path_segment_index",
"=",
"occurrence_weight_indexes",
"[",
"0",
"]",
"else",
":",
"largest_weight",
"=",
"0",
"for",
"occurrence_index",
"in",
"occurrence_weight_indexes",
":",
"value_weight",
"=",
"value_weights",
".",
"GetWeightForIndex",
"(",
"occurrence_index",
")",
"if",
"not",
"path_segment_index",
"or",
"largest_weight",
"<",
"value_weight",
":",
"largest_weight",
"=",
"value_weight",
"path_segment_index",
"=",
"occurrence_index",
"return",
"path_segment_index"
] |
Generate a uniq mapfile pathname . | def gen_mapname ( ) : filepath = None while ( filepath is None ) or ( os . path . exists ( os . path . join ( config [ 'mapfiles_dir' ] , filepath ) ) ) : filepath = '%s.map' % _gen_string ( ) return filepath | 6,308 | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/lib/helpers.py#L39-L44 | [
"def",
"delete_dimension",
"(",
"dimension_id",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"dimension",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Dimension",
")",
".",
"filter",
"(",
"Dimension",
".",
"id",
"==",
"dimension_id",
")",
".",
"one",
"(",
")",
"db",
".",
"DBSession",
".",
"query",
"(",
"Unit",
")",
".",
"filter",
"(",
"Unit",
".",
"dimension_id",
"==",
"dimension",
".",
"id",
")",
".",
"delete",
"(",
")",
"db",
".",
"DBSession",
".",
"delete",
"(",
"dimension",
")",
"db",
".",
"DBSession",
".",
"flush",
"(",
")",
"return",
"True",
"except",
"NoResultFound",
":",
"raise",
"ResourceNotFoundError",
"(",
"\"Dimension (dimension_id=%s) does not exist\"",
"%",
"(",
"dimension_id",
")",
")"
] |
Called by self . write_config this returns the text content for the config file given the provided variables . | def config_content ( self , command , vars ) : settable_vars = [ var ( 'db_url' , 'Database url for sqlite, postgres or mysql' , default = 'sqlite:///%(here)s/studio.db' ) , var ( 'ms_url' , 'Url to the mapserv CGI' , default = 'http://localhost/cgi-bin/mapserv' ) , var ( 'admin_password' , 'Password for default admin user' , default = secret . secret_string ( length = 8 ) ) ] for svar in settable_vars : if command . interactive : prompt = 'Enter %s' % svar . full_description ( ) response = command . challenge ( prompt , svar . default , svar . should_echo ) vars [ svar . name ] = response else : if not vars . has_key ( svar . name ) : vars [ svar . name ] = svar . default vars [ 'cookie_secret' ] = secret . secret_string ( ) # call default pylons install return super ( StudioInstaller , self ) . config_content ( command , vars ) | 6,309 | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/config/installer.py#L29-L55 | [
"def",
"numRegisteredForRole",
"(",
"self",
",",
"role",
",",
"includeTemporaryRegs",
"=",
"False",
")",
":",
"count",
"=",
"self",
".",
"eventregistration_set",
".",
"filter",
"(",
"cancelled",
"=",
"False",
",",
"dropIn",
"=",
"False",
",",
"role",
"=",
"role",
")",
".",
"count",
"(",
")",
"if",
"includeTemporaryRegs",
":",
"count",
"+=",
"self",
".",
"temporaryeventregistration_set",
".",
"filter",
"(",
"dropIn",
"=",
"False",
",",
"role",
"=",
"role",
")",
".",
"exclude",
"(",
"registration__expirationDate__lte",
"=",
"timezone",
".",
"now",
"(",
")",
")",
".",
"count",
"(",
")",
"return",
"count"
] |
Interpolates definitions from the top - level definitions key into the schema . This is performed in a cut - down way similar to JSON schema . | def _resolve_definitions ( self , schema , definitions ) : if not definitions : return schema if not isinstance ( schema , dict ) : return schema ref = schema . pop ( '$ref' , None ) if ref : path = ref . split ( '/' ) [ 2 : ] definition = definitions for component in path : definition = definitions [ component ] if definition : # Only update specified fields for ( key , val ) in six . iteritems ( definition ) : if key not in schema : schema [ key ] = val for key in six . iterkeys ( schema ) : schema [ key ] = self . _resolve_definitions ( schema [ key ] , definitions ) return schema | 6,310 | https://github.com/jpgxs/pyopsview/blob/5bbef35e463eda6dc67b0c34d3633a5a1c75a932/pyopsview/schema.py#L181-L207 | [
"def",
"_fill_untouched",
"(",
"idx",
",",
"ret",
",",
"fill_value",
")",
":",
"untouched",
"=",
"np",
".",
"ones_like",
"(",
"ret",
",",
"dtype",
"=",
"bool",
")",
"untouched",
"[",
"idx",
"]",
"=",
"False",
"ret",
"[",
"untouched",
"]",
"=",
"fill_value"
] |
Gets a serializer for a particular type . For primitives returns the serializer from the module - level serializers . For arrays and objects uses the special _get_T_serializer methods to build the encoders and decoders . | def _get_serializer ( self , _type ) : if _type in _serializers : # _serializers is module level return _serializers [ _type ] # array and object are special types elif _type == 'array' : return self . _get_array_serializer ( ) elif _type == 'object' : return self . _get_object_serializer ( ) raise ValueError ( 'Unknown type: {}' . format ( _type ) ) | 6,311 | https://github.com/jpgxs/pyopsview/blob/5bbef35e463eda6dc67b0c34d3633a5a1c75a932/pyopsview/schema.py#L209-L223 | [
"def",
"addTextErr",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"_currentColor",
"=",
"self",
".",
"_red",
"self",
".",
"addText",
"(",
"text",
")"
] |
Gets the encoder and decoder for an array . Uses the items key to build the encoders and decoders for the specified type . | def _get_array_serializer ( self ) : if not self . _items : raise ValueError ( 'Must specify \'items\' for \'array\' type' ) field = SchemaField ( self . _items ) def encode ( value , field = field ) : if not isinstance ( value , list ) : value = [ value ] return [ field . encode ( i ) for i in value ] def decode ( value , field = field ) : return [ field . decode ( i ) for i in value ] return ( encode , decode ) | 6,312 | https://github.com/jpgxs/pyopsview/blob/5bbef35e463eda6dc67b0c34d3633a5a1c75a932/pyopsview/schema.py#L225-L243 | [
"def",
"save_rst",
"(",
"self",
",",
"fd",
")",
":",
"from",
"pylon",
".",
"io",
"import",
"ReSTWriter",
"ReSTWriter",
"(",
"self",
")",
".",
"write",
"(",
"fd",
")"
] |
The encoder for this schema . Tries each encoder in order of the types specified for this schema . | def encode ( self , value ) : if value is None and self . _default is not None : value = self . _default for encoder in self . _encoders : try : return encoder ( value ) except ValueError as ex : pass raise ValueError ( 'Value \'{}\' is invalid. {}' . format ( value , ex . message ) ) | 6,313 | https://github.com/jpgxs/pyopsview/blob/5bbef35e463eda6dc67b0c34d3633a5a1c75a932/pyopsview/schema.py#L360-L374 | [
"def",
"extract_cookies_to_jar",
"(",
"jar",
",",
"request",
",",
"response",
")",
":",
"if",
"not",
"(",
"hasattr",
"(",
"response",
",",
"'_original_response'",
")",
"and",
"response",
".",
"_original_response",
")",
":",
"return",
"# the _original_response field is the wrapped httplib.HTTPResponse object,",
"req",
"=",
"MockRequest",
"(",
"request",
")",
"# pull out the HTTPMessage with the headers and put it in the mock:",
"res",
"=",
"MockResponse",
"(",
"response",
".",
"_original_response",
".",
"msg",
")",
"jar",
".",
"extract_cookies",
"(",
"res",
",",
"req",
")"
] |
The decoder for this schema . Tries each decoder in order of the types specified for this schema . | def decode ( self , value ) : # Use the default value unless the field accepts None types has_null_encoder = bool ( encode_decode_null in self . _decoders ) if value is None and self . _default is not None and not has_null_encoder : value = self . _default for decoder in self . _decoders : try : return decoder ( value ) except ValueError as ex : pass raise ValueError ( 'Value \'{}\' is invalid. {}' . format ( value , ex . message ) ) | 6,314 | https://github.com/jpgxs/pyopsview/blob/5bbef35e463eda6dc67b0c34d3633a5a1c75a932/pyopsview/schema.py#L376-L393 | [
"def",
"receive_data_chunk",
"(",
"self",
",",
"raw_data",
",",
"start",
")",
":",
"self",
".",
"file",
".",
"write",
"(",
"raw_data",
")",
"# CHANGED: This un-hangs us long enough to keep things rolling.",
"eventlet",
".",
"sleep",
"(",
"0",
")"
] |
The module arguments are dynamically generated based on the Opsview version . This means that fail_json isn t available until after the module has been properly initialized and the schemas have been loaded . | def _fail_early ( message , * * kwds ) : import json output = dict ( kwds ) output . update ( { 'msg' : message , 'failed' : True , } ) print ( json . dumps ( output ) ) sys . exit ( 1 ) | 6,315 | https://github.com/jpgxs/pyopsview/blob/5bbef35e463eda6dc67b0c34d3633a5a1c75a932/pyopsview/ansible/module_utils/opsview.py#L14-L27 | [
"def",
"degrees_dir",
"(",
"CIJ",
")",
":",
"CIJ",
"=",
"binarize",
"(",
"CIJ",
",",
"copy",
"=",
"True",
")",
"# ensure CIJ is binary",
"id",
"=",
"np",
".",
"sum",
"(",
"CIJ",
",",
"axis",
"=",
"0",
")",
"# indegree = column sum of CIJ",
"od",
"=",
"np",
".",
"sum",
"(",
"CIJ",
",",
"axis",
"=",
"1",
")",
"# outdegree = row sum of CIJ",
"deg",
"=",
"id",
"+",
"od",
"# degree = indegree+outdegree",
"return",
"id",
",",
"od",
",",
"deg"
] |
Deep comparison between objects ; assumes that new contains user defined parameters so only keys which exist in new will be compared . Returns True if they differ . Else False . | def _compare_recursive ( old , new ) : if isinstance ( new , dict ) : for key in six . iterkeys ( new ) : try : if _compare_recursive ( old [ key ] , new [ key ] ) : return True except ( KeyError , TypeError ) : return True elif isinstance ( new , list ) or isinstance ( new , tuple ) : for i , item in enumerate ( new ) : try : if _compare_recursive ( old [ i ] , item ) : return True except ( IndexError , TypeError ) : return True else : return old != new return False | 6,316 | https://github.com/jpgxs/pyopsview/blob/5bbef35e463eda6dc67b0c34d3633a5a1c75a932/pyopsview/ansible/module_utils/opsview.py#L30-L53 | [
"def",
"decode_offset_fetch_response",
"(",
"cls",
",",
"response",
")",
":",
"return",
"[",
"kafka",
".",
"structs",
".",
"OffsetFetchResponsePayload",
"(",
"topic",
",",
"partition",
",",
"offset",
",",
"metadata",
",",
"error",
")",
"for",
"topic",
",",
"partitions",
"in",
"response",
".",
"topics",
"for",
"partition",
",",
"offset",
",",
"metadata",
",",
"error",
"in",
"partitions",
"]"
] |
Checks whether the old object and new object differ ; only checks keys which exist in the new object | def _requires_update ( self , old_object , new_object ) : old_encoded = self . manager . _encode ( old_object ) new_encoded = self . manager . _encode ( new_object ) return _compare_recursive ( old_encoded , new_encoded ) | 6,317 | https://github.com/jpgxs/pyopsview/blob/5bbef35e463eda6dc67b0c34d3633a5a1c75a932/pyopsview/ansible/module_utils/opsview.py#L215-L221 | [
"def",
"set_offload",
"(",
"devname",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"param",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"param",
"==",
"'tcp_segmentation_offload'",
":",
"value",
"=",
"value",
"==",
"\"on\"",
"and",
"1",
"or",
"0",
"try",
":",
"ethtool",
".",
"set_tso",
"(",
"devname",
",",
"value",
")",
"except",
"IOError",
":",
"return",
"'Not supported'",
"return",
"show_offload",
"(",
"devname",
")"
] |
extract domain from url | def url2domain ( url ) : parsed_uri = urlparse . urlparse ( url ) domain = '{uri.netloc}' . format ( uri = parsed_uri ) domain = re . sub ( "^.+@" , "" , domain ) domain = re . sub ( ":.+$" , "" , domain ) return domain | 6,318 | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/web.py#L20-L27 | [
"def",
"_read_footer",
"(",
"file_obj",
")",
":",
"footer_size",
"=",
"_get_footer_size",
"(",
"file_obj",
")",
"if",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"logger",
".",
"debug",
"(",
"\"Footer size in bytes: %s\"",
",",
"footer_size",
")",
"file_obj",
".",
"seek",
"(",
"-",
"(",
"8",
"+",
"footer_size",
")",
",",
"2",
")",
"# seek to beginning of footer",
"tin",
"=",
"TFileTransport",
"(",
"file_obj",
")",
"pin",
"=",
"TCompactProtocolFactory",
"(",
")",
".",
"get_protocol",
"(",
"tin",
")",
"fmd",
"=",
"parquet_thrift",
".",
"FileMetaData",
"(",
")",
"fmd",
".",
"read",
"(",
"pin",
")",
"return",
"fmd"
] |
Call me before using any of the tables or classes in the model | def init_model ( engine ) : if meta . Session is None : sm = orm . sessionmaker ( autoflush = True , autocommit = False , bind = engine ) meta . engine = engine meta . Session = orm . scoped_session ( sm ) | 6,319 | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/model/__init__.py#L32-L38 | [
"def",
"write_asynchronously",
"(",
"library",
",",
"session",
",",
"data",
")",
":",
"job_id",
"=",
"ViJobId",
"(",
")",
"# [ViSession, ViBuf, ViUInt32, ViPJobId]",
"ret",
"=",
"library",
".",
"viWriteAsync",
"(",
"session",
",",
"data",
",",
"len",
"(",
"data",
")",
",",
"byref",
"(",
"job_id",
")",
")",
"return",
"job_id",
",",
"ret"
] |
register a property handler | def register_prop ( name , handler_get , handler_set ) : global props_get , props_set if handler_get : props_get [ name ] = handler_get if handler_set : props_set [ name ] = handler_set | 6,320 | https://github.com/unbit/davvy/blob/d9cd95fba25dbc76d80955bbbe5ff9d7cf52268a/davvy/__init__.py#L9-L17 | [
"def",
"from_manifest",
"(",
"app",
",",
"filename",
",",
"raw",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"cfg",
"=",
"current_app",
".",
"config",
"if",
"current_app",
".",
"config",
".",
"get",
"(",
"'TESTING'",
")",
":",
"return",
"# Do not spend time here when testing",
"path",
"=",
"_manifests",
"[",
"app",
"]",
"[",
"filename",
"]",
"if",
"not",
"raw",
"and",
"cfg",
".",
"get",
"(",
"'CDN_DOMAIN'",
")",
"and",
"not",
"cfg",
".",
"get",
"(",
"'CDN_DEBUG'",
")",
":",
"scheme",
"=",
"'https'",
"if",
"cfg",
".",
"get",
"(",
"'CDN_HTTPS'",
")",
"else",
"request",
".",
"scheme",
"prefix",
"=",
"'{}://'",
".",
"format",
"(",
"scheme",
")",
"if",
"not",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"# CDN_DOMAIN has no trailing slash",
"path",
"=",
"'/'",
"+",
"path",
"return",
"''",
".",
"join",
"(",
"(",
"prefix",
",",
"cfg",
"[",
"'CDN_DOMAIN'",
"]",
",",
"path",
")",
")",
"elif",
"not",
"raw",
"and",
"kwargs",
".",
"get",
"(",
"'external'",
",",
"False",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"# request.host_url has a trailing slash",
"path",
"=",
"path",
"[",
"1",
":",
"]",
"return",
"''",
".",
"join",
"(",
"(",
"request",
".",
"host_url",
",",
"path",
")",
")",
"return",
"path"
] |
retrieve a property handler | def retrieve_prop ( name ) : handler_get , handler_set = None , None if name in props_get : handler_get = props_get [ name ] if name in props_set : handler_set = props_set [ name ] return ( name , handler_get , handler_set ) | 6,321 | https://github.com/unbit/davvy/blob/d9cd95fba25dbc76d80955bbbe5ff9d7cf52268a/davvy/__init__.py#L20-L31 | [
"def",
"from_manifest",
"(",
"app",
",",
"filename",
",",
"raw",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"cfg",
"=",
"current_app",
".",
"config",
"if",
"current_app",
".",
"config",
".",
"get",
"(",
"'TESTING'",
")",
":",
"return",
"# Do not spend time here when testing",
"path",
"=",
"_manifests",
"[",
"app",
"]",
"[",
"filename",
"]",
"if",
"not",
"raw",
"and",
"cfg",
".",
"get",
"(",
"'CDN_DOMAIN'",
")",
"and",
"not",
"cfg",
".",
"get",
"(",
"'CDN_DEBUG'",
")",
":",
"scheme",
"=",
"'https'",
"if",
"cfg",
".",
"get",
"(",
"'CDN_HTTPS'",
")",
"else",
"request",
".",
"scheme",
"prefix",
"=",
"'{}://'",
".",
"format",
"(",
"scheme",
")",
"if",
"not",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"# CDN_DOMAIN has no trailing slash",
"path",
"=",
"'/'",
"+",
"path",
"return",
"''",
".",
"join",
"(",
"(",
"prefix",
",",
"cfg",
"[",
"'CDN_DOMAIN'",
"]",
",",
"path",
")",
")",
"elif",
"not",
"raw",
"and",
"kwargs",
".",
"get",
"(",
"'external'",
",",
"False",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"# request.host_url has a trailing slash",
"path",
"=",
"path",
"[",
"1",
":",
"]",
"return",
"''",
".",
"join",
"(",
"(",
"request",
".",
"host_url",
",",
"path",
")",
")",
"return",
"path"
] |
Parameters are already validated in the QuerySetPermission | def get_queryset ( self ) : model_type = self . request . GET . get ( "type" ) pk = self . request . GET . get ( "id" ) content_type_model = ContentType . objects . get ( model = model_type . lower ( ) ) Model = content_type_model . model_class ( ) model_obj = Model . objects . filter ( id = pk ) . first ( ) return Comment . objects . filter_by_object ( model_obj ) | 6,322 | https://github.com/Radi85/Comment/blob/c3c46afe51228cd7ee4e04f5e6164fff1be3a5bc/comment/api/views.py#L34-L43 | [
"def",
"remove_stale_javascripts",
"(",
"portal",
")",
":",
"logger",
".",
"info",
"(",
"\"Removing stale javascripts ...\"",
")",
"for",
"js",
"in",
"JAVASCRIPTS_TO_REMOVE",
":",
"logger",
".",
"info",
"(",
"\"Unregistering JS %s\"",
"%",
"js",
")",
"portal",
".",
"portal_javascripts",
".",
"unregisterResource",
"(",
"js",
")"
] |
extract zip or tar content to dstdir | def extractall ( archive , filename , dstdir ) : if zipfile . is_zipfile ( archive ) : z = zipfile . ZipFile ( archive ) for name in z . namelist ( ) : targetname = name # directories ends with '/' (on Windows as well) if targetname . endswith ( '/' ) : targetname = targetname [ : - 1 ] # don't include leading "/" from file name if present if targetname . startswith ( os . path . sep ) : targetname = os . path . join ( dstdir , targetname [ 1 : ] ) else : targetname = os . path . join ( dstdir , targetname ) targetname = os . path . normpath ( targetname ) # Create all upper directories if necessary. upperdirs = os . path . dirname ( targetname ) if upperdirs and not os . path . exists ( upperdirs ) : os . makedirs ( upperdirs ) # directories ends with '/' (on Windows as well) if not name . endswith ( '/' ) : # copy file file ( targetname , 'wb' ) . write ( z . read ( name ) ) elif tarfile . is_tarfile ( archive ) : tar = tarfile . open ( archive ) tar . extractall ( path = dstdir ) else : # seems to be a single file, save it shutil . copyfile ( archive , os . path . join ( dstdir , filename ) ) | 6,323 | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/lib/archivefile.py#L22-L55 | [
"def",
"create_stream_subscription",
"(",
"self",
",",
"stream",
",",
"on_data",
",",
"timeout",
"=",
"60",
")",
":",
"options",
"=",
"rest_pb2",
".",
"StreamSubscribeRequest",
"(",
")",
"options",
".",
"stream",
"=",
"stream",
"manager",
"=",
"WebSocketSubscriptionManager",
"(",
"self",
".",
"_client",
",",
"resource",
"=",
"'stream'",
",",
"options",
"=",
"options",
")",
"# Represent subscription as a future",
"subscription",
"=",
"WebSocketSubscriptionFuture",
"(",
"manager",
")",
"wrapped_callback",
"=",
"functools",
".",
"partial",
"(",
"_wrap_callback_parse_stream_data",
",",
"subscription",
",",
"on_data",
")",
"manager",
".",
"open",
"(",
"wrapped_callback",
",",
"instance",
"=",
"self",
".",
"_instance",
")",
"# Wait until a reply or exception is received",
"subscription",
".",
"reply",
"(",
"timeout",
"=",
"timeout",
")",
"return",
"subscription"
] |
Call into the merge_js module to merge the js files and minify the code . | def _merge_js ( input_file , input_dir , output_file ) : from studio . lib . buildjs import merge_js merge_js . main ( input_file , input_dir , output_file ) | 6,324 | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/websetup.py#L208-L212 | [
"def",
"set_raw_datadir",
"(",
"self",
",",
"directory",
"=",
"None",
")",
":",
"if",
"directory",
"is",
"None",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"no directory name given\"",
")",
"return",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"directory",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"directory",
")",
"self",
".",
"logger",
".",
"info",
"(",
"\"directory does not exist\"",
")",
"return",
"self",
".",
"raw_datadir",
"=",
"directory"
] |
Utility function to set up brightway2 to work correctly with lcopt . | def lcopt_bw2_setup ( ecospold_path , overwrite = False , db_name = None ) : # pragma: no cover default_ei_name = "Ecoinvent3_3_cutoff" if db_name is None : db_name = DEFAULT_PROJECT_STEM + default_ei_name if db_name in bw2 . projects : if overwrite : bw2 . projects . delete_project ( name = db_name , delete_dir = True ) else : print ( 'Looks like bw2 is already set up - if you want to overwrite the existing version run lcopt.utils.lcopt_bw2_setup in a python shell using overwrite = True' ) return False bw2 . projects . set_current ( db_name ) bw2 . bw2setup ( ) ei = bw2 . SingleOutputEcospold2Importer ( fix_mac_path_escapes ( ecospold_path ) , default_ei_name ) ei . apply_strategies ( ) ei . statistics ( ) ei . write_database ( ) return True | 6,325 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/utils.py#L38-L77 | [
"def",
"remove_unsafe_chars",
"(",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"six",
".",
"string_types",
")",
":",
"text",
"=",
"UNSAFE_RE",
".",
"sub",
"(",
"''",
",",
"text",
")",
"return",
"text"
] |
Utility function to automatically set up brightway2 to work correctly with lcopt . | def lcopt_bw2_autosetup ( ei_username = None , ei_password = None , write_config = None , ecoinvent_version = '3.3' , ecoinvent_system_model = "cutoff" , overwrite = False ) : ei_name = "Ecoinvent{}_{}_{}" . format ( * ecoinvent_version . split ( '.' ) , ecoinvent_system_model ) config = check_for_config ( ) # If, for some reason, there's no config file, write the defaults if config is None : config = DEFAULT_CONFIG with open ( storage . config_file , "w" ) as cfg : yaml . dump ( config , cfg , default_flow_style = False ) store_option = storage . project_type # Check if there's already a project set up that matches the current configuration if store_option == 'single' : project_name = storage . single_project_name if bw2_project_exists ( project_name ) : bw2 . projects . set_current ( project_name ) if ei_name in bw2 . databases and overwrite == False : #print ('{} is already set up'.format(ei_name)) return True else : # default to 'unique' project_name = DEFAULT_PROJECT_STEM + ei_name if bw2_project_exists ( project_name ) : if overwrite : bw2 . projects . delete_project ( name = project_name , delete_dir = True ) auto_ecoinvent = partial ( eidl . get_ecoinvent , db_name = ei_name , auto_write = True , version = ecoinvent_version , system_model = ecoinvent_system_model ) # check for a config file (lcopt_config.yml) if config is not None : if "ecoinvent" in config : if ei_username is None : ei_username = config [ 'ecoinvent' ] . get ( 'username' ) if ei_password is None : ei_password = config [ 'ecoinvent' ] . get ( 'password' ) write_config = False if ei_username is None : ei_username = input ( 'ecoinvent username: ' ) if ei_password is None : ei_password = getpass . getpass ( 'ecoinvent password: ' ) if write_config is None : write_config = input ( 'store username and password on this computer? y/[n]' ) in [ 'y' , 'Y' , 'yes' , 'YES' , 'Yes' ] if write_config : config [ 'ecoinvent' ] = { 'username' : ei_username , 'password' : ei_password } with open ( storage . config_file , "w" ) as cfg : yaml . dump ( config , cfg , default_flow_style = False ) # no need to keep running bw2setup - we can just copy a blank project which has been set up before if store_option == 'single' : if bw2_project_exists ( project_name ) : bw2 . projects . set_current ( project_name ) else : if not bw2_project_exists ( DEFAULT_BIOSPHERE_PROJECT ) : bw2 . projects . set_current ( project_name ) bw2 . bw2setup ( ) else : bw2 . projects . set_current ( DEFAULT_BIOSPHERE_PROJECT ) bw2 . create_core_migrations ( ) bw2 . projects . copy_project ( project_name , switch = True ) else : #if store_option == 'unique': if not bw2_project_exists ( DEFAULT_BIOSPHERE_PROJECT ) : lcopt_biosphere_setup ( ) bw2 . projects . set_current ( DEFAULT_BIOSPHERE_PROJECT ) bw2 . create_core_migrations ( ) bw2 . projects . copy_project ( project_name , switch = True ) if ei_username is not None and ei_password is not None : auto_ecoinvent ( username = ei_username , password = ei_password ) else : auto_ecoinvent ( ) write_search_index ( project_name , ei_name , overwrite = overwrite ) return True | 6,326 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/utils.py#L123-L228 | [
"def",
"remove_unsafe_chars",
"(",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"six",
".",
"string_types",
")",
":",
"text",
"=",
"UNSAFE_RE",
".",
"sub",
"(",
"''",
",",
"text",
")",
"return",
"text"
] |
Autodownloader for forwast database package for brightway . Used by lcopt_bw2_forwast_setup to get the database data . Not designed to be used on its own | def forwast_autodownload ( FORWAST_URL ) : dirpath = tempfile . mkdtemp ( ) r = requests . get ( FORWAST_URL ) z = zipfile . ZipFile ( io . BytesIO ( r . content ) ) z . extractall ( dirpath ) return os . path . join ( dirpath , 'forwast.bw2package' ) | 6,327 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/utils.py#L288-L297 | [
"def",
"resume",
"(",
"self",
",",
"instance_id",
")",
":",
"nt_ks",
"=",
"self",
".",
"compute_conn",
"response",
"=",
"nt_ks",
".",
"servers",
".",
"resume",
"(",
"instance_id",
")",
"return",
"True"
] |
Utility function to set up brightway2 to work correctly with lcopt using the FORWAST database instead of ecoinvent | def lcopt_bw2_forwast_setup ( use_autodownload = True , forwast_path = None , db_name = FORWAST_PROJECT_NAME , overwrite = False ) : if use_autodownload : forwast_filepath = forwast_autodownload ( FORWAST_URL ) elif forwast_path is not None : forwast_filepath = forwast_path else : raise ValueError ( 'Need a path if not using autodownload' ) if storage . project_type == 'single' : db_name = storage . single_project_name if bw2_project_exists ( db_name ) : bw2 . projects . set_current ( db_name ) else : bw2 . projects . set_current ( db_name ) bw2 . bw2setup ( ) else : if db_name in bw2 . projects : if overwrite : bw2 . projects . delete_project ( name = db_name , delete_dir = True ) else : print ( 'Looks like bw2 is already set up for the FORWAST database - if you want to overwrite the existing version run lcopt.utils.lcopt_bw2_forwast_setup in a python shell using overwrite = True' ) return False # no need to keep running bw2setup - we can just copy a blank project which has been set up before if not bw2_project_exists ( DEFAULT_BIOSPHERE_PROJECT ) : lcopt_biosphere_setup ( ) bw2 . projects . set_current ( DEFAULT_BIOSPHERE_PROJECT ) bw2 . create_core_migrations ( ) bw2 . projects . copy_project ( db_name , switch = True ) bw2 . BW2Package . import_file ( forwast_filepath ) return True | 6,328 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/utils.py#L300-L350 | [
"def",
"get_perturbation",
"(",
"ts",
",",
"axis",
"=",
"-",
"1",
")",
":",
"slices",
"=",
"[",
"slice",
"(",
"None",
")",
"]",
"*",
"ts",
".",
"ndim",
"slices",
"[",
"axis",
"]",
"=",
"None",
"mean",
"=",
"ts",
".",
"mean",
"(",
"axis",
"=",
"axis",
")",
"[",
"tuple",
"(",
"slices",
")",
"]",
"return",
"ts",
"-",
"mean"
] |
Validate Samples and Factors identifiers across the file . | def _validate_samples_factors ( mwtabfile , validate_samples = True , validate_factors = True ) : from_subject_samples = { i [ "local_sample_id" ] for i in mwtabfile [ "SUBJECT_SAMPLE_FACTORS" ] [ "SUBJECT_SAMPLE_FACTORS" ] } from_subject_factors = { i [ "factors" ] for i in mwtabfile [ "SUBJECT_SAMPLE_FACTORS" ] [ "SUBJECT_SAMPLE_FACTORS" ] } if validate_samples : if "MS_METABOLITE_DATA" in mwtabfile : from_metabolite_data_samples = set ( mwtabfile [ "MS_METABOLITE_DATA" ] [ "MS_METABOLITE_DATA_START" ] [ "Samples" ] ) assert from_subject_samples == from_metabolite_data_samples if "NMR_BINNED_DATA" in mwtabfile : from_nmr_binned_data_samples = set ( mwtabfile [ "NMR_BINNED_DATA" ] [ "NMR_BINNED_DATA_START" ] [ "Fields" ] [ 1 : ] ) assert from_subject_samples == from_nmr_binned_data_samples if validate_factors : if "MS_METABOLITE_DATA" in mwtabfile : from_metabolite_data_factors = set ( mwtabfile [ "MS_METABOLITE_DATA" ] [ "MS_METABOLITE_DATA_START" ] [ "Factors" ] ) assert from_subject_factors == from_metabolite_data_factors | 6,329 | https://github.com/MoseleyBioinformaticsLab/mwtab/blob/8c0ae8ab2aa621662f99589ed41e481cf8b7152b/mwtab/validator.py#L19-L44 | [
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"returnJson",
"=",
"(",
"request",
".",
"POST",
".",
"get",
"(",
"'json'",
")",
"in",
"[",
"'true'",
",",
"True",
"]",
")",
"regonline",
"=",
"getConstant",
"(",
"'registration__registrationEnabled'",
")",
"if",
"not",
"regonline",
":",
"returnUrl",
"=",
"reverse",
"(",
"'registrationOffline'",
")",
"if",
"self",
".",
"returnJson",
":",
"return",
"JsonResponse",
"(",
"{",
"'status'",
":",
"'success'",
",",
"'redirect'",
":",
"returnUrl",
"}",
")",
"return",
"HttpResponseRedirect",
"(",
"returnUrl",
")",
"return",
"super",
"(",
")",
".",
"dispatch",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Double - fork magic | def daemonize ( self ) : if self . userid : uid = pwd . getpwnam ( self . userid ) . pw_uid os . seteuid ( uid ) try : pid = os . fork ( ) if pid > 0 : sys . exit ( 0 ) except OSError as err : sys . stderr . write ( "First fork failed: {0} ({1})\n" . format ( err . errno , err . strerror ) ) sys . exit ( 1 ) # decouple from parent environment os . chdir ( "/" ) os . setsid ( ) os . umask ( 0 ) # Second fork try : pid = os . fork ( ) if pid > 0 : sys . exit ( 0 ) except OSError as err : sys . stderr . write ( "Second fork failed: {0} ({1})\n" . format ( err . errno , err . strerror ) ) sys . exit ( 1 ) sys . stdout . flush ( ) sys . stderr . flush ( ) si = open ( self . stdin , 'r' ) so = open ( self . stdout , 'w' ) se = open ( self . stderr , 'w' ) os . dup2 ( si . fileno ( ) , sys . stdin . fileno ( ) ) os . dup2 ( so . fileno ( ) , sys . stdout . fileno ( ) ) os . dup2 ( se . fileno ( ) , sys . stderr . fileno ( ) ) # write PID file atexit . register ( self . delpid ) pid = str ( os . getpid ( ) ) open ( self . pidfile , 'w' ) . write ( "%s\n" % pid ) | 6,330 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/proxy/__init__.py#L38-L77 | [
"def",
"json_to_url",
"(",
"json",
",",
"symbol",
")",
":",
"start",
"=",
"json",
"[",
"0",
"]",
"[",
"'date'",
"]",
"end",
"=",
"json",
"[",
"-",
"1",
"]",
"[",
"'date'",
"]",
"diff",
"=",
"end",
"-",
"start",
"# Get period by a ratio from calculated period to valid periods",
"# Ratio closest to 1 is the period",
"# Valid values: 300, 900, 1800, 7200, 14400, 86400",
"periods",
"=",
"[",
"300",
",",
"900",
",",
"1800",
",",
"7200",
",",
"14400",
",",
"86400",
"]",
"diffs",
"=",
"{",
"}",
"for",
"p",
"in",
"periods",
":",
"diffs",
"[",
"p",
"]",
"=",
"abs",
"(",
"1",
"-",
"(",
"p",
"/",
"(",
"diff",
"/",
"len",
"(",
"json",
")",
")",
")",
")",
"# Get ratio",
"period",
"=",
"min",
"(",
"diffs",
",",
"key",
"=",
"diffs",
".",
"get",
")",
"# Find closest period",
"url",
"=",
"(",
"'https://poloniex.com/public?command'",
"'=returnChartData¤cyPair={0}&start={1}'",
"'&end={2}&period={3}'",
")",
".",
"format",
"(",
"symbol",
",",
"start",
",",
"end",
",",
"period",
")",
"return",
"url"
] |
Render a Tropo object into a Json string . | def RenderJson ( self , pretty = False ) : steps = self . _steps topdict = { } topdict [ 'tropo' ] = steps if pretty : try : json = jsonlib . dumps ( topdict , indent = 4 , sort_keys = False ) except TypeError : json = jsonlib . dumps ( topdict ) else : json = jsonlib . dumps ( topdict ) return json | 6,331 | https://github.com/tropo/tropo-webapi-python/blob/f87772644a6b45066a4c5218f0c1f6467b64ab3c/build/lib/tropo.py#L864-L878 | [
"def",
"_linreg_future",
"(",
"self",
",",
"series",
",",
"since",
",",
"days",
"=",
"20",
")",
":",
"last_days",
"=",
"pd",
".",
"date_range",
"(",
"end",
"=",
"since",
",",
"periods",
"=",
"days",
")",
"hist",
"=",
"self",
".",
"history",
"(",
"last_days",
")",
"xi",
"=",
"np",
".",
"array",
"(",
"map",
"(",
"dt2ts",
",",
"hist",
".",
"index",
")",
")",
"A",
"=",
"np",
".",
"array",
"(",
"[",
"xi",
",",
"np",
".",
"ones",
"(",
"len",
"(",
"hist",
")",
")",
"]",
")",
"y",
"=",
"hist",
".",
"values",
"w",
"=",
"np",
".",
"linalg",
".",
"lstsq",
"(",
"A",
".",
"T",
",",
"y",
")",
"[",
"0",
"]",
"for",
"d",
"in",
"series",
".",
"index",
"[",
"series",
".",
"index",
">",
"since",
"]",
":",
"series",
"[",
"d",
"]",
"=",
"w",
"[",
"0",
"]",
"*",
"dt2ts",
"(",
"d",
")",
"+",
"w",
"[",
"1",
"]",
"series",
"[",
"d",
"]",
"=",
"0",
"if",
"series",
"[",
"d",
"]",
"<",
"0",
"else",
"series",
"[",
"d",
"]",
"return",
"series"
] |
Get the value of the indexed Tropo action . | def getIndexedValue ( self , index ) : actions = self . _actions if ( type ( actions ) is list ) : dict = actions [ index ] else : dict = actions return dict . get ( 'value' , 'NoValue' ) | 6,332 | https://github.com/tropo/tropo-webapi-python/blob/f87772644a6b45066a4c5218f0c1f6467b64ab3c/tropo.py#L724-L734 | [
"def",
"random_connection",
"(",
"self",
")",
":",
"# While at the moment there's no need for this to be a context manager",
"# per se, I would like to use that interface since I anticipate",
"# adding some wrapping around it at some point.",
"yield",
"random",
".",
"choice",
"(",
"[",
"conn",
"for",
"conn",
"in",
"self",
".",
"connections",
"(",
")",
"if",
"conn",
".",
"alive",
"(",
")",
"]",
")"
] |
Get the value of the named Tropo action . | def getNamedActionValue ( self , name ) : actions = self . _actions if ( type ( actions ) is list ) : for a in actions : if a . get ( 'name' , 'NoValue' ) == name : dict = a else : dict = actions return dict . get ( 'value' , 'NoValue' ) | 6,333 | https://github.com/tropo/tropo-webapi-python/blob/f87772644a6b45066a4c5218f0c1f6467b64ab3c/tropo.py#L736-L748 | [
"def",
"random_connection",
"(",
"self",
")",
":",
"# While at the moment there's no need for this to be a context manager",
"# per se, I would like to use that interface since I anticipate",
"# adding some wrapping around it at some point.",
"yield",
"random",
".",
"choice",
"(",
"[",
"conn",
"for",
"conn",
"in",
"self",
".",
"connections",
"(",
")",
"if",
"conn",
".",
"alive",
"(",
")",
"]",
")"
] |
Stop subprocess whose process id is pid . | def stop_subprocess ( pid ) : if hasattr ( os , "kill" ) : import signal os . kill ( pid , signal . SIGTERM ) else : import win32api pid = win32api . OpenProcess ( 1 , 0 , pid ) win32api . TerminateProcess ( pid , 0 ) os . waitpid ( pid , 0 ) | 6,334 | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/lib/os_utils.py#L23-L32 | [
"def",
"generate_http_manifest",
"(",
"self",
")",
":",
"base_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"translate_path",
"(",
"self",
".",
"path",
")",
")",
"self",
".",
"dataset",
"=",
"dtoolcore",
".",
"DataSet",
".",
"from_uri",
"(",
"base_path",
")",
"admin_metadata_fpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base_path",
",",
"\".dtool\"",
",",
"\"dtool\"",
")",
"with",
"open",
"(",
"admin_metadata_fpath",
")",
"as",
"fh",
":",
"admin_metadata",
"=",
"json",
".",
"load",
"(",
"fh",
")",
"http_manifest",
"=",
"{",
"\"admin_metadata\"",
":",
"admin_metadata",
",",
"\"manifest_url\"",
":",
"self",
".",
"generate_url",
"(",
"\".dtool/manifest.json\"",
")",
",",
"\"readme_url\"",
":",
"self",
".",
"generate_url",
"(",
"\"README.yml\"",
")",
",",
"\"overlays\"",
":",
"self",
".",
"generate_overlay_urls",
"(",
")",
",",
"\"item_urls\"",
":",
"self",
".",
"generate_item_urls",
"(",
")",
"}",
"return",
"bytes",
"(",
"json",
".",
"dumps",
"(",
"http_manifest",
")",
",",
"\"utf-8\"",
")"
] |
generate absolute path for the given file and base dir | def file2abspath ( filename , this_file = __file__ ) : return os . path . abspath ( os . path . join ( os . path . dirname ( os . path . abspath ( this_file ) ) , filename ) ) | 6,335 | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L28-L33 | [
"def",
"updateSeriesRegistrationStatus",
"(",
")",
":",
"from",
".",
"models",
"import",
"Series",
"if",
"not",
"getConstant",
"(",
"'general__enableCronTasks'",
")",
":",
"return",
"logger",
".",
"info",
"(",
"'Checking status of Series that are open for registration.'",
")",
"open_series",
"=",
"Series",
".",
"objects",
".",
"filter",
"(",
")",
".",
"filter",
"(",
"*",
"*",
"{",
"'registrationOpen'",
":",
"True",
"}",
")",
"for",
"series",
"in",
"open_series",
":",
"series",
".",
"updateRegistrationStatus",
"(",
")"
] |
save a line | def file2json ( filename , encoding = 'utf-8' ) : with codecs . open ( filename , "r" , encoding = encoding ) as f : return json . load ( f ) | 6,336 | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L39-L44 | [
"def",
"get_bars",
"(",
"self",
",",
"assets",
",",
"data_frequency",
",",
"bar_count",
"=",
"500",
")",
":",
"assets_is_scalar",
"=",
"not",
"isinstance",
"(",
"assets",
",",
"(",
"list",
",",
"set",
",",
"tuple",
")",
")",
"is_daily",
"=",
"'d'",
"in",
"data_frequency",
"# 'daily' or '1d'",
"if",
"assets_is_scalar",
":",
"symbols",
"=",
"[",
"assets",
".",
"symbol",
"]",
"else",
":",
"symbols",
"=",
"[",
"asset",
".",
"symbol",
"for",
"asset",
"in",
"assets",
"]",
"symbol_bars",
"=",
"self",
".",
"_symbol_bars",
"(",
"symbols",
",",
"'day'",
"if",
"is_daily",
"else",
"'minute'",
",",
"limit",
"=",
"bar_count",
")",
"if",
"is_daily",
":",
"intra_bars",
"=",
"{",
"}",
"symbol_bars_minute",
"=",
"self",
".",
"_symbol_bars",
"(",
"symbols",
",",
"'minute'",
",",
"limit",
"=",
"1000",
")",
"for",
"symbol",
",",
"df",
"in",
"symbol_bars_minute",
".",
"items",
"(",
")",
":",
"agged",
"=",
"df",
".",
"resample",
"(",
"'1D'",
")",
".",
"agg",
"(",
"dict",
"(",
"open",
"=",
"'first'",
",",
"high",
"=",
"'max'",
",",
"low",
"=",
"'min'",
",",
"close",
"=",
"'last'",
",",
"volume",
"=",
"'sum'",
",",
")",
")",
".",
"dropna",
"(",
")",
"intra_bars",
"[",
"symbol",
"]",
"=",
"agged",
"dfs",
"=",
"[",
"]",
"for",
"asset",
"in",
"assets",
"if",
"not",
"assets_is_scalar",
"else",
"[",
"assets",
"]",
":",
"symbol",
"=",
"asset",
".",
"symbol",
"df",
"=",
"symbol_bars",
".",
"get",
"(",
"symbol",
")",
"if",
"df",
"is",
"None",
":",
"dfs",
".",
"append",
"(",
"pd",
".",
"DataFrame",
"(",
"[",
"]",
",",
"columns",
"=",
"[",
"'open'",
",",
"'high'",
",",
"'low'",
",",
"'close'",
",",
"'volume'",
"]",
")",
")",
"continue",
"if",
"is_daily",
":",
"agged",
"=",
"intra_bars",
".",
"get",
"(",
"symbol",
")",
"if",
"agged",
"is",
"not",
"None",
"and",
"len",
"(",
"agged",
".",
"index",
")",
">",
"0",
"and",
"agged",
".",
"index",
"[",
"-",
"1",
"]",
"not",
"in",
"df",
".",
"index",
":",
"if",
"not",
"(",
"agged",
".",
"index",
"[",
"-",
"1",
"]",
">",
"df",
".",
"index",
"[",
"-",
"1",
"]",
")",
":",
"log",
".",
"warn",
"(",
"(",
"'agged.index[-1] = {}, df.index[-1] = {} '",
"'for {}'",
")",
".",
"format",
"(",
"agged",
".",
"index",
"[",
"-",
"1",
"]",
",",
"df",
".",
"index",
"[",
"-",
"1",
"]",
",",
"symbol",
")",
")",
"df",
"=",
"df",
".",
"append",
"(",
"agged",
".",
"iloc",
"[",
"-",
"1",
"]",
")",
"df",
".",
"columns",
"=",
"pd",
".",
"MultiIndex",
".",
"from_product",
"(",
"[",
"[",
"asset",
",",
"]",
",",
"df",
".",
"columns",
"]",
")",
"dfs",
".",
"append",
"(",
"df",
")",
"return",
"pd",
".",
"concat",
"(",
"dfs",
",",
"axis",
"=",
"1",
")"
] |
json stream parsing or line parsing | def file2iter ( filename , encoding = 'utf-8' , comment_prefix = "#" , skip_empty_line = True ) : ret = list ( ) visited = set ( ) with codecs . open ( filename , encoding = encoding ) as f : for line in f : line = line . strip ( ) # skip empty line if skip_empty_line and len ( line ) == 0 : continue # skip comment line if comment_prefix and line . startswith ( comment_prefix ) : continue yield line | 6,337 | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L47-L65 | [
"def",
"get_kmgraph_meta",
"(",
"mapper_summary",
")",
":",
"d",
"=",
"mapper_summary",
"[",
"\"custom_meta\"",
"]",
"meta",
"=",
"(",
"\"<b>N_cubes:</b> \"",
"+",
"str",
"(",
"d",
"[",
"\"n_cubes\"",
"]",
")",
"+",
"\" <b>Perc_overlap:</b> \"",
"+",
"str",
"(",
"d",
"[",
"\"perc_overlap\"",
"]",
")",
")",
"meta",
"+=",
"(",
"\"<br><b>Nodes:</b> \"",
"+",
"str",
"(",
"mapper_summary",
"[",
"\"n_nodes\"",
"]",
")",
"+",
"\" <b>Edges:</b> \"",
"+",
"str",
"(",
"mapper_summary",
"[",
"\"n_edges\"",
"]",
")",
"+",
"\" <b>Total samples:</b> \"",
"+",
"str",
"(",
"mapper_summary",
"[",
"\"n_total\"",
"]",
")",
"+",
"\" <b>Unique_samples:</b> \"",
"+",
"str",
"(",
"mapper_summary",
"[",
"\"n_unique\"",
"]",
")",
")",
"return",
"meta"
] |
write json in canonical json format | def json2file ( data , filename , encoding = 'utf-8' ) : with codecs . open ( filename , "w" , encoding = encoding ) as f : json . dump ( data , f , ensure_ascii = False , indent = 4 , sort_keys = True ) | 6,338 | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L71-L76 | [
"def",
"catFiles",
"(",
"filesToCat",
",",
"catFile",
")",
":",
"if",
"len",
"(",
"filesToCat",
")",
"==",
"0",
":",
"#We must handle this case or the cat call will hang waiting for input",
"open",
"(",
"catFile",
",",
"'w'",
")",
".",
"close",
"(",
")",
"return",
"maxCat",
"=",
"25",
"system",
"(",
"\"cat %s > %s\"",
"%",
"(",
"\" \"",
".",
"join",
"(",
"filesToCat",
"[",
":",
"maxCat",
"]",
")",
",",
"catFile",
")",
")",
"filesToCat",
"=",
"filesToCat",
"[",
"maxCat",
":",
"]",
"while",
"len",
"(",
"filesToCat",
")",
">",
"0",
":",
"system",
"(",
"\"cat %s >> %s\"",
"%",
"(",
"\" \"",
".",
"join",
"(",
"filesToCat",
"[",
":",
"maxCat",
"]",
")",
",",
"catFile",
")",
")",
"filesToCat",
"=",
"filesToCat",
"[",
"maxCat",
":",
"]"
] |
write json stream write lines too | def lines2file ( lines , filename , encoding = 'utf-8' ) : with codecs . open ( filename , "w" , encoding = encoding ) as f : for line in lines : f . write ( line ) f . write ( "\n" ) | 6,339 | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L79-L86 | [
"def",
"load",
"(",
"self",
",",
"filename",
")",
":",
"LOGGER",
".",
"info",
"(",
"\"Loading result from '%s'.\"",
",",
"filename",
")",
"if",
"filename",
".",
"endswith",
"(",
"\".gz\"",
")",
":",
"with",
"gzip",
".",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"file_handle",
":",
"result",
"=",
"MemoteResult",
"(",
"json",
".",
"loads",
"(",
"file_handle",
".",
"read",
"(",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
")",
"else",
":",
"with",
"open",
"(",
"filename",
",",
"\"r\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"file_handle",
":",
"result",
"=",
"MemoteResult",
"(",
"json",
".",
"load",
"(",
"file_handle",
")",
")",
"# TODO (Moritz Beber): Validate the read-in JSON maybe? Trade-off",
"# between extra time taken and correctness. Maybe we re-visit this",
"# issue when there was a new JSON format version needed.",
"return",
"result"
] |
json array to file canonical json format | def items2file ( items , filename , encoding = 'utf-8' , modifier = 'w' ) : with codecs . open ( filename , modifier , encoding = encoding ) as f : for item in items : f . write ( u"{}\n" . format ( json . dumps ( item , ensure_ascii = False , sort_keys = True ) ) ) | 6,340 | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L89-L96 | [
"def",
"perturbParams",
"(",
"self",
",",
"pertSize",
"=",
"1e-3",
")",
":",
"params",
"=",
"self",
".",
"getParams",
"(",
")",
"self",
".",
"setParams",
"(",
"params",
"+",
"pertSize",
"*",
"sp",
".",
"randn",
"(",
"params",
".",
"shape",
"[",
"0",
"]",
")",
")"
] |
Convert a voluptuous schema to a dictionary . | def convert ( schema ) : # pylint: disable=too-many-return-statements,too-many-branches if isinstance ( schema , vol . Schema ) : schema = schema . schema if isinstance ( schema , Mapping ) : val = [ ] for key , value in schema . items ( ) : description = None if isinstance ( key , vol . Marker ) : pkey = key . schema description = key . description else : pkey = key pval = convert ( value ) pval [ 'name' ] = pkey if description is not None : pval [ 'description' ] = description if isinstance ( key , ( vol . Required , vol . Optional ) ) : pval [ key . __class__ . __name__ . lower ( ) ] = True if key . default is not vol . UNDEFINED : pval [ 'default' ] = key . default ( ) val . append ( pval ) return val if isinstance ( schema , vol . All ) : val = { } for validator in schema . validators : val . update ( convert ( validator ) ) return val if isinstance ( schema , ( vol . Clamp , vol . Range ) ) : val = { } if schema . min is not None : val [ 'valueMin' ] = schema . min if schema . max is not None : val [ 'valueMax' ] = schema . max return val if isinstance ( schema , vol . Length ) : val = { } if schema . min is not None : val [ 'lengthMin' ] = schema . min if schema . max is not None : val [ 'lengthMax' ] = schema . max return val if isinstance ( schema , vol . Datetime ) : return { 'type' : 'datetime' , 'format' : schema . format , } if isinstance ( schema , vol . In ) : if isinstance ( schema . container , Mapping ) : return { 'type' : 'select' , 'options' : list ( schema . container . items ( ) ) , } return { 'type' : 'select' , 'options' : [ ( item , item ) for item in schema . container ] } if schema in ( vol . Lower , vol . Upper , vol . Capitalize , vol . Title , vol . Strip ) : return { schema . __name__ . lower ( ) : True , } if isinstance ( schema , vol . Coerce ) : schema = schema . type if schema in TYPES_MAP : return { 'type' : TYPES_MAP [ schema ] } raise ValueError ( 'Unable to convert schema: {}' . format ( schema ) ) | 6,341 | https://github.com/balloob/voluptuous-serialize/blob/02992eb3128063d065048cdcbfb907efe0a53b99/voluptuous_serialize/__init__.py#L15-L97 | [
"def",
"itemconfigure",
"(",
"self",
",",
"iid",
",",
"rectangle_options",
",",
"text_options",
")",
":",
"rectangle_id",
",",
"text_id",
"=",
"self",
".",
"_markers",
"[",
"iid",
"]",
"[",
"\"rectangle_id\"",
"]",
",",
"self",
".",
"_markers",
"[",
"iid",
"]",
"[",
"\"text_id\"",
"]",
"if",
"len",
"(",
"rectangle_options",
")",
"!=",
"0",
":",
"self",
".",
"_timeline",
".",
"itemconfigure",
"(",
"rectangle_id",
",",
"*",
"*",
"rectangle_options",
")",
"if",
"len",
"(",
"text_options",
")",
"!=",
"0",
":",
"self",
".",
"_timeline",
".",
"itemconfigure",
"(",
"text_id",
",",
"*",
"*",
"text_options",
")"
] |
Compares two versions | def version_cmp ( version_a , version_b ) : a = normalize_version ( version_a ) b = normalize_version ( version_b ) i_a = a [ 0 ] * 100 + a [ 1 ] * 10 + a [ 0 ] * 1 i_b = b [ 0 ] * 100 + b [ 1 ] * 10 + b [ 0 ] * 1 return i_a - i_b | 6,342 | https://github.com/jpgxs/pyopsview/blob/5bbef35e463eda6dc67b0c34d3633a5a1c75a932/pyopsview/utils.py#L52-L60 | [
"def",
"not_storable",
"(",
"_type",
")",
":",
"return",
"Storable",
"(",
"_type",
",",
"handlers",
"=",
"StorableHandler",
"(",
"poke",
"=",
"fake_poke",
",",
"peek",
"=",
"fail_peek",
"(",
"_type",
")",
")",
")"
] |
Returns the HTTP response header field case insensitively | def getheader ( self , field , default = '' ) : if self . headers : for header in self . headers : if field . lower ( ) == header . lower ( ) : return self . headers [ header ] return default | 6,343 | https://github.com/uw-it-aca/uw-restclients-core/blob/fda9380dceb6355ec6a3123e88c9ec66ae992682/restclients_core/models/__init__.py#L30-L39 | [
"def",
"avail_sizes",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_sizes function must be called with '",
"'-f or --function, or with the --list-sizes option'",
")",
"ret",
"=",
"{",
"'block devices'",
":",
"{",
"}",
",",
"'memory'",
":",
"{",
"}",
",",
"'processors'",
":",
"{",
"}",
",",
"}",
"conn",
"=",
"get_conn",
"(",
")",
"response",
"=",
"conn",
".",
"getCreateObjectOptions",
"(",
")",
"for",
"device",
"in",
"response",
"[",
"'blockDevices'",
"]",
":",
"#return device['template']['blockDevices']",
"ret",
"[",
"'block devices'",
"]",
"[",
"device",
"[",
"'itemPrice'",
"]",
"[",
"'item'",
"]",
"[",
"'description'",
"]",
"]",
"=",
"{",
"'name'",
":",
"device",
"[",
"'itemPrice'",
"]",
"[",
"'item'",
"]",
"[",
"'description'",
"]",
",",
"'capacity'",
":",
"device",
"[",
"'template'",
"]",
"[",
"'blockDevices'",
"]",
"[",
"0",
"]",
"[",
"'diskImage'",
"]",
"[",
"'capacity'",
"]",
",",
"}",
"for",
"memory",
"in",
"response",
"[",
"'memory'",
"]",
":",
"ret",
"[",
"'memory'",
"]",
"[",
"memory",
"[",
"'itemPrice'",
"]",
"[",
"'item'",
"]",
"[",
"'description'",
"]",
"]",
"=",
"{",
"'name'",
":",
"memory",
"[",
"'itemPrice'",
"]",
"[",
"'item'",
"]",
"[",
"'description'",
"]",
",",
"'maxMemory'",
":",
"memory",
"[",
"'template'",
"]",
"[",
"'maxMemory'",
"]",
",",
"}",
"for",
"processors",
"in",
"response",
"[",
"'processors'",
"]",
":",
"ret",
"[",
"'processors'",
"]",
"[",
"processors",
"[",
"'itemPrice'",
"]",
"[",
"'item'",
"]",
"[",
"'description'",
"]",
"]",
"=",
"{",
"'name'",
":",
"processors",
"[",
"'itemPrice'",
"]",
"[",
"'item'",
"]",
"[",
"'description'",
"]",
",",
"'start cpus'",
":",
"processors",
"[",
"'template'",
"]",
"[",
"'startCpus'",
"]",
",",
"}",
"return",
"ret"
] |
return true if the character is a letter digit underscore dollar sign or non - ASCII character . | def isAlphanum ( c ) : return ( ( c >= 'a' and c <= 'z' ) or ( c >= '0' and c <= '9' ) or ( c >= 'A' and c <= 'Z' ) or c == '_' or c == '$' or c == '\\' or ( c is not None and ord ( c ) > 126 ) ) | 6,344 | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/lib/buildjs/jsmin.py#L63-L68 | [
"def",
"unblockall",
"(",
"self",
")",
":",
"for",
"q",
"in",
"self",
".",
"queues",
".",
"values",
"(",
")",
":",
"q",
".",
"unblockall",
"(",
")",
"self",
".",
"blockEvents",
".",
"clear",
"(",
")"
] |
return the next character from stdin . Watch out for lookahead . If the character is a control character translate it to a space or linefeed . | def _get ( self ) : c = self . theLookahead self . theLookahead = None if c == None : c = self . instream . read ( 1 ) if c >= ' ' or c == '\n' : return c if c == '' : # EOF return '\000' if c == '\r' : return '\n' return ' ' | 6,345 | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/lib/buildjs/jsmin.py#L86-L101 | [
"def",
"store",
"(",
"self",
",",
"mutagen_file",
",",
"pictures",
")",
":",
"mutagen_file",
".",
"clear_pictures",
"(",
")",
"for",
"pic",
"in",
"pictures",
":",
"mutagen_file",
".",
"add_picture",
"(",
"pic",
")"
] |
Copy the input to the output deleting the characters which are insignificant to JavaScript . Comments will be removed . Tabs will be replaced with spaces . Carriage returns will be replaced with linefeeds . Most spaces and linefeeds will be removed . | def _jsmin ( self ) : self . theA = '\n' self . _action ( 3 ) while self . theA != '\000' : if self . theA == ' ' : if isAlphanum ( self . theB ) : self . _action ( 1 ) else : self . _action ( 2 ) elif self . theA == '\n' : if self . theB in [ '{' , '[' , '(' , '+' , '-' ] : self . _action ( 1 ) elif self . theB == ' ' : self . _action ( 3 ) else : if isAlphanum ( self . theB ) : self . _action ( 1 ) else : self . _action ( 2 ) else : if self . theB == ' ' : if isAlphanum ( self . theA ) : self . _action ( 1 ) else : self . _action ( 3 ) elif self . theB == '\n' : if self . theA in [ '}' , ']' , ')' , '+' , '-' , '"' , '\'' ] : self . _action ( 1 ) else : if isAlphanum ( self . theA ) : self . _action ( 1 ) else : self . _action ( 3 ) else : self . _action ( 1 ) | 6,346 | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/lib/buildjs/jsmin.py#L180-L220 | [
"def",
"GetVShadowStoreByPathSpec",
"(",
"self",
",",
"path_spec",
")",
":",
"store_index",
"=",
"vshadow",
".",
"VShadowPathSpecGetStoreIndex",
"(",
"path_spec",
")",
"if",
"store_index",
"is",
"None",
":",
"return",
"None",
"return",
"self",
".",
"_vshadow_volume",
".",
"get_store",
"(",
"store_index",
")"
] |
Get layertemplates owned by a user from the database . | def _get_lts_from_user ( self , user ) : req = meta . Session . query ( LayerTemplate ) . select_from ( join ( LayerTemplate , User ) ) return req . filter ( User . login == user ) . all ( ) | 6,347 | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/controllers/layertemplates.py#L121-L124 | [
"def",
"restart",
"(",
"self",
",",
"container",
",",
"timeout",
"=",
"10",
")",
":",
"params",
"=",
"{",
"'t'",
":",
"timeout",
"}",
"url",
"=",
"self",
".",
"_url",
"(",
"\"/containers/{0}/restart\"",
",",
"container",
")",
"conn_timeout",
"=",
"self",
".",
"timeout",
"if",
"conn_timeout",
"is",
"not",
"None",
":",
"conn_timeout",
"+=",
"timeout",
"res",
"=",
"self",
".",
"_post",
"(",
"url",
",",
"params",
"=",
"params",
",",
"timeout",
"=",
"conn_timeout",
")",
"self",
".",
"_raise_for_status",
"(",
"res",
")"
] |
Get a layertemplate owned by a user from the database by lt_id . | def _get_lt_from_user_by_id ( self , user , lt_id ) : req = meta . Session . query ( LayerTemplate ) . select_from ( join ( LayerTemplate , User ) ) try : return req . filter ( and_ ( User . login == user , LayerTemplate . id == lt_id ) ) . one ( ) except Exception , e : return None | 6,348 | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/controllers/layertemplates.py#L126-L132 | [
"def",
"_encode_string",
"(",
"string",
")",
":",
"if",
"not",
"isinstance",
"(",
"string",
",",
"bytes",
")",
":",
"string",
"=",
"string",
".",
"encode",
"(",
"'utf8'",
")",
"return",
"ffi",
".",
"new",
"(",
"'char[]'",
",",
"string",
")"
] |
A lexical analyzer for the mwtab formatted files . | def tokenizer ( text ) : stream = deque ( text . split ( "\n" ) ) while len ( stream ) > 0 : line = stream . popleft ( ) if line . startswith ( "#METABOLOMICS WORKBENCH" ) : yield KeyValue ( "#METABOLOMICS WORKBENCH" , "\n" ) yield KeyValue ( "HEADER" , line ) for identifier in line . split ( " " ) : if ":" in identifier : key , value = identifier . split ( ":" ) yield KeyValue ( key , value ) elif line . startswith ( "#ANALYSIS TYPE" ) : yield KeyValue ( "HEADER" , line ) elif line . startswith ( "#SUBJECT_SAMPLE_FACTORS:" ) : yield KeyValue ( "#ENDSECTION" , "\n" ) yield KeyValue ( "#SUBJECT_SAMPLE_FACTORS" , "\n" ) elif line . startswith ( "#" ) : yield KeyValue ( "#ENDSECTION" , "\n" ) yield KeyValue ( line . strip ( ) , "\n" ) elif line . startswith ( "SUBJECT_SAMPLE_FACTORS" ) : key , subject_type , local_sample_id , factors , additional_sample_data = line . split ( "\t" ) # factors = [dict([[i.strip() for i in f.split(":")]]) for f in factors.split("|")] yield SubjectSampleFactors ( key . strip ( ) , subject_type , local_sample_id , factors , additional_sample_data ) elif line . endswith ( "_START" ) : yield KeyValue ( line , "\n" ) while not line . endswith ( "_END" ) : line = stream . popleft ( ) if line . endswith ( "_END" ) : yield KeyValue ( line . strip ( ) , "\n" ) else : data = line . split ( "\t" ) yield KeyValue ( data [ 0 ] , tuple ( data ) ) else : if line : if line . startswith ( "MS:MS_RESULTS_FILE" ) or line . startswith ( "NM:NMR_RESULTS_FILE" ) : try : key , value , extra = line . split ( "\t" ) extra_key , extra_value = extra . strip ( ) . split ( ":" ) yield KeyValueExtra ( key . strip ( ) [ 3 : ] , value , extra_key , extra_value ) except ValueError : key , value = line . split ( "\t" ) yield KeyValue ( key . strip ( ) [ 3 : ] , value ) else : try : key , value = line . split ( "\t" ) if ":" in key : if key . startswith ( "MS_METABOLITE_DATA:UNITS" ) : yield KeyValue ( key . strip ( ) , value ) else : yield KeyValue ( key . strip ( ) [ 3 : ] , value ) else : yield KeyValue ( key . strip ( ) , value ) except ValueError : print ( "LINE WITH ERROR:\n\t" , repr ( line ) ) raise yield KeyValue ( "#ENDSECTION" , "\n" ) yield KeyValue ( "!#ENDFILE" , "\n" ) | 6,349 | https://github.com/MoseleyBioinformaticsLab/mwtab/blob/8c0ae8ab2aa621662f99589ed41e481cf8b7152b/mwtab/tokenizer.py#L28-L102 | [
"async",
"def",
"set_room_temperatures_by_name",
"(",
"self",
",",
"room_name",
",",
"sleep_temp",
"=",
"None",
",",
"comfort_temp",
"=",
"None",
",",
"away_temp",
"=",
"None",
")",
":",
"if",
"sleep_temp",
"is",
"None",
"and",
"comfort_temp",
"is",
"None",
"and",
"away_temp",
"is",
"None",
":",
"return",
"for",
"room_id",
",",
"_room",
"in",
"self",
".",
"rooms",
".",
"items",
"(",
")",
":",
"if",
"_room",
".",
"name",
"==",
"room_name",
":",
"await",
"self",
".",
"set_room_temperatures",
"(",
"room_id",
",",
"sleep_temp",
",",
"comfort_temp",
",",
"away_temp",
")",
"return",
"_LOGGER",
".",
"error",
"(",
"\"Could not find a room with name %s\"",
",",
"room_name",
")"
] |
Get a mapfile owned by a user from the database by map_id . | def _get_map_from_user_by_id ( self , user , map_id ) : req = Session . query ( Map ) . select_from ( join ( Map , User ) ) try : return req . filter ( and_ ( User . login == user , Map . id == map_id ) ) . one ( ) except Exception , e : return None | 6,350 | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/controllers/mapfiles.py#L197-L204 | [
"def",
"search_service_code",
"(",
"self",
",",
"service_index",
")",
":",
"log",
".",
"debug",
"(",
"\"search service code index {0}\"",
".",
"format",
"(",
"service_index",
")",
")",
"# The maximum response time is given by the value of PMM[3].",
"# Some cards (like RC-S860 with IC RC-S915) encode a value",
"# that is too short, thus we use at lest 2 ms.",
"a",
",",
"e",
"=",
"self",
".",
"pmm",
"[",
"3",
"]",
"&",
"7",
",",
"self",
".",
"pmm",
"[",
"3",
"]",
">>",
"6",
"timeout",
"=",
"max",
"(",
"302E-6",
"*",
"(",
"a",
"+",
"1",
")",
"*",
"4",
"**",
"e",
",",
"0.002",
")",
"data",
"=",
"pack",
"(",
"\"<H\"",
",",
"service_index",
")",
"data",
"=",
"self",
".",
"send_cmd_recv_rsp",
"(",
"0x0A",
",",
"data",
",",
"timeout",
",",
"check_status",
"=",
"False",
")",
"if",
"data",
"!=",
"\"\\xFF\\xFF\"",
":",
"unpack_format",
"=",
"\"<H\"",
"if",
"len",
"(",
"data",
")",
"==",
"2",
"else",
"\"<HH\"",
"return",
"unpack",
"(",
"unpack_format",
",",
"data",
")"
] |
Get mapfiles owned by a user from the database . | def _get_maps_from_user ( self , user ) : req = Session . query ( Map ) . select_from ( join ( Map , User ) ) return req . filter ( User . login == user ) . all ( ) | 6,351 | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/controllers/mapfiles.py#L206-L209 | [
"def",
"restart",
"(",
"self",
",",
"container",
",",
"timeout",
"=",
"10",
")",
":",
"params",
"=",
"{",
"'t'",
":",
"timeout",
"}",
"url",
"=",
"self",
".",
"_url",
"(",
"\"/containers/{0}/restart\"",
",",
"container",
")",
"conn_timeout",
"=",
"self",
".",
"timeout",
"if",
"conn_timeout",
"is",
"not",
"None",
":",
"conn_timeout",
"+=",
"timeout",
"res",
"=",
"self",
".",
"_post",
"(",
"url",
",",
"params",
"=",
"params",
",",
"timeout",
"=",
"conn_timeout",
")",
"self",
".",
"_raise_for_status",
"(",
"res",
")"
] |
Create a new mapfile entry in database . | def _new_map_from_user ( self , user , name , filepath ) : map = Map ( name , filepath ) map . user = Session . query ( User ) . filter ( User . login == user ) . one ( ) Session . add ( map ) Session . commit ( ) return map | 6,352 | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/controllers/mapfiles.py#L228-L234 | [
"def",
"confirmation",
"(",
"self",
",",
"apdu",
")",
":",
"if",
"_debug",
":",
"ClientSSM",
".",
"_debug",
"(",
"\"confirmation %r\"",
",",
"apdu",
")",
"if",
"self",
".",
"state",
"==",
"SEGMENTED_REQUEST",
":",
"self",
".",
"segmented_request",
"(",
"apdu",
")",
"elif",
"self",
".",
"state",
"==",
"AWAIT_CONFIRMATION",
":",
"self",
".",
"await_confirmation",
"(",
"apdu",
")",
"elif",
"self",
".",
"state",
"==",
"SEGMENTED_CONFIRMATION",
":",
"self",
".",
"segmented_confirmation",
"(",
"apdu",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"invalid state\"",
")"
] |
Do the actual action of proxying the call . | def _proxy ( self , url , urlparams = None ) : for k , v in request . params . iteritems ( ) : urlparams [ k ] = v query = urlencode ( urlparams ) full_url = url if query : if not full_url . endswith ( "?" ) : full_url += "?" full_url += query # build the request with its headers req = urllib2 . Request ( url = full_url ) for header in request . headers : if header . lower ( ) == "host" : req . add_header ( header , urlparse . urlparse ( url ) [ 1 ] ) else : req . add_header ( header , request . headers [ header ] ) res = urllib2 . urlopen ( req ) # add response headers i = res . info ( ) response . status = res . code got_content_length = False for header in i : # We don't support serving the result as chunked if header . lower ( ) == "transfer-encoding" : continue if header . lower ( ) == "content-length" : got_content_length = True response . headers [ header ] = i [ header ] # return the result result = res . read ( ) res . close ( ) #if not got_content_length: # response.headers['content-length'] = str(len(result)) return result | 6,353 | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/controllers/mapfiles.py#L236-L275 | [
"def",
"read_devkit",
"(",
"f",
")",
":",
"with",
"tar_open",
"(",
"f",
")",
"as",
"tar",
":",
"# Metadata table containing class hierarchy, textual descriptions, etc.",
"meta_mat",
"=",
"tar",
".",
"extractfile",
"(",
"DEVKIT_META_PATH",
")",
"synsets",
",",
"cost_matrix",
"=",
"read_metadata_mat_file",
"(",
"meta_mat",
")",
"# Raw validation data groundtruth, ILSVRC2010 IDs. Confusingly",
"# distributed inside the development kit archive.",
"raw_valid_groundtruth",
"=",
"numpy",
".",
"loadtxt",
"(",
"tar",
".",
"extractfile",
"(",
"DEVKIT_VALID_GROUNDTRUTH_PATH",
")",
",",
"dtype",
"=",
"numpy",
".",
"int16",
")",
"return",
"synsets",
",",
"cost_matrix",
",",
"raw_valid_groundtruth"
] |
Taking in a file path attempt to open mock data files with it . | def open_file ( orig_file_path ) : unquoted = unquote ( orig_file_path ) paths = [ convert_to_platform_safe ( orig_file_path ) , "%s/index.html" % ( convert_to_platform_safe ( orig_file_path ) ) , orig_file_path , "%s/index.html" % orig_file_path , convert_to_platform_safe ( unquoted ) , "%s/index.html" % ( convert_to_platform_safe ( unquoted ) ) , unquoted , "%s/index.html" % unquoted , ] file_path = None handle = None for path in paths : try : file_path = path handle = open ( path , "rb" ) break except IOError : pass return handle | 6,354 | https://github.com/uw-it-aca/uw-restclients-core/blob/fda9380dceb6355ec6a3123e88c9ec66ae992682/restclients_core/util/mock.py#L84-L110 | [
"def",
"OnRemoveCards",
"(",
"self",
",",
"removedcards",
")",
":",
"parentnode",
"=",
"self",
".",
"root",
"for",
"cardtoremove",
"in",
"removedcards",
":",
"(",
"childCard",
",",
"cookie",
")",
"=",
"self",
".",
"GetFirstChild",
"(",
"parentnode",
")",
"while",
"childCard",
".",
"IsOk",
"(",
")",
":",
"if",
"self",
".",
"GetItemText",
"(",
"childCard",
")",
"==",
"toHexString",
"(",
"cardtoremove",
".",
"atr",
")",
":",
"self",
".",
"Delete",
"(",
"childCard",
")",
"(",
"childCard",
",",
"cookie",
")",
"=",
"self",
".",
"GetNextChild",
"(",
"parentnode",
",",
"cookie",
")",
"self",
".",
"Expand",
"(",
"self",
".",
"root",
")",
"self",
".",
"EnsureVisible",
"(",
"self",
".",
"root",
")",
"self",
".",
"Repaint",
"(",
")"
] |
Attempt to open a given mock data file with different permutations of the query parameters | def attempt_open_query_permutations ( url , orig_file_path , is_header_file ) : directory = dirname ( convert_to_platform_safe ( orig_file_path ) ) + "/" # get all filenames in directory try : filenames = [ f for f in os . listdir ( directory ) if isfile ( join ( directory , f ) ) ] except OSError : return # ensure that there are not extra parameters on any files if is_header_file : filenames = [ f for f in filenames if ".http-headers" in f ] filenames = [ f for f in filenames if _compare_file_name ( orig_file_path + ".http-headers" , directory , f ) ] else : filenames = [ f for f in filenames if ".http-headers" not in f ] filenames = [ f for f in filenames if _compare_file_name ( orig_file_path , directory , f ) ] url_parts = url . split ( "/" ) url_parts = url_parts [ len ( url_parts ) - 1 ] . split ( "?" ) base = url_parts [ 0 ] params = url_parts [ 1 ] params = params . split ( "&" ) # check to ensure that the base url matches filenames = [ f for f in filenames if f . startswith ( base ) ] params = [ convert_to_platform_safe ( unquote ( p ) ) for p in params ] # ensure that all parameters are there for param in params : filenames = [ f for f in filenames if param in f ] # if we only have one file, return it if len ( filenames ) == 1 : path = join ( directory , filenames [ 0 ] ) return open_file ( path ) # if there is more than one file, raise an exception if len ( filenames ) > 1 : raise DataFailureException ( url , "Multiple mock data files matched the " + "parameters provided!" , 404 ) | 6,355 | https://github.com/uw-it-aca/uw-restclients-core/blob/fda9380dceb6355ec6a3123e88c9ec66ae992682/restclients_core/util/mock.py#L113-L167 | [
"def",
"absolute_coords",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"!=",
"EventType",
".",
"POINTER_MOTION_ABSOLUTE",
":",
"raise",
"AttributeError",
"(",
"_wrong_prop",
".",
"format",
"(",
"self",
".",
"type",
")",
")",
"abs_x",
"=",
"self",
".",
"_libinput",
".",
"libinput_event_pointer_get_absolute_x",
"(",
"self",
".",
"_handle",
")",
"abs_y",
"=",
"self",
".",
"_libinput",
".",
"libinput_event_pointer_get_absolute_y",
"(",
"self",
".",
"_handle",
")",
"return",
"abs_x",
",",
"abs_y"
] |
return the first key in dict where value is name | def lookup ( self , value ) : for k , v in self . iteritems ( ) : if value == v : return k return None | 6,356 | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/lib/mapscriptutils.py#L28-L33 | [
"def",
"online_merge_medium",
"(",
"self",
",",
"medium_attachment",
",",
"source_idx",
",",
"target_idx",
",",
"progress",
")",
":",
"if",
"not",
"isinstance",
"(",
"medium_attachment",
",",
"IMediumAttachment",
")",
":",
"raise",
"TypeError",
"(",
"\"medium_attachment can only be an instance of type IMediumAttachment\"",
")",
"if",
"not",
"isinstance",
"(",
"source_idx",
",",
"baseinteger",
")",
":",
"raise",
"TypeError",
"(",
"\"source_idx can only be an instance of type baseinteger\"",
")",
"if",
"not",
"isinstance",
"(",
"target_idx",
",",
"baseinteger",
")",
":",
"raise",
"TypeError",
"(",
"\"target_idx can only be an instance of type baseinteger\"",
")",
"if",
"not",
"isinstance",
"(",
"progress",
",",
"IProgress",
")",
":",
"raise",
"TypeError",
"(",
"\"progress can only be an instance of type IProgress\"",
")",
"self",
".",
"_call",
"(",
"\"onlineMergeMedium\"",
",",
"in_p",
"=",
"[",
"medium_attachment",
",",
"source_idx",
",",
"target_idx",
",",
"progress",
"]",
")"
] |
Provides line pos and absPosition line as string | def _getLPA ( self ) : return str ( self . line ) + ":" + str ( self . pos ) + ":" + str ( self . absPosition ) | 6,357 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/legacy/src/cdmbriefparser.py#L91-L95 | [
"def",
"convert_to_experiment_list",
"(",
"experiments",
")",
":",
"exp_list",
"=",
"experiments",
"# Transform list if necessary",
"if",
"experiments",
"is",
"None",
":",
"exp_list",
"=",
"[",
"]",
"elif",
"isinstance",
"(",
"experiments",
",",
"Experiment",
")",
":",
"exp_list",
"=",
"[",
"experiments",
"]",
"elif",
"type",
"(",
"experiments",
")",
"is",
"dict",
":",
"exp_list",
"=",
"[",
"Experiment",
".",
"from_json",
"(",
"name",
",",
"spec",
")",
"for",
"name",
",",
"spec",
"in",
"experiments",
".",
"items",
"(",
")",
"]",
"# Validate exp_list",
"if",
"(",
"type",
"(",
"exp_list",
")",
"is",
"list",
"and",
"all",
"(",
"isinstance",
"(",
"exp",
",",
"Experiment",
")",
"for",
"exp",
"in",
"exp_list",
")",
")",
":",
"if",
"len",
"(",
"exp_list",
")",
">",
"1",
":",
"logger",
".",
"warning",
"(",
"\"All experiments will be \"",
"\"using the same SearchAlgorithm.\"",
")",
"else",
":",
"raise",
"TuneError",
"(",
"\"Invalid argument: {}\"",
".",
"format",
"(",
"experiments",
")",
")",
"return",
"exp_list"
] |
Memorizes an import | def _onImport ( self , name , line , pos , absPosition ) : if self . __lastImport is not None : self . imports . append ( self . __lastImport ) self . __lastImport = Import ( name , line , pos , absPosition ) return | 6,358 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/legacy/src/cdmbriefparser.py#L497-L502 | [
"def",
"close_fds",
"(",
")",
":",
"def",
"close",
"(",
"fd",
")",
":",
"with",
"ignored",
"(",
"OSError",
")",
":",
"os",
".",
"close",
"(",
"fd",
")",
"if",
"sys",
".",
"platform",
"==",
"'linux'",
":",
"fd_dir",
"=",
"'/proc/self/fd'",
"fds",
"=",
"set",
"(",
"map",
"(",
"int",
",",
"os",
".",
"listdir",
"(",
"fd_dir",
")",
")",
")",
"for",
"x",
"in",
"(",
"fds",
"-",
"{",
"0",
",",
"1",
",",
"2",
"}",
")",
":",
"close",
"(",
"x",
")",
"elif",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"uid",
"=",
"os",
".",
"getuid",
"(",
")",
"fd_dir",
"=",
"'/dev/fd'",
"fds",
"=",
"set",
"(",
"map",
"(",
"int",
",",
"os",
".",
"listdir",
"(",
"fd_dir",
")",
")",
")",
"for",
"x",
"in",
"(",
"fds",
"-",
"{",
"0",
",",
"1",
",",
"2",
"}",
")",
":",
"path",
"=",
"'/dev/fd/'",
"+",
"str",
"(",
"x",
")",
"if",
"not",
"os",
".",
"access",
"(",
"path",
",",
"os",
".",
"R_OK",
")",
":",
"continue",
"stat",
"=",
"os",
".",
"fstat",
"(",
"x",
")",
"if",
"stat",
".",
"st_uid",
"!=",
"uid",
":",
"continue",
"close",
"(",
"x",
")"
] |
Memorizes an alias for an import or an imported item | def _onAs ( self , name ) : if self . __lastImport . what : self . __lastImport . what [ - 1 ] . alias = name else : self . __lastImport . alias = name return | 6,359 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/legacy/src/cdmbriefparser.py#L504-L510 | [
"def",
"calculate_windows",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"windows",
"=",
"find_windows",
"(",
"self",
".",
"elements",
",",
"self",
".",
"coordinates",
",",
"*",
"*",
"kwargs",
")",
"if",
"windows",
":",
"self",
".",
"properties",
".",
"update",
"(",
"{",
"'windows'",
":",
"{",
"'diameters'",
":",
"windows",
"[",
"0",
"]",
",",
"'centre_of_mass'",
":",
"windows",
"[",
"1",
"]",
",",
"}",
"}",
")",
"return",
"windows",
"[",
"0",
"]",
"else",
":",
"self",
".",
"properties",
".",
"update",
"(",
"{",
"'windows'",
":",
"{",
"'diameters'",
":",
"None",
",",
"'centre_of_mass'",
":",
"None",
",",
"}",
"}",
")",
"return",
"None"
] |
returns the count of comments of an object | def comment_count ( obj ) : model_object = type ( obj ) . objects . get ( id = obj . id ) return model_object . comments . all ( ) . count ( ) | 6,360 | https://github.com/Radi85/Comment/blob/c3c46afe51228cd7ee4e04f5e6164fff1be3a5bc/comment/templatetags/comment_tags.py#L25-L28 | [
"def",
"periodic_ping",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"is_closing",
"(",
")",
"and",
"self",
".",
"ping_callback",
"is",
"not",
"None",
":",
"self",
".",
"ping_callback",
".",
"stop",
"(",
")",
"return",
"# Check for timeout on pong. Make sure that we really have",
"# sent a recent ping in case the machine with both server and",
"# client has been suspended since the last ping.",
"now",
"=",
"IOLoop",
".",
"current",
"(",
")",
".",
"time",
"(",
")",
"since_last_pong",
"=",
"now",
"-",
"self",
".",
"last_pong",
"since_last_ping",
"=",
"now",
"-",
"self",
".",
"last_ping",
"assert",
"self",
".",
"ping_interval",
"is",
"not",
"None",
"assert",
"self",
".",
"ping_timeout",
"is",
"not",
"None",
"if",
"(",
"since_last_ping",
"<",
"2",
"*",
"self",
".",
"ping_interval",
"and",
"since_last_pong",
">",
"self",
".",
"ping_timeout",
")",
":",
"self",
".",
"close",
"(",
")",
"return",
"self",
".",
"write_ping",
"(",
"b\"\"",
")",
"self",
".",
"last_ping",
"=",
"now"
] |
returns profile url of user | def profile_url ( obj , profile_app_name , profile_model_name ) : try : content_type = ContentType . objects . get ( app_label = profile_app_name , model = profile_model_name . lower ( ) ) profile = content_type . get_object_for_this_type ( user = obj . user ) return profile . get_absolute_url ( ) except ContentType . DoesNotExist : return "" except AttributeError : return "" | 6,361 | https://github.com/Radi85/Comment/blob/c3c46afe51228cd7ee4e04f5e6164fff1be3a5bc/comment/templatetags/comment_tags.py#L32-L44 | [
"def",
"pack_tups",
"(",
"*",
"args",
")",
":",
"# Imports",
"import",
"numpy",
"as",
"np",
"# Debug flag",
"_DEBUG",
"=",
"False",
"# Marker value for non-iterable items",
"NOT_ITER",
"=",
"-",
"1",
"# Uninitialized test value",
"UNINIT_VAL",
"=",
"-",
"1",
"# Print the input if in debug mode",
"if",
"_DEBUG",
":",
"# pragma: no cover",
"print",
"(",
"\"args = {0}\"",
".",
"format",
"(",
"args",
")",
")",
"# Non-iterable subclass of str",
"class",
"StrNoIter",
"(",
"str",
")",
":",
"\"\"\" Non-iterable subclass of |str|. \"\"\"",
"def",
"__iter__",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Non-iterable string\"",
")",
"## end def __iter__",
"## end class StrNoIter",
"# Re-wrap input arguments with non-iterable strings if required",
"mod_args",
"=",
"[",
"(",
"StrNoIter",
"(",
"a",
")",
"if",
"isinstance",
"(",
"a",
",",
"str",
")",
"else",
"a",
")",
"for",
"a",
"in",
"args",
"]",
"# Determine the length or non-iterable status of each item and store",
"# the maximum value (depends on NOT_ITER < 0)",
"iterlens",
"=",
"[",
"(",
"len",
"(",
"a",
")",
"if",
"iterable",
"(",
"a",
")",
"else",
"NOT_ITER",
")",
"for",
"a",
"in",
"mod_args",
"]",
"maxiter",
"=",
"max",
"(",
"iterlens",
")",
"# Check to ensure all iterables are the same length",
"if",
"not",
"all",
"(",
"map",
"(",
"lambda",
"v",
":",
"v",
"in",
"(",
"NOT_ITER",
",",
"maxiter",
")",
",",
"iterlens",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"All iterable items must be of equal length\"",
")",
"## end if",
"# If everything is non-iterable, just return the args tuple wrapped in",
"# a list (as above, depends on NOT_ITER < 0)",
"if",
"maxiter",
"==",
"NOT_ITER",
":",
"return",
"[",
"args",
"]",
"## end if",
"# Swap any non-iterables for a suitable length repeat, and zip to",
"# tuples for return",
"tups",
"=",
"list",
"(",
"zip",
"(",
"*",
"[",
"(",
"np",
".",
"repeat",
"(",
"a",
",",
"maxiter",
")",
"if",
"l",
"==",
"NOT_ITER",
"else",
"a",
")",
"for",
"(",
"a",
",",
"l",
")",
"in",
"zip",
"(",
"mod_args",
",",
"iterlens",
")",
"]",
")",
")",
"# Dump the resulting tuples, if in debug mode",
"if",
"_DEBUG",
":",
"# pragma: no cover",
"print",
"(",
"\"tups = {0}\"",
".",
"format",
"(",
"tups",
")",
")",
"## end if",
"# Return the tuples",
"return",
"tups"
] |
returns url of profile image of a user | def img_url ( obj , profile_app_name , profile_model_name ) : try : content_type = ContentType . objects . get ( app_label = profile_app_name , model = profile_model_name . lower ( ) ) except ContentType . DoesNotExist : return "" except AttributeError : return "" Profile = content_type . model_class ( ) fields = Profile . _meta . get_fields ( ) profile = content_type . model_class ( ) . objects . get ( user = obj . user ) for field in fields : if hasattr ( field , "upload_to" ) : return field . value_from_object ( profile ) . url | 6,362 | https://github.com/Radi85/Comment/blob/c3c46afe51228cd7ee4e04f5e6164fff1be3a5bc/comment/templatetags/comment_tags.py#L48-L65 | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_closed",
":",
"return",
"False",
"log",
".",
"info",
"(",
"\"{module}: '{name}' [{id}]: is closing\"",
".",
"format",
"(",
"module",
"=",
"self",
".",
"manager",
".",
"module_name",
",",
"name",
"=",
"self",
".",
"name",
",",
"id",
"=",
"self",
".",
"id",
")",
")",
"if",
"self",
".",
"_console",
":",
"self",
".",
"_manager",
".",
"port_manager",
".",
"release_tcp_port",
"(",
"self",
".",
"_console",
",",
"self",
".",
"_project",
")",
"self",
".",
"_console",
"=",
"None",
"if",
"self",
".",
"_wrap_console",
":",
"self",
".",
"_manager",
".",
"port_manager",
".",
"release_tcp_port",
"(",
"self",
".",
"_internal_console_port",
",",
"self",
".",
"_project",
")",
"self",
".",
"_internal_console_port",
"=",
"None",
"if",
"self",
".",
"_aux",
":",
"self",
".",
"_manager",
".",
"port_manager",
".",
"release_tcp_port",
"(",
"self",
".",
"_aux",
",",
"self",
".",
"_project",
")",
"self",
".",
"_aux",
"=",
"None",
"self",
".",
"_closed",
"=",
"True",
"return",
"True"
] |
Retrieves list of comments related to a certain object and renders The appropriate template to view it | def get_comments ( obj , request , oauth = False , paginate = False , cpp = 10 ) : model_object = type ( obj ) . objects . get ( id = obj . id ) comments = Comment . objects . filter_by_object ( model_object ) comments_count = comments . count ( ) if paginate : paginator = Paginator ( comments , cpp ) page = request . GET . get ( 'page' ) try : comments = paginator . page ( page ) except PageNotAnInteger : comments = paginator . page ( 1 ) except EmptyPage : comments = paginator . page ( paginator . num_pages ) try : profile_app_name = settings . PROFILE_APP_NAME profile_model_name = settings . PROFILE_MODEL_NAME except AttributeError : profile_app_name = None profile_model_name = None try : if settings . LOGIN_URL . startswith ( "/" ) : login_url = settings . LOGIN_URL else : login_url = "/" + settings . LOGIN_URL except AttributeError : login_url = "" return { "commentform" : CommentForm ( ) , "model_object" : obj , "user" : request . user , "comments" : comments , # "comments_count": comments_count, "oauth" : oauth , "profile_app_name" : profile_app_name , "profile_model_name" : profile_model_name , "paginate" : paginate , "login_url" : login_url , "cpp" : cpp } | 6,363 | https://github.com/Radi85/Comment/blob/c3c46afe51228cd7ee4e04f5e6164fff1be3a5bc/comment/templatetags/comment_tags.py#L68-L113 | [
"def",
"_clean_characters",
"(",
"x",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"six",
".",
"string_types",
")",
":",
"x",
"=",
"str",
"(",
"x",
")",
"else",
":",
"if",
"not",
"all",
"(",
"ord",
"(",
"char",
")",
"<",
"128",
"for",
"char",
"in",
"x",
")",
":",
"msg",
"=",
"\"Found unicode character in input YAML (%s)\"",
"%",
"(",
"x",
")",
"raise",
"ValueError",
"(",
"repr",
"(",
"msg",
")",
")",
"for",
"problem",
"in",
"[",
"\" \"",
",",
"\".\"",
",",
"\"/\"",
",",
"\"\\\\\"",
",",
"\"[\"",
",",
"\"]\"",
",",
"\"&\"",
",",
"\";\"",
",",
"\"#\"",
",",
"\"+\"",
",",
"\":\"",
",",
"\")\"",
",",
"\"(\"",
"]",
":",
"x",
"=",
"x",
".",
"replace",
"(",
"problem",
",",
"\"_\"",
")",
"return",
"x"
] |
save the instance as a . lcopt file | def save ( self ) : if self . save_option == 'curdir' : model_path = os . path . join ( os . getcwd ( ) , '{}.lcopt' . format ( self . name ) ) else : # default to appdir model_path = os . path . join ( storage . model_dir , '{}.lcopt' . format ( self . name ) ) model_path = fix_mac_path_escapes ( model_path ) with open ( model_path , 'wb' ) as model_file : pickle . dump ( self , model_file ) | 6,364 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L253-L269 | [
"def",
"user_deleted_from_site_event",
"(",
"event",
")",
":",
"userid",
"=",
"event",
".",
"principal",
"catalog",
"=",
"api",
".",
"portal",
".",
"get_tool",
"(",
"'portal_catalog'",
")",
"query",
"=",
"{",
"'object_provides'",
":",
"WORKSPACE_INTERFACE",
"}",
"query",
"[",
"'workspace_members'",
"]",
"=",
"userid",
"workspaces",
"=",
"[",
"IWorkspace",
"(",
"b",
".",
"_unrestrictedGetObject",
"(",
")",
")",
"for",
"b",
"in",
"catalog",
".",
"unrestrictedSearchResults",
"(",
"query",
")",
"]",
"for",
"workspace",
"in",
"workspaces",
":",
"workspace",
".",
"remove_from_team",
"(",
"userid",
")"
] |
load data from a saved . lcopt file | def load ( self , filename ) : if filename [ - 6 : ] != ".lcopt" : filename += ".lcopt" try : savedInstance = pickle . load ( open ( "{}" . format ( filename ) , "rb" ) ) except FileNotFoundError : savedInstance = pickle . load ( open ( fix_mac_path_escapes ( os . path . join ( storage . model_dir , "{}" . format ( filename ) ) ) , "rb" ) ) attributes = [ 'name' , 'database' , 'params' , 'production_params' , 'allocation_params' , 'ext_params' , 'matrix' , 'names' , 'parameter_sets' , 'model_matrices' , 'technosphere_matrices' , 'leontif_matrices' , 'external_databases' , 'parameter_map' , 'sandbox_positions' , 'ecoinventName' , 'biosphereName' , 'forwastName' , 'analysis_settings' , 'technosphere_databases' , 'biosphere_databases' , 'result_set' , 'evaluated_parameter_sets' , 'useForwast' , 'base_project_name' , 'save_option' , 'allow_allocation' , 'ecoinvent_version' , 'ecoinvent_system_model' , ] for attr in attributes : if hasattr ( savedInstance , attr ) : setattr ( self , attr , getattr ( savedInstance , attr ) ) else : pass #print ("can't set {}".format(attr)) # use legacy save option if this is missing from the model if not hasattr ( savedInstance , 'save_option' ) : setattr ( self , 'save_option' , LEGACY_SAVE_OPTION ) # figure out ecoinvent version and system model if these are missing from the model if not hasattr ( savedInstance , 'ecoinvent_version' ) or not hasattr ( savedInstance , 'ecoinvent_system_model' ) : parts = savedInstance . ecoinventName . split ( "_" ) main_version = parts [ 0 ] [ - 1 ] sub_version = parts [ 1 ] system_model = parts [ 2 ] #print(parts) setattr ( self , 'ecoinvent_version' , '{}.{}' . format ( main_version , sub_version ) ) setattr ( self , 'ecoinvent_system_model' , system_model ) | 6,365 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L271-L334 | [
"def",
"_notin",
"(",
"expr",
",",
"values",
")",
":",
"if",
"isinstance",
"(",
"expr",
",",
"SequenceExpr",
")",
":",
"return",
"NotIn",
"(",
"_input",
"=",
"expr",
",",
"_values",
"=",
"values",
",",
"_data_type",
"=",
"types",
".",
"boolean",
")",
"elif",
"isinstance",
"(",
"expr",
",",
"Scalar",
")",
":",
"return",
"NotIn",
"(",
"_input",
"=",
"expr",
",",
"_values",
"=",
"values",
",",
"_value_type",
"=",
"types",
".",
"boolean",
")"
] |
Create a new product in the model database | def create_product ( self , name , location = 'GLO' , unit = 'kg' , * * kwargs ) : new_product = item_factory ( name = name , location = location , unit = unit , type = 'product' , * * kwargs ) if not self . exists_in_database ( new_product [ 'code' ] ) : self . add_to_database ( new_product ) #print ('{} added to database'.format(name)) return self . get_exchange ( name ) else : #print('{} already exists in this database'.format(name)) return False | 6,366 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L338-L352 | [
"def",
"get_ftr",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"ftr",
":",
"return",
"self",
".",
"ftr",
"width",
"=",
"self",
".",
"size",
"(",
")",
"[",
"0",
"]",
"return",
"re",
".",
"sub",
"(",
"\"%time\"",
",",
"\"%s\\n\"",
"%",
"time",
".",
"strftime",
"(",
"\"%H:%M:%S\"",
")",
",",
"self",
".",
"ftr",
")",
".",
"rjust",
"(",
"width",
")"
] |
Remove a link between two processes | def unlink_intermediate ( self , sourceId , targetId ) : source = self . database [ 'items' ] [ ( self . database . get ( 'name' ) , sourceId ) ] target = self . database [ 'items' ] [ ( self . database . get ( 'name' ) , targetId ) ] production_exchange = [ x [ 'input' ] for x in source [ 'exchanges' ] if x [ 'type' ] == 'production' ] [ 0 ] new_exchanges = [ x for x in target [ 'exchanges' ] if x [ 'input' ] != production_exchange ] target [ 'exchanges' ] = new_exchanges self . parameter_scan ( ) return True | 6,367 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L440-L456 | [
"def",
"_adapt_WSDateTime",
"(",
"dt",
")",
":",
"try",
":",
"ts",
"=",
"int",
"(",
"(",
"dt",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
"-",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
",",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
")",
".",
"total_seconds",
"(",
")",
")",
"except",
"(",
"OverflowError",
",",
"OSError",
")",
":",
"if",
"dt",
"<",
"datetime",
".",
"now",
"(",
")",
":",
"ts",
"=",
"0",
"else",
":",
"ts",
"=",
"2",
"**",
"63",
"-",
"1",
"return",
"ts"
] |
Generate an excel file containing the parameter sets in a format you can import into SimaPro Developer . | def generate_parameter_set_excel_file ( self ) : parameter_sets = self . parameter_sets p_set = [ ] filename = "ParameterSet_{}_input_file.xlsx" . format ( self . name ) if self . save_option == 'curdir' : base_dir = os . getcwd ( ) else : base_dir = os . path . join ( storage . simapro_dir , self . name . replace ( " " , "_" ) ) if not os . path . isdir ( base_dir ) : os . mkdir ( base_dir ) p_set_name = os . path . join ( base_dir , filename ) p = self . params for k in p . keys ( ) : if p [ k ] [ 'function' ] is None : base_dict = { 'id' : k , 'name' : p [ k ] [ 'description' ] , 'unit' : p [ k ] [ 'unit' ] } for s in parameter_sets . keys ( ) : base_dict [ s ] = parameter_sets [ s ] [ k ] p_set . append ( base_dict ) else : pass #print("{} is determined by a function".format(p[k]['description'])) for e in self . ext_params : base_dict = { 'id' : '{}' . format ( e [ 'name' ] ) , 'type' : 'external' , 'name' : e [ 'description' ] , 'unit' : '' } for s in parameter_sets . keys ( ) : base_dict [ s ] = parameter_sets [ s ] [ e [ 'name' ] ] p_set . append ( base_dict ) df = pd . DataFrame ( p_set ) with pd . ExcelWriter ( p_set_name , engine = 'xlsxwriter' ) as writer : ps_columns = [ k for k in parameter_sets . keys ( ) ] #print (ps_columns) my_columns = [ 'name' , 'unit' , 'id' ] my_columns . extend ( ps_columns ) #print (my_columns) #print(df) df . to_excel ( writer , sheet_name = self . name , columns = my_columns , index = False , merge_cells = False ) return p_set_name | 6,368 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L575-L633 | [
"def",
"_bit_mismatch",
"(",
"int1",
":",
"int",
",",
"int2",
":",
"int",
")",
"->",
"int",
":",
"for",
"i",
"in",
"range",
"(",
"max",
"(",
"int1",
".",
"bit_length",
"(",
")",
",",
"int2",
".",
"bit_length",
"(",
")",
")",
")",
":",
"if",
"(",
"int1",
">>",
"i",
")",
"&",
"1",
"!=",
"(",
"int2",
">>",
"i",
")",
"&",
"1",
":",
"return",
"i",
"return",
"-",
"1"
] |
Add a global parameter to the database that can be accessed by functions | def add_parameter ( self , param_name , description = None , default = 0 , unit = None ) : if description is None : description = "Parameter called {}" . format ( param_name ) if unit is None : unit = "-" name_check = lambda x : x [ 'name' ] == param_name name_check_list = list ( filter ( name_check , self . ext_params ) ) if len ( name_check_list ) == 0 : self . ext_params . append ( { 'name' : param_name , 'description' : description , 'default' : default , 'unit' : unit } ) else : print ( '{} already exists - choose a different name' . format ( param_name ) ) | 6,369 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L635-L651 | [
"def",
"cli",
"(",
"file1",
",",
"file2",
",",
"comments",
")",
"->",
"int",
":",
"sys",
".",
"exit",
"(",
"compare_files",
"(",
"file1",
",",
"file2",
",",
"comments",
")",
")"
] |
Only really useful when running from a jupyter notebook . | def list_parameters_as_df ( self ) : to_df = [ ] for i , e in enumerate ( self . ext_params ) : row = { } row [ 'id' ] = e [ 'name' ] row [ 'coords' ] = "n/a" row [ 'description' ] = e [ 'description' ] row [ 'function' ] = "n/a" to_df . append ( row ) for pk in self . params : p = self . params [ pk ] row = { } row [ 'id' ] = pk row [ 'coords' ] = p [ 'coords' ] row [ 'description' ] = p [ 'description' ] row [ 'function' ] = p [ 'function' ] to_df . append ( row ) df = pd . DataFrame ( to_df ) return df | 6,370 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L653-L684 | [
"def",
"save_and_validate_logo",
"(",
"logo_stream",
",",
"logo_filename",
",",
"community_id",
")",
":",
"cfg",
"=",
"current_app",
".",
"config",
"logos_bucket_id",
"=",
"cfg",
"[",
"'COMMUNITIES_BUCKET_UUID'",
"]",
"logo_max_size",
"=",
"cfg",
"[",
"'COMMUNITIES_LOGO_MAX_SIZE'",
"]",
"logos_bucket",
"=",
"Bucket",
".",
"query",
".",
"get",
"(",
"logos_bucket_id",
")",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"logo_filename",
")",
"[",
"1",
"]",
"ext",
"=",
"ext",
"[",
"1",
":",
"]",
"if",
"ext",
".",
"startswith",
"(",
"'.'",
")",
"else",
"ext",
"logo_stream",
".",
"seek",
"(",
"SEEK_SET",
",",
"SEEK_END",
")",
"# Seek from beginning to end",
"logo_size",
"=",
"logo_stream",
".",
"tell",
"(",
")",
"if",
"logo_size",
">",
"logo_max_size",
":",
"return",
"None",
"if",
"ext",
"in",
"cfg",
"[",
"'COMMUNITIES_LOGO_EXTENSIONS'",
"]",
":",
"key",
"=",
"\"{0}/logo.{1}\"",
".",
"format",
"(",
"community_id",
",",
"ext",
")",
"logo_stream",
".",
"seek",
"(",
"0",
")",
"# Rewind the stream to the beginning",
"ObjectVersion",
".",
"create",
"(",
"logos_bucket",
",",
"key",
",",
"stream",
"=",
"logo_stream",
",",
"size",
"=",
"logo_size",
")",
"return",
"ext",
"else",
":",
"return",
"None"
] |
Import an external database for use in lcopt | def import_external_db ( self , db_file , db_type = None ) : db = pickle . load ( open ( "{}.pickle" . format ( db_file ) , "rb" ) ) name = list ( db . keys ( ) ) [ 0 ] [ 0 ] new_db = { 'items' : db , 'name' : name } self . external_databases . append ( new_db ) if db_type is None : # Assume its a technosphere database db_type = 'technosphere' if db_type == 'technosphere' : self . technosphere_databases . append ( name ) elif db_type == 'biosphere' : self . biosphere_databases . append ( name ) else : raise Exception print ( "Database type must be 'technosphere' or 'biosphere'" ) | 6,371 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L686-L725 | [
"def",
"match",
"(",
"Class",
",",
"path",
",",
"pattern",
",",
"flags",
"=",
"re",
".",
"I",
",",
"sortkey",
"=",
"None",
",",
"ext",
"=",
"None",
")",
":",
"return",
"sorted",
"(",
"[",
"Class",
"(",
"fn",
"=",
"fn",
")",
"for",
"fn",
"in",
"rglob",
"(",
"path",
",",
"f\"*{ext or ''}\"",
")",
"if",
"re",
".",
"search",
"(",
"pattern",
",",
"os",
".",
"path",
".",
"basename",
"(",
"fn",
")",
",",
"flags",
"=",
"flags",
")",
"is",
"not",
"None",
"and",
"os",
".",
"path",
".",
"basename",
"(",
"fn",
")",
"[",
"0",
"]",
"!=",
"'~'",
"# omit temp files",
"]",
",",
"key",
"=",
"sortkey",
",",
")"
] |
Search external databases linked to your lcopt model . | def search_databases ( self , search_term , location = None , markets_only = False , databases_to_search = None , allow_internal = False ) : dict_list = [ ] if allow_internal : internal_dict = { } for k , v in self . database [ 'items' ] . items ( ) : if v . get ( 'lcopt_type' ) == 'intermediate' : internal_dict [ k ] = v dict_list . append ( internal_dict ) if databases_to_search is None : #Search all of the databases available #data = Dictionaries(self.database['items'], *[x['items'] for x in self.external_databases]) dict_list += [ x [ 'items' ] for x in self . external_databases ] else : #data = Dictionaries(self.database['items'], *[x['items'] for x in self.external_databases if x['name'] in databases_to_search]) dict_list += [ x [ 'items' ] for x in self . external_databases if x [ 'name' ] in databases_to_search ] data = Dictionaries ( * dict_list ) #data = Dictionaries(self.database['items'], *[x['items'] for x in self.external_databases if x['name'] in databases_to_search]) query = Query ( ) if markets_only : market_filter = Filter ( "name" , "has" , "market for" ) query . add ( market_filter ) if location is not None : location_filter = Filter ( "location" , "is" , location ) query . add ( location_filter ) query . add ( Filter ( "name" , "ihas" , search_term ) ) result = query ( data ) return result | 6,372 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L727-L770 | [
"def",
"start_transmit",
"(",
"self",
",",
"blocking",
"=",
"False",
",",
"start_packet_groups",
"=",
"True",
",",
"*",
"ports",
")",
":",
"port_list",
"=",
"self",
".",
"set_ports_list",
"(",
"*",
"ports",
")",
"if",
"start_packet_groups",
":",
"port_list_for_packet_groups",
"=",
"self",
".",
"ports",
".",
"values",
"(",
")",
"port_list_for_packet_groups",
"=",
"self",
".",
"set_ports_list",
"(",
"*",
"port_list_for_packet_groups",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixClearTimeStamp {}'",
".",
"format",
"(",
"port_list_for_packet_groups",
")",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixStartPacketGroups {}'",
".",
"format",
"(",
"port_list_for_packet_groups",
")",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixStartTransmit {}'",
".",
"format",
"(",
"port_list",
")",
")",
"time",
".",
"sleep",
"(",
"0.2",
")",
"if",
"blocking",
":",
"self",
".",
"wait_transmit",
"(",
"*",
"ports",
")"
] |
Export the lcopt model in the native brightway 2 format | def export_to_bw2 ( self ) : my_exporter = Bw2Exporter ( self ) name , bw2db = my_exporter . export_to_bw2 ( ) return name , bw2db | 6,373 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L969-L987 | [
"def",
"_wait_while_in_pause_or_in_step_mode",
"(",
"self",
")",
":",
"while",
"(",
"self",
".",
"_status",
".",
"execution_mode",
"is",
"StateMachineExecutionStatus",
".",
"PAUSED",
")",
"or",
"(",
"self",
".",
"_status",
".",
"execution_mode",
"is",
"StateMachineExecutionStatus",
".",
"STEP_MODE",
")",
":",
"try",
":",
"self",
".",
"_status",
".",
"execution_condition_variable",
".",
"acquire",
"(",
")",
"self",
".",
"synchronization_counter",
"+=",
"1",
"logger",
".",
"verbose",
"(",
"\"Increase synchronization_counter: \"",
"+",
"str",
"(",
"self",
".",
"synchronization_counter",
")",
")",
"self",
".",
"_status",
".",
"execution_condition_variable",
".",
"wait",
"(",
")",
"finally",
":",
"self",
".",
"_status",
".",
"execution_condition_variable",
".",
"release",
"(",
")"
] |
Run the analyis of the model Doesn t return anything but creates a new item LcoptModel . result_set containing the results | def analyse ( self , demand_item , demand_item_code ) : my_analysis = Bw2Analysis ( self ) self . result_set = my_analysis . run_analyses ( demand_item , demand_item_code , * * self . analysis_settings ) return True | 6,374 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L989-L996 | [
"def",
"folder_shared_message",
"(",
"self",
",",
"request",
",",
"user",
",",
"folder",
")",
":",
"messages",
".",
"success",
"(",
"request",
",",
"_",
"(",
"\"Folder {} is now shared with {}\"",
".",
"format",
"(",
"folder",
",",
"user",
")",
")",
")"
] |
Show resolve information about specified service . | def locate ( name , * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'locate' , * * { 'name' : name , 'locator' : ctx . locator , } ) | 6,375 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L364-L372 | [
"def",
"delete_unused_subjects",
"(",
")",
":",
"# This causes Django to create a single join (check with query.query)",
"query",
"=",
"d1_gmn",
".",
"app",
".",
"models",
".",
"Subject",
".",
"objects",
".",
"all",
"(",
")",
"query",
"=",
"query",
".",
"filter",
"(",
"scienceobject_submitter__isnull",
"=",
"True",
")",
"query",
"=",
"query",
".",
"filter",
"(",
"scienceobject_rights_holder__isnull",
"=",
"True",
")",
"query",
"=",
"query",
".",
"filter",
"(",
"eventlog__isnull",
"=",
"True",
")",
"query",
"=",
"query",
".",
"filter",
"(",
"permission__isnull",
"=",
"True",
")",
"query",
"=",
"query",
".",
"filter",
"(",
"whitelistforcreateupdatedelete__isnull",
"=",
"True",
")",
"logger",
".",
"debug",
"(",
"'Deleting {} unused subjects:'",
".",
"format",
"(",
"query",
".",
"count",
"(",
")",
")",
")",
"for",
"s",
"in",
"query",
".",
"all",
"(",
")",
":",
"logging",
".",
"debug",
"(",
"' {}'",
".",
"format",
"(",
"s",
".",
"subject",
")",
")",
"query",
".",
"delete",
"(",
")"
] |
Show information about the requested routing group . | def routing ( name , * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'routing' , * * { 'name' : name , 'locator' : ctx . locator , } ) | 6,376 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L378-L386 | [
"def",
"fetch",
"(",
"self",
",",
"endpoint",
",",
"data",
"=",
"None",
")",
":",
"payload",
"=",
"{",
"\"lastServerChangeId\"",
":",
"\"-1\"",
",",
"\"csrf\"",
":",
"self",
".",
"__csrf",
",",
"\"apiClient\"",
":",
"\"WEB\"",
"}",
"if",
"data",
"is",
"not",
"None",
":",
"payload",
".",
"update",
"(",
"data",
")",
"return",
"self",
".",
"post",
"(",
"endpoint",
",",
"payload",
")"
] |
Show cluster info . | def cluster ( resolve , * * kwargs ) : # Actually we have IPs and we need not do anything to resolve them to IPs. So the default # behavior fits better to this option name. ctx = Context ( * * kwargs ) ctx . execute_action ( 'cluster' , * * { 'locator' : ctx . locator , 'resolve' : resolve , } ) | 6,377 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L404-L415 | [
"def",
"create_results_dir",
"(",
"self",
")",
":",
"self",
".",
"_current_results_dir",
"=",
"self",
".",
"_cache_manager",
".",
"_results_dir_path",
"(",
"self",
".",
"cache_key",
",",
"stable",
"=",
"False",
")",
"self",
".",
"_results_dir",
"=",
"self",
".",
"_cache_manager",
".",
"_results_dir_path",
"(",
"self",
".",
"cache_key",
",",
"stable",
"=",
"True",
")",
"if",
"not",
"self",
".",
"valid",
":",
"# Clean the workspace for invalid vts.",
"safe_mkdir",
"(",
"self",
".",
"_current_results_dir",
",",
"clean",
"=",
"True",
")",
"relative_symlink",
"(",
"self",
".",
"_current_results_dir",
",",
"self",
".",
"_results_dir",
")",
"self",
".",
"ensure_legal",
"(",
")"
] |
Show information about cocaine runtime . | def info ( name , m , p , b , w , * * kwargs ) : m = ( m << 1 ) & 0b010 p = ( p << 2 ) & 0b100 # Brief disables all further flags. if b : flags = 0b000 else : flags = m | p | 0b001 ctx = Context ( * * kwargs ) ctx . execute_action ( 'info' , * * { 'node' : ctx . repo . create_secure_service ( 'node' ) , 'locator' : ctx . locator , 'name' : name , 'flags' : flags , 'use_wildcard' : w , 'timeout' : ctx . timeout , } ) | 6,378 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L425-L451 | [
"def",
"queryset",
"(",
"self",
",",
"request",
")",
":",
"qs",
"=",
"super",
"(",
"CommentAdmin",
",",
"self",
")",
".",
"queryset",
"(",
"request",
")",
"qs",
"=",
"qs",
".",
"filter",
"(",
"Q",
"(",
"user__is_staff",
"=",
"False",
")",
"|",
"Q",
"(",
"user__isnull",
"=",
"True",
")",
",",
"is_removed",
"=",
"False",
")",
"cls",
"=",
"getattr",
"(",
"self",
",",
"'cls'",
",",
"None",
")",
"if",
"cls",
":",
"qs",
"=",
"qs",
".",
"filter",
"(",
"classifiedcomment__cls",
"=",
"self",
".",
"cls",
")",
"return",
"qs",
".",
"select_related",
"(",
"'user'",
",",
"'content_type'",
")"
] |
Outputs runtime metrics collected from cocaine - runtime and its services . | def metrics ( ty , query , query_type , * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'metrics' , * * { 'metrics' : ctx . repo . create_secure_service ( 'metrics' ) , 'ty' : ty , 'query' : query , 'query_type' : query_type , } ) | 6,379 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L579-L645 | [
"def",
"unshare_project",
"(",
"project_id",
",",
"usernames",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"proj_i",
"=",
"_get_project",
"(",
"project_id",
")",
"proj_i",
".",
"check_share_permission",
"(",
"user_id",
")",
"for",
"username",
"in",
"usernames",
":",
"user_i",
"=",
"_get_user",
"(",
"username",
")",
"#Set the owner ship on the network itself",
"proj_i",
".",
"unset_owner",
"(",
"user_i",
".",
"id",
",",
"write",
"=",
"write",
",",
"share",
"=",
"share",
")",
"db",
".",
"DBSession",
".",
"flush",
"(",
")"
] |
Show uploaded applications . | def app_list ( * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'app:list' , * * { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , } ) | 6,380 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L650-L657 | [
"def",
"get_access_token",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"token",
"is",
"None",
")",
"or",
"(",
"datetime",
".",
"utcnow",
"(",
")",
">",
"self",
".",
"reuse_token_until",
")",
":",
"headers",
"=",
"{",
"'Ocp-Apim-Subscription-Key'",
":",
"self",
".",
"client_secret",
"}",
"response",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"base_url",
",",
"headers",
"=",
"headers",
")",
"response",
".",
"raise_for_status",
"(",
")",
"self",
".",
"token",
"=",
"response",
".",
"content",
"self",
".",
"reuse_token_until",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"minutes",
"=",
"5",
")",
"return",
"self",
".",
"token",
".",
"decode",
"(",
"'utf-8'",
")"
] |
Show manifest content for an application . | def app_view ( name , * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'app:view' , * * { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , 'name' : name , } ) | 6,381 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L663-L673 | [
"def",
"user_deleted_from_site_event",
"(",
"event",
")",
":",
"userid",
"=",
"event",
".",
"principal",
"catalog",
"=",
"api",
".",
"portal",
".",
"get_tool",
"(",
"'portal_catalog'",
")",
"query",
"=",
"{",
"'object_provides'",
":",
"WORKSPACE_INTERFACE",
"}",
"query",
"[",
"'workspace_members'",
"]",
"=",
"userid",
"workspaces",
"=",
"[",
"IWorkspace",
"(",
"b",
".",
"_unrestrictedGetObject",
"(",
")",
")",
"for",
"b",
"in",
"catalog",
".",
"unrestrictedSearchResults",
"(",
"query",
")",
"]",
"for",
"workspace",
"in",
"workspaces",
":",
"workspace",
".",
"remove_from_team",
"(",
"userid",
")"
] |
Import application Docker container . | def app_import ( path , name , manifest , container_url , docker_address , registry , * * kwargs ) : lower_limit = 120.0 ctx = Context ( * * kwargs ) if ctx . timeout < lower_limit : ctx . timeout = lower_limit log . info ( 'shifted timeout to the %.2fs' , ctx . timeout ) if container_url and docker_address : ctx . execute_action ( 'app:import-docker' , * * { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , 'path' : path , 'name' : name , 'manifest' : manifest , 'container' : container_url , 'address' : docker_address , 'registry' : registry } ) else : raise ValueError ( "both `container_url` and `docker_address` options must not be empty" ) | 6,382 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L761-L783 | [
"def",
"noise",
"(",
"mesh",
",",
"magnitude",
"=",
"None",
")",
":",
"if",
"magnitude",
"is",
"None",
":",
"magnitude",
"=",
"mesh",
".",
"scale",
"/",
"100.0",
"random",
"=",
"(",
"np",
".",
"random",
".",
"random",
"(",
"mesh",
".",
"vertices",
".",
"shape",
")",
"-",
".5",
")",
"*",
"magnitude",
"vertices_noise",
"=",
"mesh",
".",
"vertices",
".",
"copy",
"(",
")",
"+",
"random",
"# make sure we've re- ordered faces randomly",
"triangles",
"=",
"np",
".",
"random",
".",
"permutation",
"(",
"vertices_noise",
"[",
"mesh",
".",
"faces",
"]",
")",
"mesh_type",
"=",
"util",
".",
"type_named",
"(",
"mesh",
",",
"'Trimesh'",
")",
"permutated",
"=",
"mesh_type",
"(",
"*",
"*",
"triangles_module",
".",
"to_kwargs",
"(",
"triangles",
")",
")",
"return",
"permutated"
] |
Remove application from storage . | def app_remove ( name , * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'app:remove' , * * { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , 'name' : name , } ) | 6,383 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L789-L799 | [
"def",
"create_api_call",
"(",
"func",
",",
"settings",
")",
":",
"def",
"base_caller",
"(",
"api_call",
",",
"_",
",",
"*",
"args",
")",
":",
"\"\"\"Simply call api_call and ignore settings.\"\"\"",
"return",
"api_call",
"(",
"*",
"args",
")",
"def",
"inner",
"(",
"request",
",",
"options",
"=",
"None",
")",
":",
"\"\"\"Invoke with the actual settings.\"\"\"",
"this_options",
"=",
"_merge_options_metadata",
"(",
"options",
",",
"settings",
")",
"this_settings",
"=",
"settings",
".",
"merge",
"(",
"this_options",
")",
"if",
"this_settings",
".",
"retry",
"and",
"this_settings",
".",
"retry",
".",
"retry_codes",
":",
"api_call",
"=",
"gax",
".",
"retry",
".",
"retryable",
"(",
"func",
",",
"this_settings",
".",
"retry",
",",
"*",
"*",
"this_settings",
".",
"kwargs",
")",
"else",
":",
"api_call",
"=",
"gax",
".",
"retry",
".",
"add_timeout_arg",
"(",
"func",
",",
"this_settings",
".",
"timeout",
",",
"*",
"*",
"this_settings",
".",
"kwargs",
")",
"api_call",
"=",
"_catch_errors",
"(",
"api_call",
",",
"gax",
".",
"config",
".",
"API_ERRORS",
")",
"return",
"api_caller",
"(",
"api_call",
",",
"this_settings",
",",
"request",
")",
"if",
"settings",
".",
"page_descriptor",
":",
"if",
"settings",
".",
"bundler",
"and",
"settings",
".",
"bundle_descriptor",
":",
"raise",
"ValueError",
"(",
"'The API call has incompatible settings: '",
"'bundling and page streaming'",
")",
"api_caller",
"=",
"_page_streamable",
"(",
"settings",
".",
"page_descriptor",
")",
"elif",
"settings",
".",
"bundler",
"and",
"settings",
".",
"bundle_descriptor",
":",
"api_caller",
"=",
"_bundleable",
"(",
"settings",
".",
"bundle_descriptor",
")",
"else",
":",
"api_caller",
"=",
"base_caller",
"return",
"inner"
] |
Start an application with specified profile . | def app_start ( name , profile , * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'app:start' , * * { 'node' : ctx . repo . create_secure_service ( 'node' ) , 'name' : name , 'profile' : profile } ) | 6,384 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L806-L817 | [
"def",
"_assign_numbers",
"(",
"self",
")",
":",
"first",
"=",
"self",
".",
"select_related",
"(",
"'point_of_sales'",
",",
"'receipt_type'",
")",
".",
"first",
"(",
")",
"next_num",
"=",
"Receipt",
".",
"objects",
".",
"fetch_last_receipt_number",
"(",
"first",
".",
"point_of_sales",
",",
"first",
".",
"receipt_type",
",",
")",
"+",
"1",
"for",
"receipt",
"in",
"self",
".",
"filter",
"(",
"receipt_number__isnull",
"=",
"True",
")",
":",
"# Atomically update receipt number",
"Receipt",
".",
"objects",
".",
"filter",
"(",
"pk",
"=",
"receipt",
".",
"id",
",",
"receipt_number__isnull",
"=",
"True",
",",
")",
".",
"update",
"(",
"receipt_number",
"=",
"next_num",
",",
")",
"next_num",
"+=",
"1"
] |
Restart application . | def app_restart ( name , profile , * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'app:restart' , * * { 'node' : ctx . repo . create_secure_service ( 'node' ) , 'locator' : ctx . locator , 'name' : name , 'profile' : profile , } ) | 6,385 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L854-L868 | [
"def",
"_add_dependency",
"(",
"self",
",",
"dependency",
",",
"var_name",
"=",
"None",
")",
":",
"if",
"var_name",
"is",
"None",
":",
"var_name",
"=",
"next",
"(",
"self",
".",
"temp_var_names",
")",
"# Don't add duplicate dependencies",
"if",
"(",
"dependency",
",",
"var_name",
")",
"not",
"in",
"self",
".",
"dependencies",
":",
"self",
".",
"dependencies",
".",
"append",
"(",
"(",
"dependency",
",",
"var_name",
")",
")",
"return",
"var_name"
] |
Check application status . | def check ( name , * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'app:check' , * * { 'node' : ctx . repo . create_secure_service ( 'node' ) , 'name' : name , } ) | 6,386 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L874-L882 | [
"def",
"on_response",
"(",
"self",
",",
"ch",
",",
"method_frame",
",",
"props",
",",
"body",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"rabbitmq.Requester.on_response\"",
")",
"if",
"self",
".",
"corr_id",
"==",
"props",
".",
"correlation_id",
":",
"self",
".",
"response",
"=",
"{",
"'props'",
":",
"props",
",",
"'body'",
":",
"body",
"}",
"else",
":",
"LOGGER",
".",
"warn",
"(",
"\"rabbitmq.Requester.on_response - discarded response : \"",
"+",
"str",
"(",
"props",
".",
"correlation_id",
")",
")",
"LOGGER",
".",
"debug",
"(",
"\"natsd.Requester.on_response - discarded response : \"",
"+",
"str",
"(",
"{",
"'properties'",
":",
"props",
",",
"'body'",
":",
"body",
"}",
")",
")"
] |
Show uploaded profiles . | def profile_list ( * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'profile:list' , * * { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , } ) | 6,387 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L887-L894 | [
"def",
"vn_release",
"(",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The vn_reserve function must be called with -f or --function.'",
")",
"if",
"kwargs",
"is",
"None",
":",
"kwargs",
"=",
"{",
"}",
"vn_id",
"=",
"kwargs",
".",
"get",
"(",
"'vn_id'",
",",
"None",
")",
"vn_name",
"=",
"kwargs",
".",
"get",
"(",
"'vn_name'",
",",
"None",
")",
"path",
"=",
"kwargs",
".",
"get",
"(",
"'path'",
",",
"None",
")",
"data",
"=",
"kwargs",
".",
"get",
"(",
"'data'",
",",
"None",
")",
"if",
"vn_id",
":",
"if",
"vn_name",
":",
"log",
".",
"warning",
"(",
"'Both the \\'vn_id\\' and \\'vn_name\\' arguments were provided. '",
"'\\'vn_id\\' will take precedence.'",
")",
"elif",
"vn_name",
":",
"vn_id",
"=",
"get_vn_id",
"(",
"kwargs",
"=",
"{",
"'name'",
":",
"vn_name",
"}",
")",
"else",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The vn_release function requires a \\'vn_id\\' or a \\'vn_name\\' to '",
"'be provided.'",
")",
"if",
"data",
":",
"if",
"path",
":",
"log",
".",
"warning",
"(",
"'Both the \\'data\\' and \\'path\\' arguments were provided. '",
"'\\'data\\' will take precedence.'",
")",
"elif",
"path",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"path",
",",
"mode",
"=",
"'r'",
")",
"as",
"rfh",
":",
"data",
"=",
"rfh",
".",
"read",
"(",
")",
"else",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The vn_release function requires either \\'data\\' or a \\'path\\' to '",
"'be provided.'",
")",
"server",
",",
"user",
",",
"password",
"=",
"_get_xml_rpc",
"(",
")",
"auth",
"=",
"':'",
".",
"join",
"(",
"[",
"user",
",",
"password",
"]",
")",
"response",
"=",
"server",
".",
"one",
".",
"vn",
".",
"release",
"(",
"auth",
",",
"int",
"(",
"vn_id",
")",
",",
"data",
")",
"ret",
"=",
"{",
"'action'",
":",
"'vn.release'",
",",
"'released'",
":",
"response",
"[",
"0",
"]",
",",
"'resource_id'",
":",
"response",
"[",
"1",
"]",
",",
"'error_code'",
":",
"response",
"[",
"2",
"]",
",",
"}",
"return",
"ret"
] |
Show profile configuration content . | def profile_view ( name , * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'profile:view' , * * { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , 'name' : name , } ) | 6,388 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L900-L908 | [
"def",
"login",
"(",
"self",
")",
":",
"access_token",
"=",
"self",
".",
"_get_access_token",
"(",
")",
"try",
":",
"super",
"(",
"IAMSession",
",",
"self",
")",
".",
"request",
"(",
"'POST'",
",",
"self",
".",
"_session_url",
",",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"{",
"'access_token'",
":",
"access_token",
"}",
")",
")",
".",
"raise_for_status",
"(",
")",
"except",
"RequestException",
":",
"raise",
"CloudantException",
"(",
"'Failed to exchange IAM token with Cloudant'",
")"
] |
Remove profile from the storage . | def profile_remove ( name , * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'profile:remove' , * * { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , 'name' : name , } ) | 6,389 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L945-L953 | [
"def",
"create_api_call",
"(",
"func",
",",
"settings",
")",
":",
"def",
"base_caller",
"(",
"api_call",
",",
"_",
",",
"*",
"args",
")",
":",
"\"\"\"Simply call api_call and ignore settings.\"\"\"",
"return",
"api_call",
"(",
"*",
"args",
")",
"def",
"inner",
"(",
"request",
",",
"options",
"=",
"None",
")",
":",
"\"\"\"Invoke with the actual settings.\"\"\"",
"this_options",
"=",
"_merge_options_metadata",
"(",
"options",
",",
"settings",
")",
"this_settings",
"=",
"settings",
".",
"merge",
"(",
"this_options",
")",
"if",
"this_settings",
".",
"retry",
"and",
"this_settings",
".",
"retry",
".",
"retry_codes",
":",
"api_call",
"=",
"gax",
".",
"retry",
".",
"retryable",
"(",
"func",
",",
"this_settings",
".",
"retry",
",",
"*",
"*",
"this_settings",
".",
"kwargs",
")",
"else",
":",
"api_call",
"=",
"gax",
".",
"retry",
".",
"add_timeout_arg",
"(",
"func",
",",
"this_settings",
".",
"timeout",
",",
"*",
"*",
"this_settings",
".",
"kwargs",
")",
"api_call",
"=",
"_catch_errors",
"(",
"api_call",
",",
"gax",
".",
"config",
".",
"API_ERRORS",
")",
"return",
"api_caller",
"(",
"api_call",
",",
"this_settings",
",",
"request",
")",
"if",
"settings",
".",
"page_descriptor",
":",
"if",
"settings",
".",
"bundler",
"and",
"settings",
".",
"bundle_descriptor",
":",
"raise",
"ValueError",
"(",
"'The API call has incompatible settings: '",
"'bundling and page streaming'",
")",
"api_caller",
"=",
"_page_streamable",
"(",
"settings",
".",
"page_descriptor",
")",
"elif",
"settings",
".",
"bundler",
"and",
"settings",
".",
"bundle_descriptor",
":",
"api_caller",
"=",
"_bundleable",
"(",
"settings",
".",
"bundle_descriptor",
")",
"else",
":",
"api_caller",
"=",
"base_caller",
"return",
"inner"
] |
Show uploaded runlists . | def runlist_list ( * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'runlist:list' , * * { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , } ) | 6,390 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L990-L997 | [
"def",
"create_api_call",
"(",
"func",
",",
"settings",
")",
":",
"def",
"base_caller",
"(",
"api_call",
",",
"_",
",",
"*",
"args",
")",
":",
"\"\"\"Simply call api_call and ignore settings.\"\"\"",
"return",
"api_call",
"(",
"*",
"args",
")",
"def",
"inner",
"(",
"request",
",",
"options",
"=",
"None",
")",
":",
"\"\"\"Invoke with the actual settings.\"\"\"",
"this_options",
"=",
"_merge_options_metadata",
"(",
"options",
",",
"settings",
")",
"this_settings",
"=",
"settings",
".",
"merge",
"(",
"this_options",
")",
"if",
"this_settings",
".",
"retry",
"and",
"this_settings",
".",
"retry",
".",
"retry_codes",
":",
"api_call",
"=",
"gax",
".",
"retry",
".",
"retryable",
"(",
"func",
",",
"this_settings",
".",
"retry",
",",
"*",
"*",
"this_settings",
".",
"kwargs",
")",
"else",
":",
"api_call",
"=",
"gax",
".",
"retry",
".",
"add_timeout_arg",
"(",
"func",
",",
"this_settings",
".",
"timeout",
",",
"*",
"*",
"this_settings",
".",
"kwargs",
")",
"api_call",
"=",
"_catch_errors",
"(",
"api_call",
",",
"gax",
".",
"config",
".",
"API_ERRORS",
")",
"return",
"api_caller",
"(",
"api_call",
",",
"this_settings",
",",
"request",
")",
"if",
"settings",
".",
"page_descriptor",
":",
"if",
"settings",
".",
"bundler",
"and",
"settings",
".",
"bundle_descriptor",
":",
"raise",
"ValueError",
"(",
"'The API call has incompatible settings: '",
"'bundling and page streaming'",
")",
"api_caller",
"=",
"_page_streamable",
"(",
"settings",
".",
"page_descriptor",
")",
"elif",
"settings",
".",
"bundler",
"and",
"settings",
".",
"bundle_descriptor",
":",
"api_caller",
"=",
"_bundleable",
"(",
"settings",
".",
"bundle_descriptor",
")",
"else",
":",
"api_caller",
"=",
"base_caller",
"return",
"inner"
] |
Show configuration content for a specified runlist . | def runlist_view ( name , * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'runlist:view' , * * { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , 'name' : name } ) | 6,391 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1003-L1011 | [
"def",
"setGroups",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"requests",
"=",
"0",
"groups",
"=",
"[",
"]",
"try",
":",
"for",
"gk",
"in",
"self",
"[",
"'groupKeys'",
"]",
":",
"try",
":",
"g",
"=",
"self",
".",
"mambugroupclass",
"(",
"entid",
"=",
"gk",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"AttributeError",
"as",
"ae",
":",
"from",
".",
"mambugroup",
"import",
"MambuGroup",
"self",
".",
"mambugroupclass",
"=",
"MambuGroup",
"g",
"=",
"self",
".",
"mambugroupclass",
"(",
"entid",
"=",
"gk",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"requests",
"+=",
"1",
"groups",
".",
"append",
"(",
"g",
")",
"except",
"KeyError",
":",
"pass",
"self",
"[",
"'groups'",
"]",
"=",
"groups",
"return",
"requests"
] |
Upload runlist with context into the storage . | def runlist_upload ( name , runlist , * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'runlist:upload' , * * { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , 'name' : name , 'runlist' : runlist , } ) | 6,392 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1034-L1043 | [
"def",
"on_predicate",
"(",
"wait_gen",
",",
"predicate",
"=",
"operator",
".",
"not_",
",",
"max_tries",
"=",
"None",
",",
"max_time",
"=",
"None",
",",
"jitter",
"=",
"full_jitter",
",",
"on_success",
"=",
"None",
",",
"on_backoff",
"=",
"None",
",",
"on_giveup",
"=",
"None",
",",
"logger",
"=",
"'backoff'",
",",
"*",
"*",
"wait_gen_kwargs",
")",
":",
"def",
"decorate",
"(",
"target",
")",
":",
"# change names because python 2.x doesn't have nonlocal",
"logger_",
"=",
"logger",
"if",
"isinstance",
"(",
"logger_",
",",
"basestring",
")",
":",
"logger_",
"=",
"logging",
".",
"getLogger",
"(",
"logger_",
")",
"on_success_",
"=",
"_config_handlers",
"(",
"on_success",
")",
"on_backoff_",
"=",
"_config_handlers",
"(",
"on_backoff",
",",
"_log_backoff",
",",
"logger_",
")",
"on_giveup_",
"=",
"_config_handlers",
"(",
"on_giveup",
",",
"_log_giveup",
",",
"logger_",
")",
"retry",
"=",
"None",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"5",
")",
":",
"# pragma: python=3.5",
"import",
"asyncio",
"if",
"asyncio",
".",
"iscoroutinefunction",
"(",
"target",
")",
":",
"import",
"backoff",
".",
"_async",
"retry",
"=",
"backoff",
".",
"_async",
".",
"retry_predicate",
"elif",
"_is_event_loop",
"(",
")",
"and",
"_is_current_task",
"(",
")",
":",
"# Verify that sync version is not being run from coroutine",
"# (that would lead to event loop hiccups).",
"raise",
"TypeError",
"(",
"\"backoff.on_predicate applied to a regular function \"",
"\"inside coroutine, this will lead to event loop \"",
"\"hiccups. Use backoff.on_predicate on coroutines in \"",
"\"asynchronous code.\"",
")",
"if",
"retry",
"is",
"None",
":",
"retry",
"=",
"_sync",
".",
"retry_predicate",
"return",
"retry",
"(",
"target",
",",
"wait_gen",
",",
"predicate",
",",
"max_tries",
",",
"max_time",
",",
"jitter",
",",
"on_success_",
",",
"on_backoff_",
",",
"on_giveup_",
",",
"wait_gen_kwargs",
")",
"# Return a function which decorates a target with a retry loop.",
"return",
"decorate"
] |
Create runlist and upload it into the storage . | def runlist_create ( name , * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'runlist:create' , * * { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , 'name' : name , } ) | 6,393 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1049-L1057 | [
"def",
"plot_correlation_heatmap",
"(",
"self",
")",
":",
"data",
"=",
"None",
"corr_type",
"=",
"None",
"correlation_type",
"=",
"getattr",
"(",
"config",
",",
"'rna_seqc'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'default_correlation'",
",",
"'spearman'",
")",
"if",
"self",
".",
"rna_seqc_spearman",
"is",
"not",
"None",
"and",
"correlation_type",
"!=",
"'pearson'",
":",
"data",
"=",
"self",
".",
"rna_seqc_spearman",
"corr_type",
"=",
"'Spearman'",
"elif",
"self",
".",
"rna_seqc_pearson",
"is",
"not",
"None",
":",
"data",
"=",
"self",
".",
"rna_seqc_pearson",
"corr_type",
"=",
"'Pearson'",
"if",
"data",
"is",
"not",
"None",
":",
"pconfig",
"=",
"{",
"'id'",
":",
"'rna_seqc_correlation_heatmap'",
",",
"'title'",
":",
"'RNA-SeQC: {} Sample Correlation'",
".",
"format",
"(",
"corr_type",
")",
"}",
"self",
".",
"add_section",
"(",
"name",
"=",
"'{} Correlation'",
".",
"format",
"(",
"corr_type",
")",
",",
"anchor",
"=",
"'rseqc-rna_seqc_correlation'",
",",
"plot",
"=",
"heatmap",
".",
"plot",
"(",
"data",
"[",
"1",
"]",
",",
"data",
"[",
"0",
"]",
",",
"data",
"[",
"0",
"]",
",",
"pconfig",
")",
")"
] |
Remove runlist from the storage . | def runlist_remove ( name , * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'runlist:remove' , * * { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , 'name' : name , } ) | 6,394 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1063-L1071 | [
"def",
"rmarkdown_draft",
"(",
"filename",
",",
"template",
",",
"package",
")",
":",
"if",
"file_exists",
"(",
"filename",
")",
":",
"return",
"filename",
"draft_template",
"=",
"Template",
"(",
"'rmarkdown::draft(\"$filename\", template=\"$template\", package=\"$package\", edit=FALSE)'",
")",
"draft_string",
"=",
"draft_template",
".",
"substitute",
"(",
"filename",
"=",
"filename",
",",
"template",
"=",
"template",
",",
"package",
"=",
"package",
")",
"report_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"rcmd",
"=",
"Rscript_cmd",
"(",
")",
"with",
"chdir",
"(",
"report_dir",
")",
":",
"do",
".",
"run",
"(",
"[",
"rcmd",
",",
"\"--no-environ\"",
",",
"\"-e\"",
",",
"draft_string",
"]",
",",
"\"Creating bcbioRNASeq quality control template.\"",
")",
"do",
".",
"run",
"(",
"[",
"\"sed\"",
",",
"\"-i\"",
",",
"\"s/YYYY-MM-DD\\///g\"",
",",
"filename",
"]",
",",
"\"Editing bcbioRNAseq quality control template.\"",
")",
"return",
"filename"
] |
Add specified application with profile to the specified runlist . | def runlist_add_app ( name , app , profile , force , * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'runlist:add-app' , * * { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , 'name' : name , 'app' : app , 'profile' : profile , 'force' : force } ) | 6,395 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1112-L1125 | [
"def",
"create_or_update_group_alias",
"(",
"self",
",",
"name",
",",
"alias_id",
"=",
"None",
",",
"mount_accessor",
"=",
"None",
",",
"canonical_id",
"=",
"None",
",",
"mount_point",
"=",
"DEFAULT_MOUNT_POINT",
")",
":",
"params",
"=",
"{",
"'name'",
":",
"name",
",",
"'mount_accessor'",
":",
"mount_accessor",
",",
"'canonical_id'",
":",
"canonical_id",
",",
"}",
"if",
"alias_id",
"is",
"not",
"None",
":",
"params",
"[",
"'id'",
"]",
"=",
"alias_id",
"api_path",
"=",
"'/v1/{mount_point}/group-alias'",
".",
"format",
"(",
"mount_point",
"=",
"mount_point",
")",
"response",
"=",
"self",
".",
"_adapter",
".",
"post",
"(",
"url",
"=",
"api_path",
",",
"json",
"=",
"params",
",",
")",
"return",
"response",
".",
"json",
"(",
")"
] |
Show crashlogs status . | def crashlog_status ( * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'crashlog:status' , * * { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , } ) | 6,396 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1146-L1153 | [
"def",
"has_uncacheable_headers",
"(",
"self",
",",
"response",
")",
":",
"cc_dict",
"=",
"get_header_dict",
"(",
"response",
",",
"'Cache-Control'",
")",
"if",
"cc_dict",
":",
"if",
"'max-age'",
"in",
"cc_dict",
"and",
"cc_dict",
"[",
"'max-age'",
"]",
"==",
"'0'",
":",
"return",
"True",
"if",
"'no-cache'",
"in",
"cc_dict",
":",
"return",
"True",
"if",
"'private'",
"in",
"cc_dict",
":",
"return",
"True",
"if",
"response",
".",
"has_header",
"(",
"'Expires'",
")",
":",
"if",
"parse_http_date",
"(",
"response",
"[",
"'Expires'",
"]",
")",
"<",
"time",
".",
"time",
"(",
")",
":",
"return",
"True",
"return",
"False"
] |
Show crashlogs list for application . | def crashlog_list ( name , day , * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'crashlog:list' , * * { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , 'name' : name , 'day_string' : day , } ) | 6,397 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1160-L1175 | [
"def",
"add_reference",
"(",
"self",
",",
"source",
",",
"target",
",",
"*",
"*",
"kwargs",
")",
":",
"# Tweak keyword arguments for addReference",
"addRef_kw",
"=",
"kwargs",
".",
"copy",
"(",
")",
"addRef_kw",
".",
"setdefault",
"(",
"\"referenceClass\"",
",",
"self",
".",
"referenceClass",
")",
"if",
"\"schema\"",
"in",
"addRef_kw",
":",
"del",
"addRef_kw",
"[",
"\"schema\"",
"]",
"uid",
"=",
"api",
".",
"get_uid",
"(",
"target",
")",
"rc",
"=",
"api",
".",
"get_tool",
"(",
"\"reference_catalog\"",
")",
"# throws IndexError if uid is invalid",
"rc",
".",
"addReference",
"(",
"source",
",",
"uid",
",",
"self",
".",
"relationship",
",",
"*",
"*",
"addRef_kw",
")",
"# link the version of the reference",
"self",
".",
"link_version",
"(",
"source",
",",
"target",
")"
] |
Show crashlog for application with specified timestamp . | def crashlog_view ( name , timestamp , * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'crashlog:view' , * * { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , 'name' : name , 'timestamp' : timestamp , } ) | 6,398 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1182-L1193 | [
"def",
"get_variations",
"(",
"self",
")",
":",
"variations",
"=",
"cairo",
".",
"cairo_font_options_get_variations",
"(",
"self",
".",
"_pointer",
")",
"if",
"variations",
"!=",
"ffi",
".",
"NULL",
":",
"return",
"ffi",
".",
"string",
"(",
"variations",
")",
".",
"decode",
"(",
"'utf8'",
",",
"'replace'",
")"
] |
Remove all crashlogs for application from the storage . | def crashlog_removeall ( name , * * kwargs ) : ctx = Context ( * * kwargs ) ctx . execute_action ( 'crashlog:removeall' , * * { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , 'name' : name , } ) | 6,399 | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1215-L1223 | [
"def",
"_proc_member",
"(",
"self",
",",
"tarfile",
")",
":",
"if",
"self",
".",
"type",
"in",
"(",
"GNUTYPE_LONGNAME",
",",
"GNUTYPE_LONGLINK",
")",
":",
"return",
"self",
".",
"_proc_gnulong",
"(",
"tarfile",
")",
"elif",
"self",
".",
"type",
"==",
"GNUTYPE_SPARSE",
":",
"return",
"self",
".",
"_proc_sparse",
"(",
"tarfile",
")",
"elif",
"self",
".",
"type",
"in",
"(",
"XHDTYPE",
",",
"XGLTYPE",
",",
"SOLARIS_XHDTYPE",
")",
":",
"return",
"self",
".",
"_proc_pax",
"(",
"tarfile",
")",
"else",
":",
"return",
"self",
".",
"_proc_builtin",
"(",
"tarfile",
")"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.