Instantiate the connection to the InfluxDB client.
978427
def main(host='localhost', port=8086):
    """"""
    user = 'root'
    password = 'root'
    dbname = 'demo'
    protocol = 'json'

    client = DataFrameClient(host, port, user, password, dbname)

    print("Create pandas DataFrame")
    df = pd.DataFrame(data=list(range(30)),
                      index=pd.date_range(start='2014-11-16',
                                          periods=30, freq='H'), columns=['0'])

    print("Create database: " + dbname)
    client.create_database(dbname)

    print("Write DataFrame")
    client.write_points(df, 'demo', protocol=protocol)

    print("Write DataFrame with Tags")
    client.write_points(df, 'demo',
                        {'k1': 'v1', 'k2': 'v2'}, protocol=protocol)

    print("Read DataFrame")
    client.query("select * from demo")

    print("Delete database: " + dbname)
    client.drop_database(dbname)
317466
def connect(self):
        ""
        if self._sock:
            return
        try:
            sock = self._connect()
        except socket.timeout:
            raise TimeoutError("Timeout connecting to server")
        except socket.error:
            e = sys.exc_info()[1]
            raise ConnectionError(self._error_message(e))

        self._sock = sock
        self._selector = DefaultSelector(sock)
        try:
            self.on_connect()
        except RedisError:
            # clean up after any error in on_connect
            self.disconnect()
            raise

        # run any user callbacks. right now the only internal callback
        # is for pubsub channel/pattern resubscription
        for callback in self._connect_callbacks:
            callback(self)
1027054
async def init():
    """"""
    global redis_conn  # pylint: disable=global-statement,invalid-name
    conn = await aioredis.create_connection(
        'redis://{}:{}'.format(
            SETTINGS.get('FLOW_EXECUTOR', {}).get('REDIS_CONNECTION', {}).get('host', 'localhost'),
            SETTINGS.get('FLOW_EXECUTOR', {}).get('REDIS_CONNECTION', {}).get('port', 56379)
        ),
        db=int(SETTINGS.get('FLOW_EXECUTOR', {}).get('REDIS_CONNECTION', {}).get('db', 1))
    )
    redis_conn = aioredis.Redis(conn)
651082
def setup_influxdb(self, config):
        
        base_tags = {
            'version': self.consumer_version
        }
        measurement = self.config.get('influxdb_measurement',
                                      os.environ.get('SERVICE'))
        if measurement != self.consumer_name:
            base_tags['consumer'] = self.consumer_name
        for key in {'ENVIRONMENT', 'SERVICE'}:
            if key in os.environ:
                base_tags[key.lower()] = os.environ[key]
        influxdb.install(
            '{}://{}:{}/write'.format(
                config.get('scheme',
                           os.environ.get('INFLUXDB_SCHEME', 'http')),
                config.get('host',
                           os.environ.get('INFLUXDB_HOST', 'localhost')),
                config.get('port', os.environ.get('INFLUXDB_PORT', '8086'))
            ),
            config.get('user', os.environ.get('INFLUXDB_USER')),
            config.get('password', os.environ.get('INFLUXDB_PASSWORD')),
            base_tags=base_tags)
        return config.get('database', 'rejected'), measurement
1016864
def connect(self, origin=None):
        
        self.logger.debug('Establish connection...')

        if self.connected:
            self.logger.warning('Connection already established. Return...')
            return

        if origin is not None:
            self.origin = origin

        self.auto_reconnect = True

        self.ws_thread = threading.Thread(
            name="APIConnectionThread_{}".format(uuid.uuid1()),
            target=self._run_forever)
        self.ws_thread.daemon = True
        self.ws_thread.start()
545155
def setup_instrumentation(self):
        
        if not self.config.get('stats') and not self.config.get('statsd'):
            return

        if 'stats' not in self.config:
            self.config['stats'] = {}

        # Backwards compatible statsd config support
        if self.config.get('statsd'):
            warnings.warn('Deprecated statsd configuration detected',
                          DeprecationWarning)
            self.config['stats'].setdefault('statsd',
                                            self.config.get('statsd'))

        if self.config['stats'].get('statsd'):
            if self.config['stats']['statsd'].get('enabled', True):
                self.statsd = statsd.Client(self.consumer_name,
                                            self.config['stats']['statsd'])
            LOGGER.debug('statsd measurements configured')

        # InfluxDB support
        if influxdb and self.config['stats'].get('influxdb'):
            if self.config['stats']['influxdb'].get('enabled', True):
                self.influxdb = self.setup_influxdb(
                    self.config['stats']['influxdb'])
            LOGGER.debug('InfluxDB measurements configured: %r', self.influxdb)
