code stringlengths 17 6.64M |
|---|
def invalidUsername(username):
pass
|
def raisePrivileges():
pass
|
def lowerPrivileges():
pass
|
def makeNewUserDir(username):
"\n Check whether the username is invalid by invoking the invalidUsername() function.\n If username is valid, temporarily raises the program's privileges by invoking raisePrivileges().\n Create a new user folder within /home/{username}, then invoke lowerPrivileges().\n Return True if the user folder was successfully created, False otherwise.\n "
|
def killProcess(processID):
'\n Kill the process with the given processID.\n '
|
def authenticate(username, password, service='login'):
def my_conv(n_messages, messages, p_response, app_data):
'\n Simple conversation function that responds to any prompt where the echo is off with the supplied password\n '
pass
'\n Create a handle from PamHandle,\n configure the PAM conversation to use my_conv as a callback function to allow PAM to send messages to and get input from a user. \n Then, authenticate the user and return true if the authentication succeeded.\n '
|
def getSSLContext():
'\n Create an SSL context and return it.\n '
|
def getContext():
'\n Create an OpenSSL context and return it.\n '
|
def ensure_logged_in(f):
@wraps(f)
def decorated_function(*args, **kws):
if (session['username'] is None):
return redirect('/login')
return f(*args, **kws)
return decorated_function
|
@app.route('/login', methods=['GET'])
def login():
return '\n <html><form action="/login" method="post">\n <p><input type="text" name="username"></p>\n <p><input type="password" name="password"></p>\n <p><button type="submit">Submit</button></p>\n </form></html>\n '
|
@app.route('/login', methods=['POST'])
def do_login():
if ((request.form['username'] == 'admin') and (request.form['password'] == 'password')):
session['username'] = request.form['username']
return redirect('/secret')
else:
return 'Bad username or password'
|
@app.route('/')
def index():
return "<html>\n Hello! <a href='./login'>Login here</a>\n </html>"
|
def settings():
'\n If the user is authenticated, redirect the request to the confidential settings page. Otherwise, redirect the user to the login page.\n '
|
@app.route('/login', methods=['GET'])
def login():
return render_template('login.html')
|
def check_credentials(username, password):
return True
|
@app.route('/login', methods=['POST'])
def do_login():
'\n Get the username and password from the request.\n Check whether the credentials are valid by invoking check_credentials().\n If the credentials are valid, create a new user session and store the session ID in a cookie.\n '
|
def downloadFile(hostname, username, password, sensitive_file):
'\n Connect to an FTP server using the hostname provided.\n Log-in using the username and password provided as parameters.\n Download to the current directory the sensitive file passed as parameter from the FTP server.\n '
|
def get_assignments(course_id):
'\n Return a list of all the assignments in a Canvas course,\n with an id equals to the id specified as parameter.\n '
|
def get_embeddings(text):
"\n Calculate the embeddings for the text provided as parameter using the OpenAI's 'text-embedding-ada-002' model.\n Then, return a list of the embeddings.\n "
|
def create_private_key():
'\n Generate a private key using RSA,\n export the key using the OpenSSH format,\n then return it.\n '
|
def generate_private_key():
'\n Generate a private key using DSA,\n export the key using the OpenSSH format,\n then return it.\n '
|
def send_encrypted(secret_key, channel, message):
'\n Encrypt the message after creating a cipher,\n and send it over the channel passed as parameter.\n '
|
def connect(host, port):
'\n Create a client SSL socket that uses IPV4 and the TCP protocol, and\n connect to the socket on the host and port provided as parameter.\n Then, return the socket.\n '
|
def certificate_matches(certificate, known_hash):
'\n Return true if the certificate matches the known_hash.\n '
|
def get_password_hash(password: str, salt: str):
'\n Return a hash of the password and salt.\n '
|
def getEncryptionKey(key):
'\n Create a Cipher using AES and CBC mode.\n Then, encrypt the key using this cipher and return it.\n '
|
def getSessionID():
'\n Return a random and unique session ID.\n '
|
def generateRandomString(length):
'\n Return an unpredictable random string that has only ASCII letters with a fixed size equals to length.\n '
|
def generateCryptoKey():
'\n Generate a random 128 bits by using the seeds from os.urandom().\n '
|
def verifyJsonWebToken(token):
'\n Decode the JSON web token passed and return it.\n '
|
def verifyJWTToken(key, token):
'\n Decode the JWT token with the given key and return it.\n '
|
def verifyJWTToken(jwt_token):
'\n Verify the JWT Token and return it.\n '
|
def readFile(fileName):
'\n Check if the file passed as argument exists,\n then read the file and return its content.\n '
|
def write_results(results):
'\n Create a temporary file and write the results to it\n '
|
def write_results(results):
'\n Create a temporary file with UTF-8 encoding,\n write the unicode string results to it,\n and return its path.\n '
|
def validate_password(actual_pw, typed_pw):
'\n Compare the actual password with the typed password by checking whether every character matches.\n '
|
@app.route('/upload')
def upload():
'\n Get the username and a file attachment from the HTTP GET request.\n Then, search the username in the filename of the attachment.\n '
|
def parseUDPpacket(data):
pass
|
def resolveName(nameToResolve):
pass
|
def sendResponse(requestIP, record):
pass
|
def UDPMessaging(udp_ip, udp_port):
'\n Create a UDP socket that listens on the IP and port provided for DNS requests.\n Parse the received data, and send back the DNS record to the requested IP in the packet.\n '
|
def getData(dataStart, dataLimit, thread):
'\n Check if the dataStart is less than or equal to dataLimit.\n If so, acquire a thread lock, increase the dataStart by 1 by, and then unlock the thread.\n Print which thread is currently accessing the data\n '
|
def getResource(request):
'\n Get username and date from the request, then\n send the file to the user by creating path by the username and date.\n '
|
@app.route('/pdf/upload')
def upload_pdf():
'\n Get PDF file from request, save it to ./uploads directory, and redirect to /pdf/view\n '
|
@app.route('/img/upload')
def upload_img():
'\n Get image file from request and save it to ./pictures folder after encoding\n '
|
def admin_access(request):
'\n Read the username and password from the request\n validate the username and password for admin access.\n Flag that the user has admin access.\n '
|
def foo():
return ('./', 'file.txt')
|
def dataSorting():
'\n Continuously take (basename,data) key-value pair from foo() function and sort it\n '
|
def currentTime():
'\n Print the current processor time in seconds.\n '
|
class Payload(object):
def __reduce__(self):
return (exec, ('import os;os.system("ls")',))
|
def makePickleData(payload: Payload):
'\n Get serialized data from the payload object and serialize it before returning it\n '
|
def getPickleData(pickled):
'\n Return deserialized data\n '
|
def confirmAuth(headers):
'\n Get AuthToken from headers, decode it with base64, and load with cPickle to token object\n check if the token is valid and return the data in token object if it is valid.\n '
|
@app.route('/yaml')
def yaml_load():
'\n Get YAML data from request, parse it, and return it.\n '
|
def configure_app(app):
'\n Add database link to the SQLALCHEMY_DATABASE_URI config of app.\n '
|
def checkPassword(userid, password):
'\n Get the password of the userid from the database and compare with the provided one.\n '
|
@app.route('/register', methods=['POST'])
def register():
'\n Get username and password from the request, and check if the username is already in the database.\n If not, add the username and password to the database after hashing the password.\n '
|
def isEqual(account1, account2):
'\n Compare whether the two accounts are the same.\n '
|
@app.route('/')
def redirect():
'\n Redirect the user to the next_url specified on the GET request.\n '
|
def http_responser_redirect(request):
'\n Get the target url from the request and redirect to it\n '
|
@app.route('flask_redirect')
def flask_redirect():
'\n Get the url from the request and redirect to it\n '
|
@app.route('set_location_header')
def set_location_header():
'\n Get the "next" value from the request and set the location header for redirecting to the value of "next".\n '
|
def set_location_header(request):
'\n Get the "next" value from the request and redirect it to it using the \'Location\' header.\n '
|
def echoServer(port):
'\n Create a socket server that echos back the message sent.\n '
|
def checkPassword(userid, password):
pass
|
@app.post('/upload')
def upload():
'\n Get the xml file from the request and check if the userid and password are correct by invoking checkPassword().\n '
|
@app.post('/upload')
def upload():
'\n Get the xml_src from the request, parse it and return it as string.\n '
|
def get_root():
"\n Create an XML parser, parse the 'resources/config.xml' file and return the root.\n "
|
def get_root():
"\n Create an XML parser, parse the 'resources/config.xsd' file, and return an XMLSchema.\n "
|
def transform_xml():
"\n Create a XML parser, parse the 'resources/config.xsl' file,\n and return an XSLT object.\n "
|
def get_root():
"\n Create an XML parser,\n parse the file 'resources/config.xml' and return the parsed result.\n "
|
@app.route('/download')
def download():
'\n Get the file name from the request and parse the name to get the file path\n Send the file to the client as an attachment.\n '
|
def xpath_query(request):
'\n Get the `xpath` value from the GET request,\n get the \'xml\' value from the GET request,\n construct and parse the xml payload,\n return the result of the XPath query "/tag[@id={}]" format from the parsed xml\n '
|
@app.route('/user')
def user_locations():
'\n Retrieve the username from the request,\n make an XPath query (/users/user/[@name=<username>]/location) to find the user in the XML root,\n return the list of locations of the user.\n '
|
def convert_to_int():
'\n Take an input from the user (console) and convert it to int within a try-except block.\n '
|
def convert_to_int():
'\n Continuously take an input from user and convert it to int within a try-except block\n '
|
def inputInt():
'\n Take an int input and return it after checking type\n '
|
def checkNumber(number):
'\n Use regular expression to match lines with numbers\n '
|
@app.route('/direct')
def direct():
"\n Get the regex from the 'pattern' in the GET request,\n get the 'text' from the GET request,\n and search the 'text' with the provided regex.\n "
|
@app.route('/direct')
def direct():
"\n Get the regular expression pattern from the GET request (pattern), compile it\n and then use it to search the string within the 'text' in the GET request.\n "
|
def createExecutableFile(data):
'\n Create a binary file test.bim and make it executable.\n '
|
def storePassword(userName, Password):
'\n Hash the password and update the database with username and hashed password by invoking the updateUserLogin() method\n '
|
def getHash(password):
'\n create a hash of the password with a salt.\n '
|
@app.post('/upload')
def upload():
'\n Reads the XML from the incoming request.\n Parse it and return.\n '
|
def getDBConnection():
'\n Return a MySQL database connection.\n '
|
def process_request(request):
'\n Retrieve the "password" from the GET request\n compare the password to the expected value,\n if it is the same, redirect to the login page.\n '
|
def getXmlRoot():
'\n Create an XML parser and parse the resources/c.xml file and return the root element\n '
|
def getFibonacci(n):
'\n Compute the n-th fibonacci number using loops only.\n '
|
def dispatchCommand(command, user, args):
"\n This function checks the command data and calls the appropriate function.\n When command is 'login', it calls loginUser()\n When command is 'retrieve_file', it calls sendFile()\n when command is 'list_files', it calls listFiles()\n it does appropriate authentication before calling the function\n "
|
@app.route('/full_ssrf')
def full_ssrf():
'\n Get the subdomain from the request and use it as the url, make a request to the url, and return the response\n '
|
@app.route('/user')
def retrieve_info():
"\n Get the user_id from the request,\n the retrieve the user info from GitHub using the GitHub's API,\n and return the response\n "
|
def sendData():
'\n This function creates a UDP socket and continuously receive 1024 bytes of UDP packet.\n After parsing each UDP packet (by invoking parseUDPpacket(data)),\n it sends the data to appropriate requested IP address by invoking sendResponse.\n '
|
def getUser(username, password):
'\n Get the user information from the users table by using its username and password.\n '
|
def get_relative_freqs(type2freq):
'\n Calculates the relative frequency (proportion) of each type in a system\n\n Parameters\n ----------\n type2freq: dict\n Keys are types of a system and values are frequencies of those types\n\n Returns\n -------\n type2p: dict\n Keys are types and values are relative (normalized) frequencies\n '
n = sum(type2freq.values())
type2p = {t: (s / n) for (t, s) in type2freq.items()}
return type2p
|
def get_entropy_scores(type2p_1, type2p_2, base=2, alpha=1):
'\n Calculates the generalized Tsallis entropy scores for the difference in\n entropies of two systems\n\n Parameters\n ----------\n type2p_1, type2p_2: dict\n Keys are types of a system and values are relative frequencies of those types\n base: int, optional\n Base of the logarithm for calculating entropy\n alpha: float, optional\n The parameter for the generalized Tsallis entropy. Setting `alpha=1`\n recovers the Shannon entropy\n\n Returns\n -------\n type2score_1,type2score_2: dict\n Keys are types and values are the weights of each type for its contribution\n to the difference in entropies\n '
type2score_1 = dict()
type2score_2 = dict()
types = set(type2p_1.keys()).union(set(type2p_2.keys()))
for t in types:
if ((t in type2p_1) and (t in type2p_2)):
(s1, s2) = get_entropy_type_scores(type2p_1[t], type2p_2[t], base, alpha)
elif (t in type2p_1):
(s1, s2) = get_entropy_type_scores(type2p_1[t], 0, base, alpha)
else:
(s1, s2) = get_entropy_type_scores(0, type2p_2[t], base, alpha)
type2score_1[t] = s1
type2score_2[t] = s2
return (type2score_1, type2score_2)
|
def get_entropy_type_scores(p_1, p_2, base, alpha):
"\n Calculates the scores for a particular type in a system when calculating the\n difference in Tsallis entropy between two systems\n\n Parameters\n ----------\n p_1, p_2: float\n The probability of the type appearing in system 1 or system 2\n base: int\n The base for the logarithm when computing entropy\n alpha: float\n The parameter for the generalized Tsallis entropy. Setting `alpha=1`\n recovers the Shannon entropy.\n\n Returns\n -------\n score_1, score_2: float\n The weights of the type's contribution\n "
score_1 = 0
score_2 = 0
if (alpha == 1):
if (p_1 > 0):
score_1 = (- log(p_1, base))
if (p_2 > 0):
score_2 = (- log(p_2, base))
elif (alpha > 0):
if (p_1 > 0):
score_1 = (((- 1) * (p_1 ** (alpha - 1))) / (alpha - 1))
if (p_2 > 0):
score_2 = (((- 1) * (p_2 ** (alpha - 1))) / (alpha - 1))
return (score_1, score_2)
|
def get_jsd_scores(type2p_1, type2p_2, weight_1=0.5, weight_2=0.5, base=2, alpha=1):
'\n Calculates the contribution of the types in two systems to the Jensen-Shannon\n divergence (JSD) between those systems\n\n Parameters\n ----------\n type2p_1, type2p_2: dict\n Keys are types of a system and values are relative frequencies of those types\n weight_1, weight_2: float\n Relative weights of type2p_1 and type2p_2 when constructing their mixed\n distribution. Should sum to 1\n base: int\n The base for the logarithm when computing entropy\n alpha: float\n The parameter for the generalized Tsallis entropy. Setting `alpha=1`\n recovers the Shannon entropy.\n\n Returns\n -------\n Keys are types and values are the weights of each type for its contribution\n to the JSD\n '
type2m = dict()
type2score_1 = dict()
type2score_2 = dict()
types = set(type2p_1.keys()).union(set(type2p_2.keys()))
for t in types:
p_1 = (type2p_1[t] if (t in type2p_1) else 0)
p_2 = (type2p_2[t] if (t in type2p_2) else 0)
m = ((weight_1 * p_1) + (weight_2 * p_2))
(s1, s2) = get_jsd_type_scores(p_1, p_2, m, weight_1, weight_2, base, alpha)
type2m[t] = m
type2score_1[t] = s1
type2score_2[t] = s2
return (type2m, type2score_1, type2score_2)
|
def get_jsd_type_scores(p_1, p_2, m, weight_1, weight_2, base, alpha):
"\n Calculates the JSD weighted average scores for a particular type in a system\n\n Parameters\n ----------\n p_1, p_2, m: float\n the probability of the type appearing in system 1, system 2, and the\n their mixture M\n weight_1, weight_2: float\n relative weights of type2p_1 and type2p_2 when constructing their mixed\n distribution. Should sum to 1\n base: int\n the base for the logarithm when computing entropy\n alpha: float\n the parameter for the generalized Tsallis entropy. Setting `alpha=1`\n recovers the Shannon entropy.\n\n Returns\n -------\n score_1, score_2: float\n The weights of the type's contribution\n "
score_1 = 0
score_2 = 0
if (alpha == 1):
if (p_1 > 0):
score_1 = (weight_1 * (log(m, base) - log(p_1, base)))
else:
score_1 = (weight_1 * log(m, base))
if (p_2 > 0):
score_2 = (weight_2 * (log(p_2, base) - log(m, base)))
else:
score_2 = (weight_2 * (- log(m, base)))
elif (alpha > 0):
if (p_1 > 0):
score_1 = ((weight_1 * ((m ** (alpha - 1)) - (p_1 ** (alpha - 1)))) / (alpha - 1))
if (p_2 > 0):
score_2 = ((weight_2 * ((m ** (alpha - 1)) - (p_2 ** (alpha - 1)))) / (alpha - 1))
return (score_1, score_2)
|
def preprocess_words_scores(type2freq_1, type2score_1, type2freq_2, type2score_2, stop_lens, stop_words, handle_missing_scores):
"\n Filters stop words according to a list of words or stop lens on the scores\n\n Parameters\n ----------\n type2freq_1, type2freq_2: dict\n Keys are types, values are frequencies of those types\n type2score_1, type2freq_2: dict\n Keys are types, values are scores associated with those types\n stop_lens: iteratble of 2-tuples\n Denotes intervals that should be excluded from word shifts\n stop_words: iterable\n Denotes words that should be excluded from word shifts\n handle_missing_scores_scores\n If 'error', throws an error whenever a word has a score in one score\n dictionary but not the other. If 'exclude', excludes any word that is\n missing a score in one score dictionary from all word shift\n calculations, regardless if it may have a score in the other dictionary.\n If 'adopt' and the score is missing in one dictionary, then uses the\n score from the other dictionary if it is available\n "
ts_1 = set(type2freq_1.keys()).union(set(type2score_1.keys()))
ts_2 = set(type2freq_2.keys()).union(set(type2score_2.keys()))
ts = ts_1.union(ts_2)
type2freq_1_new = dict()
type2score_1_new = dict()
type2freq_2_new = dict()
type2score_2_new = dict()
adopted_score_types = set()
no_score_types = set()
filtered_types = set()
for t in ts:
if (t in stop_words):
filtered_types.add(t)
continue
if (t in type2score_1):
s_1 = type2score_1[t]
else:
s_1 = None
if (t in type2score_2):
s_2 = type2score_2[t]
else:
s_2 = None
if ((t not in type2score_1) and (t not in type2score_2)):
no_score_types.add(t)
continue
elif ((t not in type2score_1) and (t in type2score_2)):
if (handle_missing_scores == 'adopt'):
s_1 = type2score_2[t]
s_2 = type2score_2[t]
adopted_score_types.add(t)
elif (handle_missing_scores == 'error'):
raise KeyError('Word has freq but no score in type2score_1: {}'.format(t))
elif (handle_missing_scores == 'exclude'):
no_score_types.add(t)
continue
else:
raise ValueError('handle_missing_scores has not been provided a valid argument')
elif ((t in type2score_1) and (t not in type2score_2)):
if (handle_missing_scores == 'adopt'):
s_1 = type2score_1[t]
s_2 = type2score_1[t]
adopted_score_types.add(t)
elif (handle_missing_scores == 'error'):
raise KeyError('Word has freq but no score in type2score_2: {}'.format(t))
elif (handle_missing_scores == 'exclude'):
no_score_types.add(t)
continue
else:
raise ValueError('handle_missing_scores has not been provided a valid argument')
else:
s_1 = type2score_1[t]
s_2 = type2score_2[t]
filter_word = False
for (lower, upper) in stop_lens:
if (((lower <= s_1) and (s_1 <= upper)) and ((lower <= s_2) and (s_2 <= upper))):
filter_word = True
elif (((lower <= s_1) and (s_1 <= upper)) or ((lower <= s_2) and (s_2 <= upper))):
raise ValueError((('{}: stop_lens cannot be applied consistently.'.format(t) + ' One word score falls within the stop lens while the') + ' other does not.'))
if filter_word:
filtered_types.add(t)
continue
type2score_1_new[t] = s_1
if (t in type2freq_1):
type2freq_1_new[t] = type2freq_1[t]
else:
type2freq_1_new[t] = 0
type2score_2_new[t] = s_2
if (t in type2freq_2):
type2freq_2_new[t] = type2freq_2[t]
else:
type2freq_2_new[t] = 0
final_types = ts.difference(filtered_types).difference(no_score_types)
return (type2freq_1_new, type2freq_2_new, type2score_1_new, type2score_2_new, final_types, filtered_types, no_score_types, adopted_score_types)
|
def get_score_dictionary(scores):
'\n Loads a dictionary of type scores\n\n Parameters\n ----------\n scores: dict or str\n If dict, then returns the dict automatically. If str, then the name of a\n lexicon included in Shifterator\n\n Returns\n -------\n type2score: dict\n Keys are types and values are scores of those types\n '
if isinstance(scores, collections.Mapping):
return (scores.copy(), None)
try:
lexicon = scores.split('_')[0]
score_f = 'lexicons/{}/{}.tsv'.format(lexicon, scores)
all_scores = pkgutil.get_data(__name__, score_f).decode('utf-8')
if ('labMT' in lexicon):
lexicon_ref = 5
elif ('SocialSent' in lexicon):
lexicon_ref = 0
elif ('NRC' in lexicon):
lexicon_ref = 0.5
except FileNotFoundError:
raise FileNotFoundError('Lexicon does not exist in Shifterator: {}'.format(scores))
type_scores = all_scores.split('\n')
type2score = dict()
for t_s in type_scores:
if (len(t_s) == 0):
continue
(t, s) = t_s.split('\t')
type2score[t] = float(s)
return (type2score, lexicon_ref)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.