Search is not available for this dataset
text
stringlengths
75
104k
def truncate(self, table): """Send DDL to truncate the specified `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None """ truncate_sql, serial_key_sql =...
def write_table(self, table): """Send DDL to create the specified `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None """ table_sql, serial_key_sql = s...
def write_indexes(self, table): """Send DDL to create the specified `table` indexes :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None """ index_sql = super(P...
def write_triggers(self, table): """Send DDL to create the specified `table` triggers :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None """ index_sql = super...
def write_constraints(self, table): """Send DDL to create the specified `table` constraints :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None """ constraint_...
def write_contents(self, table, reader): """Write the contents of `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. - `reader`: an instance of a :py:class:`mysql2pgsql.lib.mysql...
def process_row(self, table, row): """Examines row data from MySQL and alters the values when necessary to be compatible with sending to PostgreSQL via the copy command """ for index, column in enumerate(table.columns): hash_key = hash(frozenset(column.items())) ...
def truncate(self, table): """Write DDL to truncate the specified `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None """ truncate_sql, serial_key_sql ...
def write_table(self, table): """Write DDL to create the specified `table`. :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None """ table_sql, serial_key_sql =...
def write_indexes(self, table): """Write DDL of `table` indexes to the output file :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None """ self.f.write('\n'.jo...
def write_constraints(self, table): """Write DDL of `table` constraints to the output file :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None """ self.f.write...
def write_triggers(self, table): """Write TRIGGERs existing on `table` to the output file :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None """ self.f.write(...
def write_contents(self, table, reader): """Write the data contents of `table` to the output file. :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. - `reader`: an instance of a :py:cla...
def parse_fntdata(_data, _config, _extra_data_receiver=None): """ info face="Haettenschweiler" size=60 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=2,2 common lineHeight=64 base=53 scaleW=256 scaleH=128 pages=1 packed=0 page id=0 file="attack_num.png" chars count=12 char...
def _pvr_head(_data): """ struct CCZHeader { unsigned char sig[4]; // signature. Should be 'CCZ!' 4 bytes unsigned short compression_type; // should 0 unsigned short version; // should be 2 (although version type==1 is also supported) ...
def qsize(self, extra_predicate=None): """ Return an approximate number of queued tasks in the queue. """ count = self._query_queued('COUNT(*) AS count', extra_predicate=extra_predicate) return count[0].count
def enqueue(self, data): """ Enqueue task with specified data. """ jsonified_data = json.dumps(data) with self._db_conn() as conn: return conn.execute( 'INSERT INTO %s (created, data) VALUES (%%(created)s, %%(data)s)' % self.table_name, created=datetim...
def start(self, block=False, timeout=None, retry_interval=0.5, extra_predicate=None): """ Retrieve a task handler from the queue. If block is True, this function will block until it is able to retrieve a task. If block is True and timeout is a number it will block for at most <timeout> ...
def _build_extra_predicate(self, extra_predicate): """ This method is a good one to extend if you want to create a queue which always applies an extra predicate. """ if extra_predicate is None: return '' # if they don't have a supported format seq, wrap it for them if not is...
def simplejson_datetime_serializer(obj): """ Designed to be passed as the default kwarg in simplejson.dumps. Serializes dates and datetimes to ISO strings. """ if hasattr(obj, 'isoformat'): return obj.isoformat() else: raise TypeError('Object of type %s with value of %s is not JSON ...
def reconnect(self): """Closes the existing database connection and re-opens it.""" conn = _mysql.connect(**self._db_args) if conn is not None: self.close() self._db = conn
def query(self, query, *parameters, **kwparameters): """ Query the connection and return the rows (or affected rows if not a select query). Mysql errors will be propogated as exceptions. """ return self._query(query, parameters, kwparameters)
def get(self, query, *parameters, **kwparameters): """Returns the first row returned for the given query.""" rows = self._query(query, parameters, kwparameters) if not rows: return None elif not isinstance(rows, list): raise MySQLError("Query is not a select query...
def execute(self, query, *parameters, **kwparameters): """Executes the given query, returning the lastrowid from the query.""" return self.execute_lastrowid(query, *parameters, **kwparameters)
def execute_lastrowid(self, query, *parameters, **kwparameters): """Executes the given query, returning the lastrowid from the query.""" self._execute(query, parameters, kwparameters) self._result = self._db.store_result() return self._db.insert_id()
def get_connection(db=DATABASE): """ Returns a new connection to the database. """ return database.connect(host=HOST, port=PORT, user=USER, password=PASSWORD, database=db)
def run_benchmark(): """ Run a set of InsertWorkers and record their performance. """ stopping = threading.Event() workers = [ InsertWorker(stopping) for _ in range(NUM_WORKERS) ] print('Launching %d workers' % NUM_WORKERS) [ worker.start() for worker in workers ] time.sleep(WORKLOAD_TIME) ...
def _pool_connect(self, agg): """ `agg` should be (host, port) Returns a live connection from the connection pool """ return self._pool.connect(agg[0], agg[1], self._user, self._password, self._database)
def _connect(self): """ Returns an aggregator connection. """ with self._lock: if self._aggregator: try: return self._pool_connect(self._aggregator) except PoolConnectionException: self._aggregator = None if...
def lookup_by_number(errno): """ Used for development only """ for key, val in globals().items(): if errno == val: print(key)
def size(self): """ Returns the number of connections cached by the pool. """ return sum(q.qsize() for q in self._connections.values()) + len(self._fairies)
def __potential_connection_failure(self, e): """ OperationalError's are emitted by the _mysql library for almost every error code emitted by MySQL. Because of this we verify that the error is actually a connection error before terminating the connection and firing off a PoolConnectionEx...
def simple_expression(joiner=', ', **fields): """ Build a simple expression ready to be added onto another query. >>> simple_expression(joiner=' AND ', name='bob', role='admin') "`name`=%(_QB_name)s AND `name`=%(_QB_role)s", { '_QB_name': 'bob', '_QB_role': 'admin' } """ expression, params = [], {}...
def update(table_name, **fields): """ Build a update query. >>> update('foo_table', a=5, b=2) "UPDATE `foo_table` SET `a`=%(_QB_a)s, `b`=%(_QB_b)s", { '_QB_a': 5, '_QB_b': 2 } """ prefix = "UPDATE `%s` SET " % table_name sets, params = simple_expression(', ', **fields) return prefix + sets,...
def ping(self): """ Notify the manager that this lock is still active. """ with self._db_conn() as conn: affected_rows = conn.query(''' UPDATE %s SET last_contact=%%s WHERE id = %%s AND lock_hash = %%s ''' % self._manager.table_name...
def release(self): """ Release the lock. """ if self.valid(): with self._db_conn() as conn: affected_rows = conn.query(''' DELETE FROM %s WHERE id = %%s AND lock_hash = %%s ''' % self._manager.table_name, self._lock_id, ...
def connect(self, host='127.0.0.1', port=3306, user='root', password='', database=None): """ Connect to the database specified """ if database is None: raise exceptions.RequiresDatabase() self._db_args = { 'host': host, 'port': port, 'user': user, 'password': password, 'database': ...
def setup(self): """ Initialize the required tables in the database """ with self._db_conn() as conn: for table_defn in self._tables.values(): conn.execute(table_defn) return self
def destroy(self): """ Destroy the SQLStepQueue tables in the database """ with self._db_conn() as conn: for table_name in self._tables: conn.execute('DROP TABLE IF EXISTS %s' % table_name) return self
def ready(self): """ Returns True if the tables have been setup, False otherwise """ with self._db_conn() as conn: tables = [row.t for row in conn.query(''' SELECT table_name AS t FROM information_schema.tables WHERE table_schema=%s ''', self._db_a...
def valid(self): """ Check to see if we are still active. """ if self.finished is not None: return False with self._db_conn() as conn: row = conn.get(''' SELECT (last_contact > %%(now)s - INTERVAL %%(ttl)s SECOND) AS valid FROM %s ...
def ping(self): """ Notify the queue that this task is still active. """ if self.finished is not None: raise AlreadyFinished() with self._db_conn() as conn: success = conn.query(''' UPDATE %s SET last_contact=%%(now)s, ...
def start_step(self, step_name): """ Start a step. """ if self.finished is not None: raise AlreadyFinished() step_data = self._get_step(step_name) if step_data is not None: if 'stop' in step_data: raise StepAlreadyFinished() else: ...
def stop_step(self, step_name): """ Stop a step. """ if self.finished is not None: raise AlreadyFinished() steps = copy.deepcopy(self.steps) step_data = self._get_step(step_name, steps=steps) if step_data is None: raise StepNotStarted() elif 'sto...
def _load_steps(self, raw_steps): """ load steps -> basically load all the datetime isoformats into datetimes """ for step in raw_steps: if 'start' in step: step['start'] = parser.parse(step['start']) if 'stop' in step: step['stop'] = parser.parse(...
def disconnect(self): """Disconnects from the websocket connection and joins the Thread. :return: """ self.log.debug("disconnect(): Disconnecting from API..") self.reconnect_required.clear() self.disconnect_called.set() if self.socket: self.socket.clo...
def reconnect(self): """Issues a reconnection by setting the reconnect_required event. :return: """ # Reconnect attempt at self.reconnect_interval self.log.debug("reconnect(): Initialzion reconnect sequence..") self.connected.clear() self.reconnect_required.set()...
def _connect(self): """Creates a websocket connection. :return: """ self.log.debug("_connect(): Initializing Connection..") self.socket = websocket.WebSocketApp( self.url, on_open=self._on_open, on_message=self._on_message, on_erro...
def _on_message(self, ws, message): """Handles and passes received data to the appropriate handlers. :return: """ self._stop_timers() raw, received_at = message, time.time() self.log.debug("_on_message(): Received new message %s at %s", raw, recei...
def _stop_timers(self): """Stops ping, pong and connection timers. :return: """ if self.ping_timer: self.ping_timer.cancel() if self.connection_timer: self.connection_timer.cancel() if self.pong_timer: self.pong_timer.cancel() ...
def send_ping(self): """Sends a ping message to the API and starts pong timers. :return: """ self.log.debug("send_ping(): Sending ping to API..") self.socket.send(json.dumps({'event': 'ping'})) self.pong_timer = Timer(self.pong_timeout, self._check_pong) self.pon...
def _check_pong(self): """Checks if a Pong message was received. :return: """ self.pong_timer.cancel() if self.pong_received: self.log.debug("_check_pong(): Pong received in time.") self.pong_received = False else: # reconnect ...
def send(self, api_key=None, secret=None, list_data=None, auth=False, **kwargs): """Sends the given Payload to the API via the websocket connection. :param kwargs: payload paarameters as key=value pairs :return: """ if auth: nonce = str(int(time.time() * 10000000)) ...
def pass_to_client(self, event, data, *args): """Passes data up to the client via a Queue(). :param event: :param data: :param args: :return: """ self.q.put((event, data, *args))
def _unpause(self): """Unpauses the connection. Send a message up to client that he should re-subscribe to all channels. :return: """ self.log.debug("_unpause(): Clearing paused() Flag!") self.paused.clear() self.log.debug("_unpause(): Re-subscribing sof...
def _system_handler(self, data, ts): """Distributes system messages to the appropriate handler. System messages include everything that arrives as a dict, or a list containing a heartbeat. :param data: :param ts: :return: """ self.log.debug("_system_hand...
def _response_handler(self, event, data, ts): """Handles responses to (un)subscribe and conf commands. Passes data up to client. :param data: :param ts: :return: """ self.log.debug("_response_handler(): Passing %s to client..", data) self.pass_to_client(...
def _info_handler(self, data): """ Handle INFO messages from the API and issues relevant actions. :param data: :param ts: """ def raise_exception(): """Log info code as error and raise a ValueError.""" self.log.error("%s: %s", data['code'], info_...
def _error_handler(self, data): """ Handle Error messages and log them accordingly. :param data: :param ts: """ errors = {10000: 'Unknown event', 10001: 'Generic error', 10008: 'Concurrency error', 10020: 'Request par...
def _data_handler(self, data, ts): """Handles data messages by passing them up to the client. :param data: :param ts: :return: """ # Pass the data up to the Client self.log.debug("_data_handler(): Passing %s to client..", data) self.pass...
def _resubscribe(self, soft=False): """Resubscribes to all channels found in self.channel_configs. :param soft: if True, unsubscribes first. :return: None """ # Restore non-default Bitfinex websocket configuration if self.bitfinex_config: self.send(**self.bit...
def join(self, timeout=None): """Set sentinel for run() method and join thread. :param timeout: :return: """ self._stopped.set() super(QueueProcessor, self).join(timeout=timeout)
def run(self): """Main routine. :return: """ while not self._stopped.is_set(): try: message = self.q.get(timeout=0.1) except Empty: continue dtype, data, ts = message if dtype in ('subscribed', 'unsubscribe...
def _handle_subscribed(self, dtype, data, ts,): """Handles responses to subscribe() commands. Registers a channel id with the client and assigns a data handler to it. :param dtype: :param data: :param ts: :return: """ self.log.debug("_handle_subscribed: ...
def _handle_unsubscribed(self, dtype, data, ts): """Handles responses to unsubscribe() commands. Removes a channel id from the client. :param dtype: :param data: :param ts: :return: """ self.log.debug("_handle_unsubscribed: %s - %s - %s", dtype, data, ts...
def _handle_auth(self, dtype, data, ts): """Handles authentication responses. :param dtype: :param data: :param ts: :return: """ # Contains keys status, chanId, userId, caps if dtype == 'unauth': raise NotImplementedError channel_id = ...
def _handle_conf(self, dtype, data, ts): """Handles configuration messages. :param dtype: :param data: :param ts: :return: """ self.log.debug("_handle_conf: %s - %s - %s", dtype, data, ts) self.log.info("Configuration accepted: %s", dtype) return
def update_timestamps(self, chan_id, ts): """Updates the timestamp for the given channel id. :param chan_id: :param ts: :return: """ try: self.last_update[chan_id] = ts except KeyError: self.log.warning("Attempted ts update of channel %s, ...
def _handle_account(self, data, ts): """ Handles Account related data. translation table for channel names: Data Channels os - Orders hos - Historical Orders ps - Positions hts - Trades (snapshot) te ...
def _handle_ticker(self, dtype, data, ts): """Adds received ticker data to self.tickers dict, filed under its channel id. :param dtype: :param data: :param ts: :return: """ self.log.debug("_handle_ticker: %s - %s - %s", dtype, data, ts) channel_id...
def _handle_book(self, dtype, data, ts): """Updates the order book stored in self.books[chan_id]. :param dtype: :param data: :param ts: :return: """ self.log.debug("_handle_book: %s - %s - %s", dtype, data, ts) channel_id, *data = data log.debug("...
def _handle_raw_book(self, dtype, data, ts): """Updates the raw order books stored in self.raw_books[chan_id]. :param dtype: :param data: :param ts: :return: """ self.log.debug("_handle_raw_book: %s - %s - %s", dtype, data, ts) channel_id, *data = data ...
def _handle_trades(self, dtype, data, ts): """Files trades in self._trades[chan_id]. :param dtype: :param data: :param ts: :return: """ self.log.debug("_handle_trades: %s - %s - %s", dtype, data, ts) channel_id, *data = data channel_identifier = s...
def _handle_candles(self, dtype, data, ts): """Stores OHLC data received via wss in self.candles[chan_id]. :param dtype: :param data: :param ts: :return: """ self.log.debug("_handle_candles: %s - %s - %s", dtype, data, ts) channel_id, *data = data ...
def reset(self): """Reset the client. :return: """ self.conn.reconnect() while not self.conn.connected.is_set(): log.info("reset(): Waiting for connection to be set up..") time.sleep(1) for key in self.channel_configs: self.conn.send(...
def candles(self, pair, timeframe=None): """Return a queue containing all received candles data. :param pair: str, Symbol pair to request data for :param timeframe: str :return: Queue() """ timeframe = '1m' if not timeframe else timeframe key = ('candles', pair, ...
def config(self, decimals_as_strings=True, ts_as_dates=False, sequencing=False, ts=False, **kwargs): """Send configuration to websocket server :param decimals_as_strings: bool, turn on/off decimals as strings :param ts_as_dates: bool, decide to request timestamps as dates instead...
def subscribe_to_ticker(self, pair, **kwargs): """Subscribe to the passed pair's ticker channel. :param pair: str, Symbol pair to request data for :param kwargs: :return: """ identifier = ('ticker', pair) self._subscribe('ticker', identifier, symbol=pair, **kwarg...
def unsubscribe_from_ticker(self, pair, **kwargs): """Unsubscribe to the passed pair's ticker channel. :param pair: str, Symbol pair to request data for :param kwargs: :return: """ identifier = ('ticker', pair) self._unsubscribe('ticker', identifier, symbol=pair,...
def subscribe_to_order_book(self, pair, **kwargs): """Subscribe to the passed pair's order book channel. :param pair: str, Symbol pair to request data for :param kwargs: :return: """ identifier = ('book', pair) self._subscribe('book', identifier, symbol=pair, **k...
def unsubscribe_from_order_book(self, pair, **kwargs): """Unsubscribe to the passed pair's order book channel. :param pair: str, Symbol pair to request data for :param kwargs: :return: """ identifier = ('book', pair) self._unsubscribe('book', identifier, symbol=p...
def subscribe_to_raw_order_book(self, pair, prec=None, **kwargs): """Subscribe to the passed pair's raw order book channel. :param pair: str, Symbol pair to request data for :param prec: :param kwargs: :return: """ identifier = ('raw_book', pair) prec = '...
def unsubscribe_from_raw_order_book(self, pair, prec=None, **kwargs): """Unsubscribe to the passed pair's raw order book channel. :param pair: str, Symbol pair to request data for :param prec: :param kwargs: :return: """ identifier = ('raw_book', pair) pr...
def subscribe_to_trades(self, pair, **kwargs): """Subscribe to the passed pair's trades channel. :param pair: str, Symbol pair to request data for :param kwargs: :return: """ identifier = ('trades', pair) self._subscribe('trades', identifier, symbol=pair, **kwarg...
def unsubscribe_from_trades(self, pair, **kwargs): """Unsubscribe to the passed pair's trades channel. :param pair: str, Symbol pair to request data for :param kwargs: :return: """ identifier = ('trades', pair) self._unsubscribe('trades', identifier, symbol=pair,...
def subscribe_to_candles(self, pair, timeframe=None, **kwargs): """Subscribe to the passed pair's OHLC data channel. :param pair: str, Symbol pair to request data for :param timeframe: str, {1m, 5m, 15m, 30m, 1h, 3h, 6h, 12h, 1D, 7D, 14D, 1M} :param kwarg...
def unsubscribe_from_candles(self, pair, timeframe=None, **kwargs): """Unsubscribe to the passed pair's OHLC data channel. :param timeframe: str, {1m, 5m, 15m, 30m, 1h, 3h, 6h, 12h, 1D, 7D, 14D, 1M} :param kwargs: :return: """ valid_tfs =...
def authenticate(self): """Authenticate with the Bitfinex API. :return: """ if not self.key and not self.secret: raise ValueError("Must supply both key and secret key for API!") self.channel_configs['auth'] = {'api_key': self.key, 'secret': self.secret} self....
def cancel_order(self, multi=False, **order_identifiers): """Cancel one or multiple orders via Websocket. :param multi: bool, whether order_settings contains settings for one, or multiples orders :param order_identifiers: Identifiers for the order(s) you with to cancel ...
def parseEnvVars(): """ Parse environment variables into a Python dictionary suitable for passing to the device client constructor as the `options` parameter - `WIOTP_IDENTITY_APPID` - `WIOTP_AUTH_KEY` - `WIOTP_AUTH_TOKEN` - `WIOTP_OPTIONS_DOMAIN` (optional) - `WIOTP_OPTIONS_LOGLEVEL` ...
def parseConfigFile(configFilePath): """ Parse a yaml configuration file into a Python dictionary suitable for passing to the device client constructor as the `options` parameter # Example Configuration File identity: appId: myApp auth: key: a-23gh56-sdsdajhjnee toke...
def _onCommand(self, client, userdata, pahoMessage): """ Internal callback for device command messages, parses source device from topic string and passes the information on to the registered device command callback """ try: command = Command(pahoMessage, self._message...
def _onDeviceCommand(self, client, userdata, pahoMessage): """ Internal callback for gateway command messages, parses source device from topic string and passes the information on to the registered device command callback """ try: command = Command(pahoMessage, self._...
def _onMessageNotification(self, client, userdata, pahoMessage): """ Internal callback for gateway notification messages, parses source device from topic string and passes the information on to the registered device command callback """ try: note = Notification(pahoMe...
def find(self, nameFilter=None, typeFilter=None, enabledFilter=None, serviceId=None): """ Gets the list of Historian connectors, they are used to configure the Watson IoT Platform to store IoT data in compatible services. Parameters: - nameFilter(string) - Filt...
def create(self, name, serviceId, timezone, description, enabled): """ Create a connector for the organization in the Watson IoT Platform. The connector must reference the target service that the Watson IoT Platform will store the IoT data in. Parameters: - name (string) - N...
def update(self, connectorId, name, description, timezone, enabled): """ Updates the connector with the specified uuid. if description is empty, the existing description will be removed. Parameters: - connector (String), Connnector Id which is a UUID - name (strin...
def find(self, nameFilter=None, typeFilter=None, bindingModeFilter=None, boundFilter=None): """ Gets the list of services that the Watson IoT Platform can connect to. The list can include a mixture of services that are either bound or unbound. Parameters: -...
def create(self, serviceBinding): """ Create a new external service. The service must include all of the details required to connect and authenticate to the external service in the credentials property. Parameters: - serviceName (string) - Name of the service ...
def update(self, serviceId, serviceName, credentials, description): """ Updates the service with the specified id. if description is empty, the existing description will be removed. Parameters: - serviceId (String), Service Id which is a UUID - serviceName (string...