749726
async def connect(self, req: 'ClientRequest',
                      traces: List['Trace'],
                      timeout: 'ClientTimeout') -> Connection:
        """"""
        key = req.connection_key
        available = self._available_connections(key)

        # Wait if there are no available connections.
        if available <= 0:
            fut = self._loop.create_future()

            # This connection will now count towards the limit.
            waiters = self._waiters[key]
            waiters.append(fut)

            if traces:
                for trace in traces:
                    await trace.send_connection_queued_start()

            try:
                await fut
            except BaseException as e:
                # remove a waiter even if it was cancelled, normally it's
                #  removed when it's notified
                try:
                    waiters.remove(fut)
                except ValueError:  # fut may no longer be in list
                    pass

                raise e
            finally:
                if not waiters:
                    try:
                        del self._waiters[key]
                    except KeyError:
                        # the key was evicted before.
                        pass

            if traces:
                for trace in traces:
                    await trace.send_connection_queued_end()

        proto = self._get(key)
        if proto is None:
            placeholder = cast(ResponseHandler, _TransportPlaceholder())
            self._acquired.add(placeholder)
            self._acquired_per_host[key].add(placeholder)

            if traces:
                for trace in traces:
                    await trace.send_connection_create_start()

            try:
                proto = await self._create_connection(req, traces, timeout)
                if self._closed:
                    proto.close()
                    raise ClientConnectionError("Connector is closed.")
            except BaseException:
                if not self._closed:
                    self._acquired.remove(placeholder)
                    self._drop_acquired_per_host(key, placeholder)
                    self._release_waiter()
                raise
            else:
                if not self._closed:
                    self._acquired.remove(placeholder)
                    self._drop_acquired_per_host(key, placeholder)

            if traces:
                for trace in traces:
                    await trace.send_connection_create_end()
        else:
            if traces:
                for trace in traces:
                    await trace.send_connection_reuseconn()

        self._acquired.add(proto)
        self._acquired_per_host[key].add(proto)
        return Connection(self, key, proto, self._loop)
1118796
def _create_connection(self):
        
        transport = SSL if self.ssl else TCP
        return transport(self.server, self.port)
162978
public void connect() throws DBException {
        try {
            LOGGER.debug("Initializing MongoDB client");
            mongoClient = new MongoClient(this.host, this.port);
        } catch (UnknownHostException e) {
            throw new DBException(e.toString());

        }
    }
1249244
void establishConnection () throws IOException {
        synchronized (operationOnConnectionMonitor) {
            if (state == State.CLOSED) {
                throw new IOException("Attempt to establish a connection with a closed connection factory");
            } else if (state == State.CONNECTED) {
                LOGGER.warn("Establishing new connection although a connection is already established");
            }
            try {
                LOGGER.info("Trying to establish connection to {}:{}", getHost(), getPort());
                connection = super.newConnection(executorService);
                connection.addShutdownListener(connectionShutdownListener);
                LOGGER.info("Established connection to {}:{}", getHost(), getPort());
                changeState(State.CONNECTED);
            } catch (IOException e) {
                LOGGER.error("Failed to establish connection to {}:{}", getHost(), getPort());
                throw e;
            }
        }
    }
328384
def main():
    """"""
    parser = argparse.ArgumentParser()
    parser.add_argument('-u', '--username',
                        help='Hydro Quebec username')
    parser.add_argument('-p', '--password',
                        help='Password')
    parser.add_argument('-j', '--json', action='store_true',
                        default=False, help='Json output')
    parser.add_argument('-i', '--influxdb', action='store_true',
                        default=False, help='InfluxDb output')
    parser.add_argument('-c', '--contract',
                        default=None, help='Contract number')
    parser.add_argument('-l', '--list-contracts', action='store_true',
                        default=False, help='List all your contracts')
    parser.add_argument('-H', '--hourly', action='store_true',
                        default=False, help='Show yesterday hourly consumption')
    parser.add_argument('-t', '--timeout',
                        default=REQUESTS_TIMEOUT, help='Request timeout')
    parser.add_argument('-V', '--version', action='store_true',
                        default=False, help='Show version')
    raw_group = parser.add_argument_group('Detailled-energy raw download option')
    raw_group.add_argument('--detailled-energy', action='store_true',
                           default=False, help='Get raw json output download')
    raw_group.add_argument('--start-date',
                           default=(datetime.datetime.now(HQ_TIMEZONE) -
                                    datetime.timedelta(days=1)).strftime("%Y-%m-%d"),
                           help='Start date for detailled-output')
    raw_group.add_argument('--end-date',
                           default=datetime.datetime.now(HQ_TIMEZONE).strftime("%Y-%m-%d"),
                           help="End date for detailled-output")

    args = parser.parse_args()

    if args.version:
        print(VERSION)
        return 0

    if not args.username or not args.password:
        parser.print_usage()
        print("pyhydroquebec: error: the following arguments are required: "
              "-u/--username, -p/--password")
        return 3

    client = HydroQuebecClient(args.username, args.password, args.timeout)
    loop = asyncio.get_event_loop()

    if args.detailled_energy is False:
        async_func = client.fetch_data()
    else:
        start_date = datetime.datetime.strptime(args.start_date, '%Y-%m-%d')
        end_date = datetime.datetime.strptime(args.end_date, '%Y-%m-%d')
        async_func = client.fetch_data_detailled_energy_use(start_date,
                                                            end_date)
    try:
        fut = asyncio.wait([async_func])
        loop.run_until_complete(fut)
    except BaseException as exp:
        print(exp)
        return 1
    finally:
        close_fut = asyncio.wait([client.close_session()])
        loop.run_until_complete(close_fut)

    if not client.get_data():
        return 2

    if args.list_contracts:
        print("Contracts: {}".format(", ".join(client.get_contracts())))
    elif args.influxdb:
        output_influx(client.get_data(args.contract))
    elif args.json or args.detailled_energy:
        output_json(client.get_data(args.contract))
    else:
        output_text(args.username, client.get_data(args.contract), args.hourly)
    return 0
