_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q32900
TwistedConnectionProtocol.connectionMade
train
def connectionMade(self): """ Callback function that is called when a connection has succeeded. Reaches back to the Connection object and confirms that the connection is ready. """ try: # Non SSL connection self.connection = self.transport.connect...
python
{ "resource": "" }
q32901
TwistedConnectionClientFactory.clientConnectionFailed
train
def clientConnectionFailed(self, connector, reason): """ Overridden twisted callback which is called when the connection attempt fails. """ log.debug("Connect failed: %s", reason) self.conn.defunct(reason.value)
python
{ "resource": "" }
q32902
TwistedConnection.add_connection
train
def add_connection(self): """ Convenience function to connect and store the resulting connector. """ if self.ssl_options: if not _HAS_SSL: raise ImportError( str(e) + ', pyOpenSSL must be installed to enable SSL...
python
{ "resource": "" }
q32903
TwistedConnection.client_connection_made
train
def client_connection_made(self, transport): """ Called by twisted protocol when a connection attempt has succeeded. """ with self.lock: self.is_closed = False self.transport = transport self._send_options_message()
python
{ "resource": "" }
q32904
TwistedConnection.close
train
def close(self): """ Disconnect and error-out all requests. """ with self.lock: if self.is_closed: return self.is_closed = True log.debug("Closing connection (%s) to %s", id(self), self.endpoint) reactor.callFromThread(self.connect...
python
{ "resource": "" }
q32905
MonotonicTimestampGenerator._next_timestamp
train
def _next_timestamp(self, now, last): """ Returns the timestamp that should be used if ``now`` is the current time and ``last`` is the last timestamp returned by this object. Intended for internal and testing use only; to generate timestamps, call an instantiated ``MonotonicTimes...
python
{ "resource": "" }
q32906
BaseModel._get_column_by_db_name
train
def _get_column_by_db_name(cls, name): """ Returns the column, mapped by db_field name """ return cls._columns.get(cls._db_map.get(name, name))
python
{ "resource": "" }
q32907
BaseModel._as_dict
train
def _as_dict(self): """ Returns a map of column names to cleaned values """ values = self._dynamic_columns or {} for name, col in self._columns.items(): values[name] = col.to_database(getattr(self, name, None)) return values
python
{ "resource": "" }
q32908
BaseModel.create
train
def create(cls, **kwargs): """ Create an instance of this model in the database. Takes the model column values as keyword arguments. Setting a value to `None` is equivalent to running a CQL `DELETE` on that column. Returns the instance. """ extra_columns = set(k...
python
{ "resource": "" }
q32909
BaseModel.save
train
def save(self): """ Saves an object to the database. .. code-block:: python #create a person instance person = Person(first_name='Kimberly', last_name='Eggleston') #saves it to Cassandra person.save() """ # handle polymorphic mod...
python
{ "resource": "" }
q32910
BaseModel.update
train
def update(self, **values): """ Performs an update on the model instance. You can pass in values to set on the model for updating, or you can call without values to execute an update against any modified fields. If no fields on the model have been modified since loading, no query will be...
python
{ "resource": "" }
q32911
BaseModel.delete
train
def delete(self): """ Deletes the object from the database """ self.__dmlquery__(self.__class__, self, batch=self._batch, timestamp=self._timestamp, consistency=self.__consistency__, t...
python
{ "resource": "" }
q32912
BaseModel.get_changed_columns
train
def get_changed_columns(self): """ Returns a list of the columns that have been updated since instantiation or save """ return [k for k, v in self._values.items() if v.changed]
python
{ "resource": "" }
q32913
ProtocolVersion.get_lower_supported
train
def get_lower_supported(cls, previous_version): """ Return the lower supported protocol version. Beta versions are omitted. """ try: version = next(v for v in sorted(ProtocolVersion.SUPPORTED_VERSIONS, reverse=True) if v not in ProtocolVersion.BETA_...
python
{ "resource": "" }
q32914
BaseClause.update_context
train
def update_context(self, ctx): """ updates the query context with this clauses values """ assert isinstance(ctx, dict) ctx[str(self.context_id)] = self.value
python
{ "resource": "" }
q32915
Connection.get_request_id
train
def get_request_id(self): """ This must be called while self.lock is held. """ try: return self.request_ids.popleft() except IndexError: new_request_id = self.highest_request_id + 1 # in_flight checks should guarantee this assert ne...
python
{ "resource": "" }
q32916
Connection.register_watcher
train
def register_watcher(self, event_type, callback, register_timeout=None): """ Register a callback for a given event type. """ self._push_watchers[event_type].add(callback) self.wait_for_response( RegisterMessage(event_list=[event_type]), timeout=register_ti...
python
{ "resource": "" }
q32917
Metadata.rebuild_token_map
train
def rebuild_token_map(self, partitioner, token_map): """ Rebuild our view of the topology from fresh rows from the system topology tables. For internal use only. """ self.partitioner = partitioner if partitioner.endswith('RandomPartitioner'): token_cla...
python
{ "resource": "" }
q32918
KeyspaceMetadata.export_as_string
train
def export_as_string(self): """ Returns a CQL query string that can be used to recreate the entire keyspace, including user-defined types and tables. """ cql = "\n\n".join([self.as_cql_query() + ';'] + self.user_type_strings() + ...
python
{ "resource": "" }
q32919
KeyspaceMetadata.as_cql_query
train
def as_cql_query(self): """ Returns a CQL query string that can be used to recreate just this keyspace, not including user-defined types and tables. """ if self.virtual: return "// VIRTUAL KEYSPACE {}".format(protect_name(self.name)) ret = "CREATE KEYSPACE %s ...
python
{ "resource": "" }
q32920
TableMetadata.is_cql_compatible
train
def is_cql_compatible(self): """ A boolean indicating if this table can be represented as CQL in export """ if self.virtual: return False comparator = getattr(self, 'comparator', None) if comparator: # no compact storage with more than one column b...
python
{ "resource": "" }
q32921
TableMetadata.export_as_string
train
def export_as_string(self): """ Returns a string of CQL queries that can be used to recreate this table along with all indexes on it. The returned string is formatted to be human readable. """ if self._exc_info: import traceback ret = "/*\nWarning...
python
{ "resource": "" }
q32922
IndexMetadata.as_cql_query
train
def as_cql_query(self): """ Returns a CQL query that can be used to recreate this index. """ options = dict(self.index_options) index_target = options.pop("target") if self.kind != "CUSTOM": return "CREATE INDEX %s ON %s.%s (%s)" % ( protect_na...
python
{ "resource": "" }
q32923
BytesToken.from_string
train
def from_string(cls, token_string): """ `token_string` should be the string representation from the server. """ # unhexlify works fine with unicode input in everythin but pypy3, where it Raises "TypeError: 'str' does not support the buffer interface" if isinstance(token_string, six.text_type): ...
python
{ "resource": "" }
q32924
EventletConnection.service_timeouts
train
def service_timeouts(cls): """ cls._timeout_watcher runs in this loop forever. It is usually waiting for the next timeout on the cls._new_timer Event. When new timers are added, that event is set so that the watcher can wake up and possibly set an earlier timeout. """ ...
python
{ "resource": "" }
q32925
EC2MultiRegionTranslator.translate
train
def translate(self, addr): """ Reverse DNS the public broadcast_address, then lookup that hostname to get the AWS-resolved IP, which will point to the private IP address within the same datacenter. """ # get family of this address so we translate to the same family = sock...
python
{ "resource": "" }
q32926
Encoder.cql_encode_float
train
def cql_encode_float(self, val): """ Encode floats using repr to preserve precision """ if math.isinf(val): return 'Infinity' if val > 0 else '-Infinity' elif math.isnan(val): return 'NaN' else: return repr(val)
python
{ "resource": "" }
q32927
cython_protocol_handler
train
def cython_protocol_handler(colparser): """ Given a column parser to deserialize ResultMessages, return a suitable Cython-based protocol handler. There are three Cython-based protocol handlers: - obj_parser.ListParser decodes result messages into a list of tuples - obj_par...
python
{ "resource": "" }
q32928
_ProtocolHandler.encode_message
train
def encode_message(cls, msg, stream_id, protocol_version, compressor, allow_beta_protocol_version): """ Encodes a message using the specified frame parameters, and compressor :param msg: the message, typically of cassandra.protocol._MessageType, generated by the driver :param stream_id:...
python
{ "resource": "" }
q32929
_ProtocolHandler._write_header
train
def _write_header(f, version, flags, stream_id, opcode, length): """ Write a CQL protocol frame header. """ pack = v3_header_pack if version >= 3 else header_pack f.write(pack(version, flags, stream_id, opcode)) write_int(f, length)
python
{ "resource": "" }
q32930
_ProtocolHandler.decode_message
train
def decode_message(cls, protocol_version, user_type_map, stream_id, flags, opcode, body, decompressor, result_metadata): """ Decodes a native protocol message body :param protocol_version: version to use decoding contents :param user_type_map: map[keyspace name] =...
python
{ "resource": "" }
q32931
format_log_context
train
def format_log_context(msg, connection=None, keyspace=None): """Format log message to add keyspace and connection context""" connection_info = connection or 'DEFAULT_CONNECTION' if keyspace: msg = '[Connection: {0}, Keyspace: {1}] {2}'.format(connection_info, keyspace, msg) else: msg = ...
python
{ "resource": "" }
q32932
setup
train
def setup( hosts, default_keyspace, consistency=None, lazy_connect=False, retry_connect=False, **kwargs): """ Setup a the driver connection used by the mapper :param list hosts: list of hosts, (``contact_points`` for :class:`cassandra.cluster.Cluster`) :p...
python
{ "resource": "" }
q32933
Connection.setup
train
def setup(self): """Setup the connection""" global cluster, session if 'username' in self.cluster_options or 'password' in self.cluster_options: raise CQLEngineException("Username & Password are now handled by using the native driver's auth_provider") if self.lazy_connect: ...
python
{ "resource": "" }
q32934
run_in_executor
train
def run_in_executor(f): """ A decorator to run the given method in the ThreadPoolExecutor. """ @wraps(f) def new_f(self, *args, **kwargs): if self.is_shutdown: return try: future = self.executor.submit(f, self, *args, **kwargs) future.add_done_ca...
python
{ "resource": "" }
q32935
_watch_callback
train
def _watch_callback(obj_weakref, method_name, *args, **kwargs): """ A callback handler for the ControlConnection that tolerates weak references. """ obj = obj_weakref() if obj is None: return getattr(obj, method_name)(*args, **kwargs)
python
{ "resource": "" }
q32936
Cluster.register_user_type
train
def register_user_type(self, keyspace, user_type, klass): """ Registers a class to use to represent a particular user-defined type. Query parameters for this user-defined type will be assumed to be instances of `klass`. Result sets for this user-defined type will be instances of...
python
{ "resource": "" }
q32937
Cluster.connection_factory
train
def connection_factory(self, endpoint, *args, **kwargs): """ Called to create a new connection with proper configuration. Intended for internal use only. """ kwargs = self._make_connection_kwargs(endpoint, kwargs) return self.connection_class.factory(endpoint, self.connec...
python
{ "resource": "" }
q32938
Cluster.add_host
train
def add_host(self, endpoint, datacenter=None, rack=None, signal=True, refresh_nodes=True): """ Called when adding initial contact points and when the control connection subsequently discovers a new node. Returns a Host instance, and a flag indicating whether it was new in the met...
python
{ "resource": "" }
q32939
Cluster.remove_host
train
def remove_host(self, host): """ Called when the control connection observes that a node has left the ring. Intended for internal use only. """ if host and self.metadata.remove_host(host): log.info("Cassandra host %s removed", host) self.on_remove(host)
python
{ "resource": "" }
q32940
Cluster._ensure_core_connections
train
def _ensure_core_connections(self): """ If any host has fewer than the configured number of core connections open, attempt to open connections until that number is met. """ for session in tuple(self.sessions): for pool in tuple(session._pools.values()): ...
python
{ "resource": "" }
q32941
Cluster.get_control_connection_host
train
def get_control_connection_host(self): """ Returns the control connection host metadata. """ connection = self.control_connection._connection endpoint = connection.endpoint if connection else None return self.metadata.get_host(endpoint) if endpoint else None
python
{ "resource": "" }
q32942
Cluster.refresh_schema_metadata
train
def refresh_schema_metadata(self, max_schema_agreement_wait=None): """ Synchronously refresh all schema metadata. By default, the timeout for this operation is governed by :attr:`~.Cluster.max_schema_agreement_wait` and :attr:`~.Cluster.control_connection_timeout`. Passing max_...
python
{ "resource": "" }
q32943
Cluster.refresh_keyspace_metadata
train
def refresh_keyspace_metadata(self, keyspace, max_schema_agreement_wait=None): """ Synchronously refresh keyspace metadata. This applies to keyspace-level information such as replication and durability settings. It does not refresh tables, types, etc. contained in the keyspace. See :met...
python
{ "resource": "" }
q32944
Cluster.refresh_table_metadata
train
def refresh_table_metadata(self, keyspace, table, max_schema_agreement_wait=None): """ Synchronously refresh table metadata. This applies to a table, and any triggers or indexes attached to the table. See :meth:`~.Cluster.refresh_schema_metadata` for description of ``max_schema_agreemen...
python
{ "resource": "" }
q32945
Cluster.refresh_user_type_metadata
train
def refresh_user_type_metadata(self, keyspace, user_type, max_schema_agreement_wait=None): """ Synchronously refresh user defined type metadata. See :meth:`~.Cluster.refresh_schema_metadata` for description of ``max_schema_agreement_wait`` behavior """ if not self.control_connec...
python
{ "resource": "" }
q32946
Cluster.refresh_user_function_metadata
train
def refresh_user_function_metadata(self, keyspace, function, max_schema_agreement_wait=None): """ Synchronously refresh user defined function metadata. ``function`` is a :class:`cassandra.UserFunctionDescriptor`. See :meth:`~.Cluster.refresh_schema_metadata` for description of ``max_sc...
python
{ "resource": "" }
q32947
Cluster.refresh_user_aggregate_metadata
train
def refresh_user_aggregate_metadata(self, keyspace, aggregate, max_schema_agreement_wait=None): """ Synchronously refresh user defined aggregate metadata. ``aggregate`` is a :class:`cassandra.UserAggregateDescriptor`. See :meth:`~.Cluster.refresh_schema_metadata` for description of ``m...
python
{ "resource": "" }
q32948
Session.execute
train
def execute(self, query, parameters=None, timeout=_NOT_SET, trace=False, custom_payload=None, execution_profile=EXEC_PROFILE_DEFAULT, paging_state=None, host=None): """ Execute the given query and synchronously wait for the response. If an error is encountered wh...
python
{ "resource": "" }
q32949
Session.get_execution_profile
train
def get_execution_profile(self, name): """ Returns the execution profile associated with the provided ``name``. :param name: The name (or key) of the execution profile. """ profiles = self.cluster.profile_manager.profiles try: return profiles[name] ex...
python
{ "resource": "" }
q32950
Session.execution_profile_clone_update
train
def execution_profile_clone_update(self, ep, **kwargs): """ Returns a clone of the ``ep`` profile. ``kwargs`` can be specified to update attributes of the returned profile. This is a shallow clone, so any objects referenced by the profile are shared. This means Load Balancing Policy ...
python
{ "resource": "" }
q32951
Session.add_request_init_listener
train
def add_request_init_listener(self, fn, *args, **kwargs): """ Adds a callback with arguments to be called when any request is created. It will be invoked as `fn(response_future, *args, **kwargs)` after each client request is created, and before the request is sent\*. This can be used to...
python
{ "resource": "" }
q32952
Session.remove_request_init_listener
train
def remove_request_init_listener(self, fn, *args, **kwargs): """ Removes a callback and arguments from the list. See :meth:`.Session.add_request_init_listener`. """ self._request_init_callbacks.remove((fn, args, kwargs))
python
{ "resource": "" }
q32953
Session.prepare_on_all_hosts
train
def prepare_on_all_hosts(self, query, excluded_host, keyspace=None): """ Prepare the given query on all hosts, excluding ``excluded_host``. Intended for internal use only. """ futures = [] for host in tuple(self._pools.keys()): if host != excluded_host and hos...
python
{ "resource": "" }
q32954
Session.shutdown
train
def shutdown(self): """ Close all connections. ``Session`` instances should not be used for any purpose after being shutdown. """ with self._lock: if self.is_shutdown: return else: self.is_shutdown = True # PYTHON-...
python
{ "resource": "" }
q32955
Session.on_down
train
def on_down(self, host): """ Called by the parent Cluster instance when a node is marked down. Only intended for internal use. """ future = self.remove_pool(host) if future: future.add_done_callback(lambda f: self.update_created_pools())
python
{ "resource": "" }
q32956
Session._set_keyspace_for_all_pools
train
def _set_keyspace_for_all_pools(self, keyspace, callback): """ Asynchronously sets the keyspace on all pools. When all pools have set all of their connections, `callback` will be called with a dictionary of all errors that occurred, keyed by the `Host` that they occurred against...
python
{ "resource": "" }
q32957
Session.user_type_registered
train
def user_type_registered(self, keyspace, user_type, klass): """ Called by the parent Cluster instance when the user registers a new mapping from a user-defined type to a class. Intended for internal use only. """ try: ks_meta = self.cluster.metadata.keyspaces...
python
{ "resource": "" }
q32958
ControlConnection._get_and_set_reconnection_handler
train
def _get_and_set_reconnection_handler(self, new_handler): """ Called by the _ControlReconnectionHandler when a new connection is successfully created. Clears out the _reconnection_handler on this ControlConnection. """ with self._reconnection_lock: old = self...
python
{ "resource": "" }
q32959
ControlConnection._address_from_row
train
def _address_from_row(self, row): """ Parse the broadcast rpc address from a row and return it untranslated. """ addr = None if "rpc_address" in row: addr = row.get("rpc_address") # peers and local if "native_transport_address" in row: addr = row....
python
{ "resource": "" }
q32960
ResponseFuture._on_timeout
train
def _on_timeout(self, _attempts=0): """ Called when the request associated with this ResponseFuture times out. This function may reschedule itself. The ``_attempts`` parameter tracks the number of times this has happened. This parameter should only be set in those cases, where `...
python
{ "resource": "" }
q32961
ResponseFuture._execute_after_prepare
train
def _execute_after_prepare(self, host, connection, pool, response): """ Handle the response to our attempt to prepare a statement. If it succeeded, run the original query again against the same host. """ if pool: pool.return_connection(connection) if self._fi...
python
{ "resource": "" }
q32962
ResponseFuture.result
train
def result(self): """ Return the final result or raise an Exception if errors were encountered. If the final result or error has not been set yet, this method will block until it is set, or the timeout set for the request expires. Timeout is specified in the Session req...
python
{ "resource": "" }
q32963
ResponseFuture.get_query_trace
train
def get_query_trace(self, max_wait=None, query_cl=ConsistencyLevel.LOCAL_ONE): """ Fetches and returns the query trace of the last response, or `None` if tracing was not enabled. Note that this may raise an exception if there are problems retrieving the trace details from Cassan...
python
{ "resource": "" }
q32964
ResponseFuture.get_all_query_traces
train
def get_all_query_traces(self, max_wait_per=None, query_cl=ConsistencyLevel.LOCAL_ONE): """ Fetches and returns the query traces for all query pages, if tracing was enabled. See note in :meth:`~.get_query_trace` regarding possible exceptions. """ if self._query_traces: ...
python
{ "resource": "" }
q32965
ResponseFuture.add_callback
train
def add_callback(self, fn, *args, **kwargs): """ Attaches a callback function to be called when the final results arrive. By default, `fn` will be called with the results as the first and only argument. If `*args` or `**kwargs` are supplied, they will be passed through as addit...
python
{ "resource": "" }
q32966
ResultSet.was_applied
train
def was_applied(self): """ For LWT results, returns whether the transaction was applied. Result is indeterminate if called on a result that was not an LWT request or on a :class:`.query.BatchStatement` containing LWT. In the latter case either all the batch succeeds or fails. ...
python
{ "resource": "" }
q32967
Shutdown._prepair
train
def _prepair(self): '''Try to connect to the given dbus services. If successful it will return a callable dbus proxy and those arguments. ''' try: sessionbus = dbus.SessionBus() systembus = dbus.SystemBus() except: return (None, None) ...
python
{ "resource": "" }
q32968
Shutdown.shutdown
train
def shutdown(self): '''Call the dbus proxy to start the shutdown.''' if self._proxy: os.sync() self._proxy(*self._args)
python
{ "resource": "" }
q32969
App.on_app_shutdown
train
def on_app_shutdown(self, app): '''Dump profile content to disk''' if self.filewatcher: self.filewatcher.stop() if self.profile: self.upload_page.on_destroy() self.download_page.on_destroy()
python
{ "resource": "" }
q32970
async_call
train
def async_call(func, *args, callback=None): '''Call `func` in background thread, and then call `callback` in Gtk main thread. If error occurs in `func`, error will keep the traceback and passed to `callback` as second parameter. Always check `error` is not None. ''' def do_call(): result = ...
python
{ "resource": "" }
q32971
calculate_legacy_pad_amount
train
def calculate_legacy_pad_amount(H_in, pad_h, k_h, s_h): ''' This function calculate padding amount along H-axis. It can be applied to other axes. It should be only used with pooling conversion. :param H_in: input dimension along H-axis :param pad_h: padding amount at H-axis :param k_h: kernel's...
python
{ "resource": "" }
q32972
create_legacy_pad
train
def create_legacy_pad(scope, input_name, output_name, H_in, W_in, k_h, k_w, s_h, s_w, p_h, p_w, padded_value, container): ''' This function adds one Pad operator into its last argument, which is a Container object. By feeding the output of the created Pad operator into Pool operator un...
python
{ "resource": "" }
q32973
_parse_model
train
def _parse_model(topology, scope, model, inputs=None, outputs=None): ''' This is a delegate function of all top-level parsing functions. It does nothing but call a proper function to parse the given model. ''' if inputs is None: inputs = list() if outputs is None: outputs = list...
python
{ "resource": "" }
q32974
calculate_lstm_output_shapes
train
def calculate_lstm_output_shapes(operator): ''' See LSTM's conversion function for its output shapes. ''' check_input_and_output_numbers(operator, input_count_range=[1, 3], output_count_range=[1, 3]) check_input_and_output_types(operator, good_input_types=[FloatTensorType]) input_shape = operat...
python
{ "resource": "" }
q32975
get_xgb_params
train
def get_xgb_params(xgb_node): """ Retrieves parameters of a model. """ if hasattr(xgb_node, 'kwargs'): # XGBoost >= 0.7 params = xgb_node.get_xgb_params() else: # XGBoost < 0.7 params = xgb_node.__dict__ return params
python
{ "resource": "" }
q32976
_make_tensor_fixed
train
def _make_tensor_fixed(name, data_type, dims, vals, raw=False): ''' Make a TensorProto with specified arguments. If raw is False, this function will choose the corresponding proto field to store the values based on data_type. If raw is True, use "raw_data" proto field to store the values, and value...
python
{ "resource": "" }
q32977
calculate_linear_classifier_output_shapes
train
def calculate_linear_classifier_output_shapes(operator): ''' This operator maps an input feature vector into a scalar label if the number of outputs is one. If two outputs appear in this operator's output list, we should further generate a map storing all classes' probabilities. Allowed input/output pa...
python
{ "resource": "" }
q32978
is_backend_enabled
train
def is_backend_enabled(backend): """ Tells if a backend is enabled. """ if backend == "onnxruntime": try: import onnxruntime return True except ImportError: return False else: raise NotImplementedError("Not implemented for backend '{0}'".fo...
python
{ "resource": "" }
q32979
calculate_sparkml_string_indexer_output_shapes
train
def calculate_sparkml_string_indexer_output_shapes(operator): ''' This function just copy the input shape to the output because label encoder only alters input features' values, not their shape. ''' check_input_and_output_numbers(operator, output_count_range=1) check_input_and_output_types(opera...
python
{ "resource": "" }
q32980
_post_process_output
train
def _post_process_output(res): """ Applies post processings before running the comparison such as changing type from list to arrays. """ if isinstance(res, list): if len(res) == 0: return res elif len(res) == 1: return _post_process_output(res[0]) elif...
python
{ "resource": "" }
q32981
_create_column
train
def _create_column(values, dtype): "Creates a column from values with dtype" if str(dtype) == "tensor(int64)": return numpy.array(values, dtype=numpy.int64) elif str(dtype) == "tensor(float)": return numpy.array(values, dtype=numpy.float32) else: raise OnnxRuntimeAssertionError("...
python
{ "resource": "" }
q32982
calculate_gru_output_shapes
train
def calculate_gru_output_shapes(operator): ''' See GRU's conversion function for its output shapes. ''' check_input_and_output_numbers(operator, input_count_range=[1, 2], output_count_range=[1, 2]) check_input_and_output_types(operator, good_input_types=[FloatTensorType]) input_shape = operator...
python
{ "resource": "" }
q32983
Solution.delete_node_nto1
train
def delete_node_nto1(node_list, begin, node, end): # type: ([],LinkedNode, LinkedNode, LinkedNode)->[] """ delete the node which has n-input and 1-output """ if begin is None: assert node is not None begin = node.precedence elif not isinstance(begin, list...
python
{ "resource": "" }
q32984
Solution.delete_node_1ton
train
def delete_node_1ton(node_list, begin, node, end): # type: ([],LinkedNode, LinkedNode, LinkedNode)->[] """ delete the node which has 1-input and n-output """ if end is None: assert end is not None end = node.successor elif not isinstance(end, list): ...
python
{ "resource": "" }
q32985
Scope.get_onnx_variable_name
train
def get_onnx_variable_name(self, seed): ''' Retrieve the variable ID of the given seed or create one if it is the first time of seeing this seed ''' if seed in self.variable_name_mapping: return self.variable_name_mapping[seed][-1] else: return self.get_un...
python
{ "resource": "" }
q32986
Scope.find_sink_variables
train
def find_sink_variables(self): ''' Find sink variables in this scope ''' # First we assume all variables are sinks is_sink = {name: True for name in self.variables.keys()} # Then, we remove those variables which are inputs of some operators for operator in self.op...
python
{ "resource": "" }
q32987
Scope.declare_local_variable
train
def declare_local_variable(self, raw_name, type=None, prepend=False): ''' This function may create a new variable in this scope. If raw_name has been used to create other variables, the new variable will hide all other variables created using raw_name. ''' # Get unique ID for the...
python
{ "resource": "" }
q32988
Scope.declare_local_operator
train
def declare_local_operator(self, type, raw_model=None): ''' This function is used to declare new local operator. ''' onnx_name = self.get_unique_operator_name(str(type)) operator = Operator(onnx_name, self.name, type, raw_model, self.target_opset) self.operators[onnx_name...
python
{ "resource": "" }
q32989
Scope.delete_local_operator
train
def delete_local_operator(self, onnx_name): ''' Remove the operator whose onnx_name is the input onnx_name ''' if onnx_name not in self.onnx_operator_names or onnx_name not in self.operators: raise RuntimeError('The operator to be removed not found') self.onnx_operato...
python
{ "resource": "" }
q32990
Scope.delete_local_variable
train
def delete_local_variable(self, onnx_name): ''' Remove the variable whose onnx_name is the input onnx_name ''' if onnx_name not in self.onnx_variable_names or onnx_name not in self.variables: raise RuntimeError('The variable to be removed not found') self.onnx_variabl...
python
{ "resource": "" }
q32991
Topology.find_root_and_sink_variables
train
def find_root_and_sink_variables(self): ''' Find root variables of the whole graph ''' # First we assume all variables are roots is_root = {name: True for scope in self.scopes for name in scope.variables.keys()} # Then, we remove those variables which are outputs of some ...
python
{ "resource": "" }
q32992
Topology.topological_operator_iterator
train
def topological_operator_iterator(self): ''' This is an iterator of all operators in Topology object. Operators may be produced in a topological order. If you want to simply go though all operators without considering their topological structure, please use another function, unordered_op...
python
{ "resource": "" }
q32993
Topology._check_structure
train
def _check_structure(self): ''' This function applies some rules to check if the parsed model is proper. Currently, it only checks if isolated variable and isolated operator exists. ''' # Collect all variable names and operator names unused_variables = set() unuse...
python
{ "resource": "" }
q32994
Topology._initialize_graph_status_for_traversing
train
def _initialize_graph_status_for_traversing(self): ''' Initialize the status of all variables and operators for traversing the underline graph ''' # In the beginning, we set is_root and is_leaf true. For is_fed, we have two different behaviors depending on # whether root_names is...
python
{ "resource": "" }
q32995
Topology._infer_all_types
train
def _infer_all_types(self): ''' Infer all variables' shapes in the computational graph. ''' self._initialize_graph_status_for_traversing() # Deliver user-specified types to root variables for raw_name, initial_type in self.initial_types: # Check all variables...
python
{ "resource": "" }
q32996
Topology._resolve_duplicates
train
def _resolve_duplicates(self): ''' Merge variables connected by identity operator to reduce the number of redundant variables ''' self._initialize_graph_status_for_traversing() # Traverse the graph from roots to leaves for operator in self.topological_operator_iterator()...
python
{ "resource": "" }
q32997
Topology.compile
train
def compile(self): ''' This function aims at giving every operator enough information so that all operator conversions can happen independently. We also want to check, fix, and simplify the network structure here. ''' self._prune() self._resolve_duplicates() self....
python
{ "resource": "" }
q32998
convert_tensor_to_probability_map
train
def convert_tensor_to_probability_map(scope, operator, container): ''' This converter tries to convert a special operator 'TensorToProbabilityMap' into a sequence of some ONNX operators. Those operators are used to create a dictionary in which keys are class labels and values are the associated probabil...
python
{ "resource": "" }
q32999
calculate_bidirectional_lstm_output_shapes
train
def calculate_bidirectional_lstm_output_shapes(operator): ''' See bidirectional LSTM's conversion function for its output shapes. ''' check_input_and_output_numbers(operator, input_count_range=[1, 5], output_count_range=[1, 5]) check_input_and_output_types(operator, good_input_types=[FloatTensorType...
python
{ "resource": "" }