Python string.ascii_lowercase() Examples

The following are 30 code examples of string.ascii_lowercase(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module string , or try the search function .
Example #1
Source File: bacnet_connector.py    From thingsboard-gateway with Apache License 2.0 6 votes vote down vote up
def __init__(self, gateway, config, connector_type):
        self.__connector_type = connector_type
        self.statistics = {'MessagesReceived': 0,
                           'MessagesSent': 0}
        super().__init__()
        self.__config = config
        self.setName(config.get('name', 'BACnet ' + ''.join(choice(ascii_lowercase) for _ in range(5))))
        self.__devices = []
        self.__device_indexes = {}
        self.__devices_address_name = {}
        self.__gateway = gateway
        self._application = TBBACnetApplication(self, self.__config)
        self.__bacnet_core_thread = Thread(target=run, name="BACnet core thread")
        self.__bacnet_core_thread.start()
        self.__stopped = False
        self.__config_devices = self.__config["devices"]
        self.default_converters = {"uplink_converter": TBUtility.check_and_import(self.__connector_type, "BACnetUplinkConverter"),
                                     "downlink_converter": TBUtility.check_and_import(self.__connector_type, "BACnetDownlinkConverter")}
        self.__request_functions = {"writeProperty": self._application.do_write_property,
                                    "readProperty": self._application.do_read_property}
        self.__available_object_resources = {}
        self.rpc_requests_in_progress = {}
        self.__connected = False
        self.daemon = True 
Example #2
Source File: util.py    From instavpn with Apache License 2.0 6 votes vote down vote up
def setup_passwords():
    try:
        char_set = string.ascii_lowercase + string.ascii_uppercase + string.digits
        f = open('/etc/ppp/chap-secrets', 'w')
        pw1 = gen_random_text(12)
        pw2 = gen_random_text(12)
        f.write("username1 l2tpd {} *\n".format(pw1))
        f.write("username2 l2tpd {} *".format(pw2))
        f.close()
        f = open('/etc/ipsec.secrets', 'w')
        f.write('1.2.3.4 %any: PSK "{}"'.format(gen_random_text(16)))
        f.close()
    except:
        logger.exception("Exception creating passwords:")
        return False

    return True 
Example #3
Source File: custom_serial_connector.py    From thingsboard-gateway with Apache License 2.0 6 votes vote down vote up
def __init__(self, gateway, config, connector_type):
        super().__init__()    # Initialize parents classes
        self.statistics = {'MessagesReceived': 0,
                           'MessagesSent': 0}    # Dictionary, will save information about count received and sent messages.
        self.__config = config    # Save configuration from the configuration file.
        self.__gateway = gateway    # Save gateway object, we will use some gateway methods for adding devices and saving data from them.
        self.setName(self.__config.get("name",
                                       "Custom %s connector " % self.get_name() + ''.join(choice(ascii_lowercase) for _ in range(5))))    # get from the configuration or create name for logs.
        log.info("Starting Custom %s connector", self.get_name())    # Send message to logger
        self.daemon = True    # Set self thread as daemon
        self.stopped = True    # Service variable for check state
        self.__connected = False    # Service variable for check connection to device
        self.__devices = {}    # Dictionary with devices, will contain devices configurations, converters for devices and serial port objects
        self.__load_converters(connector_type)    # Call function to load converters and save it into devices dictionary
        self.__connect_to_devices()    # Call function for connect to devices
        log.info('Custom connector %s initialization success.', self.get_name())    # Message to logger
        log.info("Devices in configuration file found: %s ", '\n'.join(device for device in self.__devices))    # Message to logger 
Example #4
Source File: pyscf_helpers.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def v2a_sym(a, labels, shapes, ixs):
    """
    Decompresses the antisymmetric array.
    Args:
        a (numpy.ndarray): array to decompress;
        labels (iterable): array's axes' labels;
        shapes (iterable): arrays' shapes;
        ixs (iterable): indexes of lower-triangle parts;

    Returns:
        Decompressed amplitude tensors.
    """
    result = []
    pos = 0
    for lbls, shape, ix in zip(labels, shapes, ixs):
        ampl = numpy.zeros(shape, dtype=a.dtype)
        end = pos + len(ix[0])
        ampl[ix] = a[pos:end]
        pos = end
        for l in set(lbls):
            letters = iter(string.ascii_lowercase)
            str_spec = ''.join(next(letters) if i == l else '.' for i in lbls)
            ampl = p(str_spec, ampl)
        result.append(ampl)
    return result 
Example #5
Source File: demodata_importer.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def create_fake_students():
    """
    Make a bunch of fake students so we can add them to classes later.
    """
    global all_students
    for lett in string.ascii_lowercase:
        for i in range(11):
            if i==10:
                userid = "0%sgrad" % (lett*3)
                fname = randname(8)
                lname = "Grad"
            else:
                userid = "0%s%i" % (lett*3, i)
                fname = randname(8)
                lname = "Student"
            p = Person(emplid=fake_emplid(), userid=userid, last_name=lname, first_name=fname, middle_name="", pref_first_name=fname[:4])
            p.save()
            all_students[userid] = p 
Example #6
Source File: test_bytes_can_uplink_converter.py    From thingsboard-gateway with Apache License 2.0 6 votes vote down vote up
def _test_string(self, encoding="ascii"):
        str_length = randint(1, 8)
        str_value = ''.join(choice(ascii_lowercase) for _ in range(str_length))

        configs = [{
            "key": "stringVar",
            "is_ts": True,
            "type": "string",
            "start": 0,
            "length": str_length,
            "encoding": encoding
        }]

        can_data = str_value.encode(encoding)
        tb_data = self.converter.convert(configs, can_data)
        self.assertEqual(tb_data["telemetry"]["stringVar"], str_value) 
Example #7
Source File: test_can_connector.py    From thingsboard-gateway with Apache License 2.0 6 votes vote down vote up
def test_string_attribute_and_custom_device_type(self):
        self._create_connector("ts_and_attr.json")
        device_name = self.config["devices"][0]["name"]
        config = self.config["devices"][0]["attributes"][0]
        value_matches = re.search(self.connector.VALUE_REGEX, config["value"])

        string_value = ''.join(choice(ascii_lowercase) for _ in range(int(value_matches.group(2))))
        can_data = list(config["command"]["value"].to_bytes(config["command"]["length"],
                                                            config["command"]["byteorder"]))
        can_data.extend(string_value.encode(value_matches.group(5)))

        message_count = 5
        for _ in range(message_count):
            self.bus.send(Message(arbitration_id=config["nodeId"],
                                  is_fd=config["isFd"],
                                  data=can_data))

        sleep(1)  # Wait while connector process CAN message

        self.assertEqual(self.gateway.send_to_storage.call_count, message_count)
        self.gateway.send_to_storage.assert_called_with(self.connector.get_name(),
                                                        {"deviceName": device_name,
                                                         "deviceType": self.config["devices"][0]["type"],
                                                         "attributes": [{"serialNumber": string_value}],
                                                         "telemetry": []}) 
Example #8
Source File: custom_serial_connector.py    From thingsboard-gateway with Apache License 2.0 6 votes vote down vote up
def __init__(self, gateway, config, connector_type):
        super().__init__()    # Initialize parents classes
        self.statistics = {'MessagesReceived': 0,
                           'MessagesSent': 0}    # Dictionary, will save information about count received and sent messages.
        self.__config = config    # Save configuration from the configuration file.
        self.__gateway = gateway    # Save gateway object, we will use some gateway methods for adding devices and saving data from them.
        self.setName(self.__config.get("name",
                                       "Custom %s connector " % self.get_name() + ''.join(choice(ascii_lowercase) for _ in range(5))))    # get from the configuration or create name for logs.
        log.info("Starting Custom %s connector", self.get_name())    # Send message to logger
        self.daemon = True    # Set self thread as daemon
        self.stopped = True    # Service variable for check state
        self.__connected = False    # Service variable for check connection to device
        self.__devices = {}    # Dictionary with devices, will contain devices configurations, converters for devices and serial port objects
        self.__load_converters(connector_type)    # Call function to load converters and save it into devices dictionary
        self.__connect_to_devices()    # Call function for connect to devices
        log.info('Custom connector %s initialization success.', self.get_name())    # Message to logger
        log.info("Devices in configuration file found: %s ", '\n'.join(device for device in self.__devices))    # Message to logger 
Example #9
Source File: rest_connector.py    From thingsboard-gateway with Apache License 2.0 6 votes vote down vote up
def __init__(self, gateway, config, connector_type):
        super().__init__()
        self.__log = log
        self._default_converters = {
            "uplink": "JsonRESTUplinkConverter",
            "downlink": "JsonRESTDownlinkConverter"
        }
        self.__config = config
        self._connector_type = connector_type
        self.statistics = {'MessagesReceived': 0,
                           'MessagesSent': 0}
        self.__gateway = gateway
        self.__USER_DATA = {}
        self.setName(config.get("name", 'REST Connector ' + ''.join(choice(ascii_lowercase) for _ in range(5))))

        self._connected = False
        self.__stopped = False
        self.daemon = True
        self._app = Flask(self.get_name())
        self._api = Api(self._app)
        self.__rpc_requests = []
        self.__attribute_updates = []
        self.__fill_requests_from_TB()
        self.endpoints = self.load_endpoints()
        self.load_handlers() 
Example #10
Source File: modbus_connector.py    From thingsboard-gateway with Apache License 2.0 6 votes vote down vote up
def __init__(self, gateway, config, connector_type):
        self.statistics = {'MessagesReceived': 0,
                           'MessagesSent': 0}
        super().__init__()
        self.__gateway = gateway
        self._connector_type = connector_type
        self.__master = None
        self.__config = config.get("server")
        self.__byte_order = self.__config.get("byteOrder")
        self.__configure_master()
        self.__devices = {}
        self.setName(self.__config.get("name",
                                       'Modbus Default ' + ''.join(choice(ascii_lowercase) for _ in range(5))))
        self.__load_converters()
        self.__connected = False
        self.__stopped = False
        self.daemon = True 
Example #11
Source File: ble_connector.py    From thingsboard-gateway with Apache License 2.0 6 votes vote down vote up
def __init__(self, gateway, config, connector_type):
        super().__init__()
        self.__connector_type = connector_type
        self.__default_services = list(range(0x1800, 0x183A))
        self.statistics = {'MessagesReceived': 0,
                           'MessagesSent': 0}
        self.__gateway = gateway
        self.__config = config
        self.setName(self.__config.get("name",
                                       'BLE Connector ' + ''.join(choice(ascii_lowercase) for _ in range(5))))

        self._connected = False
        self.__stopped = False
        self.__previous_scan_time = time.time() - 10000
        self.__previous_read_time = time.time() - 10000
        self.__check_interval_seconds = self.__config['checkIntervalSeconds'] if self.__config.get(
            'checkIntervalSeconds') is not None else 10
        self.__rescan_time = self.__config['rescanIntervalSeconds'] if self.__config.get(
            'rescanIntervalSeconds') is not None else 10
        self.__scanner = Scanner().withDelegate(ScanDelegate(self))
        self.__devices_around = {}
        self.__available_converters = []
        self.__notify_delegators = {}
        self.__fill_interest_devices()
        self.daemon = True 
Example #12
Source File: input_readers.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def __iter__(self):
    ctx = context.get()

    while self._count:
      self._count -= 1
      start_time = time.time()
      content = "".join(random.choice(string.ascii_lowercase)
                        for _ in range(self._string_length))
      if ctx:
        operation.counters.Increment(
            COUNTER_IO_READ_MSEC, int((time.time() - start_time) * 1000))(ctx)
        operation.counters.Increment(COUNTER_IO_READ_BYTES, len(content))(ctx)
      yield content 
Example #13
Source File: test_function.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_series_groupby_nunique(n, m, sort, dropna):

    def check_nunique(df, keys, as_index=True):
        gr = df.groupby(keys, as_index=as_index, sort=sort)
        left = gr['julie'].nunique(dropna=dropna)

        gr = df.groupby(keys, as_index=as_index, sort=sort)
        right = gr['julie'].apply(Series.nunique, dropna=dropna)
        if not as_index:
            right = right.reset_index(drop=True)

        tm.assert_series_equal(left, right, check_names=False)

    days = date_range('2015-08-23', periods=10)

    frame = DataFrame({'jim': np.random.choice(list(ascii_lowercase), n),
                       'joe': np.random.choice(days, n),
                       'julie': np.random.randint(0, m, n)})

    check_nunique(frame, ['jim'])
    check_nunique(frame, ['jim', 'joe'])

    frame.loc[1::17, 'jim'] = None
    frame.loc[3::37, 'joe'] = None
    frame.loc[7::19, 'julie'] = None
    frame.loc[8::19, 'julie'] = None
    frame.loc[9::19, 'julie'] = None

    check_nunique(frame, ['jim'])
    check_nunique(frame, ['jim', 'joe'])
    check_nunique(frame, ['jim'], as_index=False)
    check_nunique(frame, ['jim', 'joe'], as_index=False) 
Example #14
Source File: auth_test.py    From cassandra-dtest with Apache License 2.0 5 votes vote down vote up
def username(self):
        return ''.join(random.choice(string.ascii_lowercase) for _ in range(8)); 
Example #15
Source File: test_whitelist.py    From recruit with Apache License 2.0 5 votes vote down vote up
def df_letters():
    letters = np.array(list(ascii_lowercase))
    N = 10
    random_letters = letters.take(np.random.randint(0, 26, N))
    df = DataFrame({'floats': N / 10 * Series(np.random.random(N)),
                    'letters': Series(random_letters)})
    return df 
Example #16
Source File: config.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def _new_token() -> str:
        return "".join(random.choices(string.ascii_lowercase + string.digits, k=64)) 
Example #17
Source File: crackfortran.py    From recruit with Apache License 2.0 5 votes vote down vote up
def expr2name(a, block, args=[]):
    orig_a = a
    a_is_expr = not analyzeargs_re_1.match(a)
    if a_is_expr:  # `a` is an expression
        implicitrules, attrrules = buildimplicitrules(block)
        at = determineexprtype(a, block['vars'], implicitrules)
        na = 'e_'
        for c in a:
            c = c.lower()
            if c not in string.ascii_lowercase + string.digits:
                c = '_'
            na = na + c
        if na[-1] == '_':
            na = na + 'e'
        else:
            na = na + '_e'
        a = na
        while a in block['vars'] or a in block['args']:
            a = a + 'r'
    if a in args:
        k = 1
        while a + str(k) in args:
            k = k + 1
        a = a + str(k)
    if a_is_expr:
        block['vars'][a] = at
    else:
        if a not in block['vars']:
            if orig_a in block['vars']:
                block['vars'][a] = block['vars'][orig_a]
            else:
                block['vars'][a] = {}
        if 'externals' in block and orig_a in block['externals'] + block['interfaced']:
            block['vars'][a] = setattrspec(block['vars'][a], 'external')
    return a 
Example #18
Source File: util.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def __init__(self):
    self.prefix = 's:'
    self.code = string.ascii_uppercase + string.ascii_lowercase + string.digits
    self.min = 0
    self.max = len(self.code) - 1 
Example #19
Source File: __init__.py    From scikit-downscale with Apache License 2.0 5 votes vote down vote up
def random_grid_data(grid_shape=(2, 3), n_times=100, n_vars=1):
    ds = xr.Dataset()
    size = (n_times,) + grid_shape
    dims = ("time", "y", "x")
    times = pd.date_range("1979-01-01", freq="1D", periods=n_times)
    for vname in string.ascii_lowercase[:n_vars]:
        ds[vname] = xr.DataArray(np.random.random(size=size), dims=(dims), coords={"time": times})
    return ds 
Example #20
Source File: username_generator.py    From pythonpentest with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def census_parser(filename, verbose):
    # Create the named tuple
    CensusTuple = namedtuple('Census', 'name, rank, count, prop100k, cum_prop100k, pctwhite, pctblack, pctapi, pctaian, pct2prace, pcthispanic')

    # Define the location of the file and worksheet till arguments are developed
    worksheet_name = "top1000"

    #Define work book and work sheet variables
    workbook = xlrd.open_workbook(filename)
    spreadsheet = workbook.sheet_by_name(worksheet_name)
    total_rows = spreadsheet.nrows - 1
    current_row = -1

    # Define holder for details
    username_dict = {}
    surname_dict = {}
    alphabet = list(string.ascii_lowercase)

    while current_row < total_rows:
        row = spreadsheet.row(current_row)
        current_row += 1
        entry = CensusTuple(*tuple(row)) #Passing the values of the row as a tuple into the namedtuple
        surname_dict[entry.rank] = entry
        cellname = entry.name
        cellrank = entry.rank
        for letter in alphabet:
            if "." not in str(cellrank.value):
                if verbose > 1:
                    print("[-] Eliminating table headers")
                break
            username = letter + str(cellname.value.lower())
            rank = str(cellrank.value)
            username_dict[username] = rank
    username_list = sorted(username_dict, key=lambda key: username_dict[key])

    return(surname_dict, username_dict, username_list) 
Example #21
Source File: __init__.py    From scikit-downscale with Apache License 2.0 5 votes vote down vote up
def random_point_data(n_points=1, n_times=100, n_vars=1):
    ds = xr.Dataset()
    size = (n_times, n_points)
    dims = ("time", "point")
    times = pd.date_range("1979-01-01", freq="1D", periods=n_times)
    for vname in string.ascii_lowercase[:n_vars]:
        ds[vname] = xr.DataArray(np.random.random(size=size), dims=(dims), coords={"time": times})
    return ds 
Example #22
Source File: util.py    From instavpn with Apache License 2.0 5 votes vote down vote up
def webui():
    logger.debug('Generate random password')
    char_set = string.ascii_lowercase + string.ascii_uppercase + string.digits
    with open('web/server/credentials.json', 'w') as f:
        json.dump({
            "admin": {
                "login": "admin",
                "password": gen_random_text(16)
            }
        }, f)

    logger.debug('Copy web UI directory')
    # it fix web UI critical error
    if not run_command("mkdir --mode=755 -p /opt"):
        return False
    #end
    if not run_command("cp -rf web/ /opt/instavpn"):
        return False

    logger.debug('Install node_modules')
    if not run_command("cd /opt/instavpn && npm install"):
        return False

    logger.debug('Copy upstart script')
    if not run_command("cp files/instavpn.conf /etc/init"):
        return False

    logger.debug('Add vnstati to cron')
    if not run_command(CRONTAB):
        return False

    logger.debug('Start service')
    if not run_command("start instavpn"):
        return False

    return True 
Example #23
Source File: sklearn.py    From decompose with MIT License 5 votes vote down vote up
def __calc_variance_ratio(self, data, U):
        varData = np.var(data)
        evr = np.zeros(self.n_components)
        F = len(U)
        axisIds = string.ascii_lowercase[:F]
        subscripts = f'k{",k".join(axisIds)}->{axisIds}'
        for k in range(self.n_components):
            Uks = []
            for Uf in U:
                Uks.append(Uf[k][None, ...])
            recons = np.einsum(subscripts, *Uks)
            evr[k] = np.var(recons)/varData
        return(evr) 
Example #24
Source File: normalNdLikelihood.py    From decompose with MIT License 5 votes vote down vote up
def outterTensorProduct(self, Us):
        F = len(Us)
        axisIds = string.ascii_lowercase[:F]
        subscripts = f'k{",k".join(axisIds)}->{axisIds}k'
        Xhat = tf.einsum(subscripts, *Us)
        return(Xhat) 
Example #25
Source File: normalNdLikelihood.py    From decompose with MIT License 5 votes vote down vote up
def residuals(self, U: Tuple[Tensor, ...], X: Tensor) -> Tensor:
        F = len(U)
        axisIds = string.ascii_lowercase[:F]
        subscripts = f'k{",k".join(axisIds)}->{axisIds}'
        Xhat = tf.einsum(subscripts, *U)
        residuals = X-Xhat
        return(residuals) 
Example #26
Source File: cvNormalNdLikelihood.py    From decompose with MIT License 5 votes vote down vote up
def outterTensorProduct(self, Us):
        F = len(Us)
        axisIds = string.ascii_lowercase[:F]
        subscripts = f'k{",k".join(axisIds)}->{axisIds}k'
        Xhat = tf.einsum(subscripts, *Us)
        return(Xhat) 
Example #27
Source File: cvNormalNdLikelihood.py    From decompose with MIT License 5 votes vote down vote up
def trainResiduals(self, U: Tuple[Tensor, ...], X: Tensor) -> Tensor:
        F = len(U)
        axisIds = string.ascii_lowercase[:F]
        subscripts = f'k{",k".join(axisIds)}->{axisIds}'
        Xhat = tf.einsum(subscripts, *U)
        residuals = tf.reshape(X-Xhat, (-1,))
        indices = tf.cast(tf.where(tf.reshape(self.trainMask, (-1,))),
                          dtype=tf.int32)
        trainResiduals = tf.gather_nd(residuals, indices)
        return(trainResiduals) 
Example #28
Source File: cvNormalNdLikelihood.py    From decompose with MIT License 5 votes vote down vote up
def testResiduals(self, U: Tuple[Tensor, ...], X: Tensor) -> Tensor:
        F = len(U)
        axisIds = string.ascii_lowercase[:F]
        subscripts = f'k{",k".join(axisIds)}->{axisIds}'
        Xhat = tf.einsum(subscripts, *U)
        residuals = tf.reshape(X-Xhat, (-1,))
        indices = tf.cast(tf.where(tf.reshape(self.testMask, (-1,))),
                          dtype=tf.int32)
        testResiduals = tf.gather_nd(residuals, indices)
        return(testResiduals) 
Example #29
Source File: lowRank.py    From decompose with MIT License 5 votes vote down vote up
def tensorReconstruction(self, U: Tuple[ndarray, ndarray]) -> ndarray:
        """Reconstructs the data using the estimates provided"""
        F = len(U)
        axisIds = string.ascii_lowercase[:F]
        subscripts = f'k{",k".join(axisIds)}->{axisIds}'
        r = np.einsum(subscripts, *U)
        return(r) 
Example #30
Source File: cv.py    From decompose with MIT License 5 votes vote down vote up
def mask(self, X: Tensor):
        U = self.lowrankMask(X)
        F = len(U)
        axis = string.ascii_lowercase[:F]
        subscripts = ','.join(axis) + "->" + axis
        mask = tf.cast(tf.einsum(subscripts, *U), dtype=tf.bool)
        return(mask)