1370120
def get_db():
    """"""
    return client.InfluxDBClient(
        settings.INFLUXDB_HOST,
        settings.INFLUXDB_PORT,
        settings.INFLUXDB_USER,
        settings.INFLUXDB_PASSWORD,
        settings.INFLUXDB_DATABASE,
    )
1205041
def instantiate_client(self, config):
        
        modules = config.module.split('.')
        class_name = modules.pop()
        module_path = '.'.join(modules)

        client_instance = getattr(
            __import__(module_path, {}, {}, ['']),
            class_name
        )()

        client_instance.add_config(config)

        return client_instance
490112
def main(host='localhost', port=8086, nb_day=15):
    """"""
    nb_day = 15  # number of day to generate time series
    timeinterval_min = 5  # create an event every x minutes
    total_minutes = 1440 * nb_day
    total_records = int(total_minutes / timeinterval_min)
    now = datetime.datetime.today()
    metric = "server_data.cpu_idle"
    series = []

    for i in range(0, total_records):
        past_date = now - datetime.timedelta(minutes=i * timeinterval_min)
        value = random.randint(0, 200)
        hostName = "server-%d" % random.randint(1, 5)
        # pointValues = [int(past_date.strftime('%s')), value, hostName]
        pointValues = {
            "time": int(past_date.strftime('%s')),
            "measurement": metric,
            "fields": {
                "value": value,
            },
            "tags": {
                "hostName": hostName,
            },
        }
        series.append(pointValues)

    print(series)

    client = InfluxDBClient(host, port, USER, PASSWORD, DBNAME)

    print("Create database: " + DBNAME)
    try:
        client.create_database(DBNAME)
    except InfluxDBClientError:
        # Drop and create
        client.drop_database(DBNAME)
        client.create_database(DBNAME)

    print("Create a retention policy")
    retention_policy = 'server_data'
    client.create_retention_policy(retention_policy, '3d', 3, default=True)

    print("Write points #: {0}".format(total_records))
    client.write_points(series, retention_policy=retention_policy)

    time.sleep(2)

    query = "SELECT MEAN(value) FROM {} WHERE \
            time > now() - 10d GROUP BY time(500m)".format(metric)
    result = client.query(query, database=DBNAME)
    print(result)
    print("Result: {0}".format(result))

    print("Drop database: {}".format(DBNAME))
    client.drop_database(DBNAME)
1018050
def connect(self):
        """"""
        self.socket = socket.create_connection(self.address, self.timeout)
735327
def open(self):
        """"""
        self._id = str(uuid.uuid4())
        self._client.open_connection(self._id, info=self._connection_args)
1100348
def create_connection(self, room, ws_url, agent, cookies):
        """"""

        urlparts = urlsplit(ws_url)
        req = Request("GET", ws_url)
        cookies = get_cookie_header(cookies, req)
        if cookies:
            headers = dict(Cookie=cookies)
        else:
            headers = None

        factory = WebSocketClientFactory(ws_url, headers=headers, loop=self.loop)
        factory.useragent = agent
        factory.protocol = lambda: room
        conn = self.loop.create_connection(
            factory,
            host=urlparts.netloc,
            port=urlparts.port or 443,
            ssl=urlparts.scheme == "wss",
        )
        asyncio.ensure_future(conn, loop=self.loop)