repo
stringlengths 5
121
| content
stringlengths 35
2.09M
|
|---|---|
00-01/temp
|
00-01/temp
base.py
```import os
import sys
from time import time
import cv2
import face_recognition as fr
import numpy as np
from PyQt5 import QtWidgets
from PyQt5.QtCore import QThread, pyqtSignal, Qt
from PyQt5.QtGui import QPixmap, QImage, QScreen
from PyQt5.QtWidgets import QDialog, QMessageBox, QApplication
from PyQt5.uic import loadUi
from db import access_db
class Main(QDialog):
def __init__(self):
super(Main, self).__init__()
loadUi('ui/login.ui', self)
self.loginButton.clicked.connect(self.login)
self.signupButton.clicked.connect(self.create)
self.PW.setEchoMode(QtWidgets.QLineEdit.Password)
def login(self):
id = self.ID.text()
pw = self.PW.text()
print(f'{id} has logged in')
widget.addWidget(Face_Recognition())
widget.setCurrentIndex(widget.currentIndex()+1)
def create(self):
widget.addWidget(Signup())
widget.setCurrentIndex(widget.currentIndex()+1)
class Signup(QDialog):
def __init__(self):
super(Signup, self).__init__()
loadUi('ui/signup.ui', self)
self.signupButton.clicked.connect(self.createId)
self.PW.setEchoMode(QtWidgets.QLineEdit.Password)
self.PW_2.setEchoMode(QtWidgets.QLineEdit.Password)
def createId(self):
id = self.ID.text()
if self.PW.text() == self.PW_2.text():
pw = self.PW.text()
print(f'create ID: {id} success!')
widget.addWidget(Main())
widget.setCurrentIndex(widget.currentIndex()+1)
cam_num = '/dev/video0'
cap = cv2.VideoCapture(cam_num, cv2.CAP_V4L2)
distance = 0.35
path = 'new/'
ext = '.jpg'
class Face_Recognition(QDialog):
def __init__(self):
super(Face_Recognition, self).__init__()
loadUi("ui/face_rec.ui", self)
self.add.clicked.connect(self.add_new_id)
self.run = Run_Camera()
self.run.start()
self.run.ImageUpdate.connect(self.ImageUpdateSlot)
def ImageUpdateSlot(self, Image):
self.imgLabel.setPixmap(QPixmap.fromImage(Image))
self.imgLabel.setScaledContents(True)
def add_new_id(self):
self.run.stop()
widget.addWidget(Save())
widget.setCurrentIndex(widget.currentIndex()+1)
class Run_Camera(QThread):
ImageUpdate = pyqtSignal(QImage)
def run(self):
_, _, col, error_col = access_db()
n = list(col.find({}))
names = [i['name'] for i in n]
id = [j['id'] for j in n]
self.ThreadActive = True
while self.ThreadActive:
s = time()
ret, frame = cap.read()
if ret == False:
break
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = cv2.flip(frame, 1)
face_locations = fr.face_locations(frame)
face_encodings = fr.face_encodings(frame, face_locations)
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
name = "- - -"
face_distances = fr.face_distance(id, face_encoding) # calculate the distances from input to matches
best_match_index = np.argmin(face_distances) # select the lowest distance index
if face_distances[best_match_index] < distance:
name = names[best_match_index]
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.putText(frame, name, (left - 1, bottom + 24), cv2.FONT_HERSHEY_DUPLEX, 1.0, (255, 0, 0), 1)
print('name : ', name)
# calculate fps
seconds = time() - s
fps = 1 / seconds
fps = ("%.2f" % fps)
print(f"fps : {fps}", '\n')
img = QImage(frame.data, frame.shape[1], frame.shape[0], QImage.Format_RGB888)
self.ImageUpdate.emit(img)
def stop(self):
self.ThreadActive = False
self.quit()
class Save(QDialog):
def __init__(self):
super(Save, self).__init__()
loadUi('ui/save.ui', self)
self.save.clicked.connect(self.capture)
self.retrn.clicked.connect(self.face_rec)
self.take_photo = Take_photo()
self.take_photo.start()
self.take_photo.ImageUpdate.connect(self.ImageUpdateSlot)
def capture(self):
# fix image size
screenshot = QScreen.grabWindow(app.primaryScreen(), widget.winId(), 0, 0, 800, 600)
msg = QMessageBox()
msg.setWindowFlag(Qt.WindowStaysOnTopHint)
msg.setIconPixmap(QPixmap(screenshot))
msg.setText('저장 하시겠습니까?')
msg.setStandardButtons(QMessageBox.No|QMessageBox.Yes)
x = msg.exec_()
if x == QMessageBox.Yes:
name = self.name.text()
captured_img = path + name + ext
screenshot.save(captured_img)
_, _, col, error_col = access_db()
with open(captured_img, "rb") as data:
photo = data.read()
try:
id = fr.face_encodings(fr.load_image_file(captured_img), model='large')[0]
data = {'name': name, 'id': id.tolist(), 'photo': photo}
col.insert_one(data)
print('저장 완료!! : ', name)
except IndexError:
error_col.insert_one({'name': name})
os.remove(captured_img)
print('warning! face not detected! : ', name)
# client.close()
else: pass
def face_rec(self):
widget.addWidget(Face_Recognition())
widget.setCurrentIndex(widget.currentIndex()+1)
def ImageUpdateSlot(self, Image):
self.imgLabel.setPixmap(QPixmap.fromImage(Image))
self.imgLabel.setScaledContents(True)
class Take_photo(QThread):
ImageUpdate = pyqtSignal(QImage)
def run(self):
self.ThreadActive = True
# # cap = cv2.VideoCapture(cam_num)
while self.ThreadActive:
ret, frame = cap.read()
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = cv2.flip(frame, 1)
img = QImage(frame.data, frame.shape[1], frame.shape[0], QImage.Format_RGB888)
self.ImageUpdate.emit(img)
def stop(self):
cap.release()
cv2.destroyAllWindows()
self.ThreadActive = False
self.quit()
app = QApplication(sys.argv)
main = Main()
widget = QtWidgets.QStackedWidget()
widget.addWidget(main)
# widget.setFixedHeight(1280)
# widget.setFixedWidth(800)
# widget.move(QApplication.desktop().screen().rect().center()- rect().center())
widget.setWindowFlag(Qt.WindowStaysOnTopHint)
widget.show()
sys.exit(app.exec_())
```
essential.py
```from time import time
import concurrent.futures as cf
import cv2
import face_recognition as fr
import numpy as np
from db import access_db
# import concurrent.futures as cf
_, _, col, error_col = access_db()
n = list(col.find({}))
names = [i['name'] for i in n]
id = [j['id'] for j in n]
cap = cv2.VideoCapture(0)
distance = 0.35
def run():
while True:
s = time()
ret, frame = cap.read()
# frame1 = frame[:, :, ::-1]
# frame1 = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = cv2.flip(frame, 1)
face_locations = fr.face_locations(frame)
face_encodings = fr.face_encodings(frame, face_locations)
for (y, x1, y1, x), face_encoding in zip(face_locations, face_encodings):
name = "- - -"
face_distances = fr.face_distance(id, face_encoding) # calculate the distances from input to matches
best_match_index = np.argmin(face_distances) # select the lowest distance index
if face_distances[best_match_index] < distance:
name = names[best_match_index]
cv2.rectangle(frame, (x, y), (x1, y1), (0, 0, 255), 2)
cv2.putText(frame, name, (x - 1, y1 + 24), cv2.FONT_HERSHEY_DUPLEX, 1.0, (255, 0, 0), 1)
print('name : ', name)
# calculate fps
seconds = time() - s
fps = 1 / seconds
fps = ("%.2f" % fps)
print(f"fps : {fps}", '\n')
cv2.imshow('frame', frame)
if cv2.waitKey(1) == 27:
break
run()```
|
0072016/-.-.-.-.-.----.---..
|
0072016/-.-.-.-.-.----.---..
CHANGELOG.md
```# Changelog
## 0.1.0
- fix checkFormat task to use the passed folders instead of `.`
- initial release
- add default Grinder tasks
```
README.md
```# BWU Utils Dev
[](https://github.com/bwu-dart/bwu_utils_dev)
[](https://pub.dartlang.org/packages/bwu_utils_dev)
[](https://travis-ci.org/bwu-dart/bwu_utils_dev)
[](https://coveralls.io/r/bwu-dart/bwu_utils_dev)
Just a collection of utilities I want to reuse in my other packages.
```
|
007arunwilson/react-native-firebase
|
007arunwilson/react-native-firebase
README.md
```## React Native Application with Firebase
- Firebase notification Implemented ( google-services.json file is git ignored )
```
|
00mjk/snafu
|
00mjk/snafu
test.c
```const char *handler(const char *input)
{
return "Hello World";
}
```
docker.py
```# Snafu: Snake Functions - Docker Executor
import requests
import os
import configparser
import time
import random
container = "jszhaw/snafu"
endpoints = {}
multi = 3
authorised = True
def launch(tenant, portnum):
authmount = ""
if authorised:
accdb = os.path.expanduser("~/.snafu-accounts")
accdir = os.path.expanduser("~/.snafu-accounts-tenants/{}".format(tenant))
if os.getenv("HOME") == "/":
accdb = "/root/.snafu-accounts"
accdir = "/root/.snafu-accounts-tenants/{}".format(tenant)
c = configparser.ConfigParser()
try:
c.read(accdb)
except:
pass
else:
sections = c.sections()
secretkey = None
for section in sections:
ckeyid = c.get(section, "access_key_id")
if ckeyid == tenant:
secretkey = c.get(section, "secret_access_key")
break
if secretkey:
authmount = "-v {}:/root/.aws".format(accdir)
os.makedirs(accdir, exist_ok=True)
c = configparser.ConfigParser()
acc = "default"
c.add_section(acc)
c.set(acc, "aws_access_key_id", tenant)
c.set(acc, "aws_secret_access_key", secretkey)
f = open("{}/credentials".format(accdir), "w")
c.write(f)
f.close()
c = configparser.ConfigParser()
acc = "default"
c.add_section(acc)
c.set(acc, "region", "invalid")
f = open("{}/config".format(accdir), "w")
c.write(f)
f.close()
dockercmd = "docker run -d -p 127.0.0.1:{}:10000 -v /opt/functions-tenants/{}:/opt/functions-local {} {}".format(portnum, tenant, authmount, container)
os.system(dockercmd)
def executecontrol(flaskrequest, tenant):
if not tenant in endpoints:
if multi:
endpoints[tenant] = []
for i in range(multi):
entries = sum([len(x) if type(x) == list else 1 for x in endpoints.values()])
portnum = 10000 + entries + 1
endpoints[tenant].append("http://localhost:{}".format(portnum))
launch(tenant, portnum)
else:
entries = len(endpoints)
portnum = 10000 + entries + 1
endpoints[tenant] = "http://localhost:{}".format(portnum)
launch(tenant, portnum)
time.sleep(2)
endpoint = endpoints[tenant]
if multi:
endpoint = random.choice(endpoint)
#print("CHOICE", endpoint)
headers = {}
headers["X-Amz-Date"] = flaskrequest.headers.get("X-Amz-Date")
data = flaskrequest.data.decode("utf-8")
#method=r.method -> requests.post
reply = requests.post(endpoint + flaskrequest.path, data=data, headers=headers)
if reply.status_code == 200:
return reply.content.decode("utf-8")
else:
return
```
fib.c
```#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int fib(int n)
{
if(n < 2)
return 1;
else
return fib(n - 1) + fib(n - 2);
}
const char *handler(const char *input)
{
int n = atoi(input);
n = fib(n);
char result[100];
snprintf(result, sizeof(result) - 1, "%d", n);
return strdup(result);
}
```
publisher.py
```# Syntax: python3 publisher.py amqp://guest:guest@localhost:6379/
from kombu import Connection
import datetime
import sys
with Connection(sys.argv[1]) as conn:
try:
simple_queue = conn.SimpleQueue('sslq')
except:
print('Error: connection to broker or queue failed.')
exit()
message = 'helloword, sent at %s' % datetime.datetime.today()
simple_queue.put(message)
print('Sent: %s' % message)
simple_queue.close()
```
cexec.c
```#include <stdio.h>
#include <dlfcn.h>
int main(int argc, char *argv[])
{
void *handler;
const char *(*handlerfunc)(const char*);
const char *ret;
if(argc != 3)
{
fprintf(stderr, "Syntax: cexec <handler.so> <inputarg>\n");
return -1;
}
handler = dlopen(argv[1], RTLD_NOW);
*(void**)(&handlerfunc) = dlsym(handler, "handler");
ret = (*handlerfunc)(argv[2]);
printf("ret:%s\n", ret);
dlclose(handler);
return 0;
}
```
python3.py
```# Snafu: Snake Functions - Python3 Executor
import json
import subprocess
import pickle
import base64
def strbool(x):
return True if x == "True" else False
def execute(func, funcargs, envvars, sourceinfos):
for i, funcarg in enumerate(funcargs):
if "__class__" in dir(funcarg) and funcarg.__class__.__name__ == "SnafuContext":
funcargs[i] = "pickle:" + base64.b64encode(pickle.dumps(funcarg)).decode("utf-8")
funcargs = json.dumps(funcargs)
envvars = json.dumps(envvars)
p = subprocess.run("python3 snafulib/executors/python3-exec.py {} {} '{}' '{}'".format(sourceinfos.source, func.__name__, funcargs, envvars), stdout=subprocess.PIPE, shell=True)
try:
dtime, success, *res = p.stdout.decode("utf-8").strip().split(" ")
except:
dtime = 0.0
success = False
res = []
dtime = float(dtime)
success = strbool(success)
res = " ".join(res)
#print("PY2", res)
return dtime, success, res
```
Hello.java
```/*package example;*/
/*import com.amazonaws.services.lambda.runtime.Context;*/
public class Hello {
public String myHandler(int myCount, /*Context*/ Object context) {
return String.valueOf(myCount);
}
public final static void main(String[] args)
{
System.out.println(new Hello().myHandler(10, null));
}
}
```
python2-exec.py
```# Snafu: Snake Functions - Python2 Executor (Exec Module)
import sys
import os
import time
import json
import base64
import pickle
class Context:
def __init__(self):
self.SnafuContext = self
def __new__(self, x):
return x
def execute(filename, func, funcargs, envvars):
if funcargs.startswith("tempfile:"):
funcargs = open(funcargs[9:]).read()
funcargs = json.loads(funcargs)
envvars = json.loads(envvars)
for i, funcarg in enumerate(funcargs):
if type(funcarg) == str and funcarg.startswith("pickle:"):
sys.modules["lib"] = Context()
sys.modules["lib.snafu"] = Context()
funcarg = pickle.loads(base64.b64decode(funcarg.split(":")[1]))
sys.path.append(".")
os.chdir(os.path.dirname(filename))
mod = __import__(os.path.basename(filename[:-3]))
func = getattr(mod, func)
for envvar in envvars:
os.environ[envvar] = envvars[envvar]
stime = time.time()
try:
res = func(*funcargs)
success = True
except Exception as e:
res = e
success = False
dtime = (time.time() - stime) * 1000
#return dtime, success, res
return "{} {} {}".format(dtime, success, "{}".format(res).replace("'", "\""))
print(execute(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]))
```
patch-gcloud
```#!/bin/bash
gcloudfolder=`gcloud info | grep "Installation Root" | cut -d "[" -f 2 | cut -d "]" -f 1`
if [ ! -z "$gcloudfolder" ]
then
file=$gcloudfolder/lib/googlecloudsdk/third_party/apis/cloudfunctions/v1beta2/cloudfunctions_v1beta2_client.py
echo "Patching $file..."
sed -i -e "s,^ BASE_URL = u'https://cloudfunctions.googleapis.com/', BASE_URL = u'http://localhost:10000/'," $file
fi
```
c.py
```# Snafu: Snake Functions - C Parser
import os
def activatefile(self, source, convention, SnafuFunctionSource):
if not os.path.isfile("snafulib/executors/c/cexec"):
pwd = os.getcwd()
os.chdir("snafulib/executors/c")
os.system("gcc -Wall -O2 -o cexec cexec.c -ldl")
os.chdir(pwd)
if source.endswith(".c"):
binfile = source.replace(".c", ".so")
if not os.path.isfile(binfile):
if not self.quiet:
print("» c source:", source)
pwd = os.getcwd()
os.chdir(os.path.dirname(source))
os.system("gcc -Wall -O2 -fPIC -shared -o {} {}".format(os.path.basename(binfile), os.path.basename(source)))
os.chdir(pwd)
source = binfile
else:
return
if not self.quiet:
print("» c module:", source)
funcname = os.path.basename(source).replace(".", "_") + ".handler"
funcparams = ["input"]
if not self.quiet:
print(" function: {} (unchecked)".format(funcname))
sourceinfos = SnafuFunctionSource(source, scan=False)
self.functions[funcname] = ([funcname] + funcparams, None, sourceinfos)
```
run-rabbit.sh
```#!/bin/bash
if [ ! -d rabbitmq_server-3.6.6 ]
then
if [ ! -f rabbitmq-server-generic-unix-3.6.6.tar.xz ]
then
wget -c http://www.rabbitmq.com/releases/rabbitmq-server/v3.6.6/rabbitmq-server-generic-unix-3.6.6.tar.xz
fi
tar xf rabbitmq-server-generic-unix-3.6.6.tar.xz
fi
cd rabbitmq_server-3.6.6
echo "** runing RabbitMQ **"
./sbin/rabbitmq-server
```
snafu-accounts
```#!/usr/bin/env python3
#
# Snafu: Snake Functions - Account Management Command-Line Tool
import snafulib.snafuaccounts
snafulib.snafuaccounts.SnafuAccountsRunner()
```
make-dist.sh
```#!/bin/bash
if [ -f ../setup.py ]
then
cd ..
fi
if [ ! -f setup.py ]
then
echo "Error: Needs to run from root directory." >&2
exit 1
fi
rm -rf dist
python3 setup.py sdist
python3 setup.py bdist_wheel
python3 setup.py bdist_egg
read -p "Upload? (y/n)" upload
if [ "$upload" = "y" ]
then
twine upload dist/*.*
fi
```
python2.py
```# Snafu: Snake Functions - Python2 Executor
import json
import subprocess
import pickle
import base64
import tempfile
def strbool(x):
return True if x == "True" else False
def execute(func, funcargs, envvars, sourceinfos):
for i, funcarg in enumerate(funcargs):
if "__class__" in dir(funcarg) and funcarg.__class__.__name__ == "SnafuContext":
funcargs[i] = "pickle:" + base64.b64encode(pickle.dumps(funcarg, protocol=2)).decode("utf-8")
funcargs = json.dumps(funcargs)
envvars = json.dumps(envvars)
if len(funcargs) > 256:
tf = tempfile.NamedTemporaryFile()
tf.write(bytes(funcargs, "utf-8"))
funcargs = "tempfile:" + tf.name
p = subprocess.run("python2 snafulib/executors/python2-exec.py {} {} '{}' '{}'".format(sourceinfos.source, func.__name__, funcargs, envvars), stdout=subprocess.PIPE, shell=True)
try:
dtime, success, *res = p.stdout.decode("utf-8").strip().split(" ")
except:
dtime = 0.0
success = False
res = []
dtime = float(dtime)
success = strbool(success)
res = " ".join(res)
#print("PY2", res)
return dtime, success, res
```
deploy-function.sh
```#!/bin/bash
ep=http://localhost:10000
if [ ! -z $1 ]
then
ep=$1
fi
if [ ! -f functions/localfib.py ]
then
echo "Error: Needs to run from root directory." >&2
exit 1
fi
cp functions/localfib.py testfib.py
echo "def lambda_handler(c, e):return fib(10)" >> testfib.py
zip testfib.zip testfib.py
rm testfib.py
aws --endpoint-url $ep lambda create-function --function-name testfib --runtime python3.5 --role notimportant --handler testfib.lambda_handler --zip-file fileb:///$PWD/testfib.zip
aws --endpoint-url $ep lambda list-functions
```
lambada.py
```# Snafu: Snake Functions - Lambada (Python) Parser
import os
import importlib
import types
import sys
import lambadalib.lambada
def activatefile(self, source, convention, SnafuFunctionSource):
sourceinfos = None
try:
sourceinfos = SnafuFunctionSource(source)
sourcecode = sourceinfos.content
except:
print("Warning: {} is not parseable, skipping.".format(source), file=sys.stderr)
return
if not self.quiet:
print("» module:", source)
loader = importlib.machinery.SourceFileLoader(os.path.basename(source), source)
mod = types.ModuleType(loader.name)
sourceinfos.module = mod
if not os.path.dirname(source) in sys.path:
sys.path.append(os.path.dirname(source))
try:
loader.exec_module(mod)
except Exception as e:
if not self.quiet:
print(" Warning: skipping due to import error: {}".format(e))
return
def moveinternal(moveglobals, function, arguments, body, local, lambdafunctions, imports, dependencies, tainted, features, role, debug, endpoint, globalvars, cfc):
if not self.quiet:
print(" function: {}".format(function))
self.functions[function] = (moveglobals[function], None, sourceinfos)
lambadalib.lambada.moveinternal = moveinternal
lambadalib.lambada.move(mod.__dict__, local=True)
```
build-docker-images.sh
```#!/bin/sh
if [ "$1" = "build" ]
then
rm -rf _snafu_clean_
git clone .. _snafu_clean_
#cd _snafu_clean_
cp Dockerfile* _snafu_clean_
docker build -t snafu -f _snafu_clean_/Dockerfile _snafu_clean_
docker tag snafu jszhaw/snafu
docker build -t snafucomplete -f _snafu_clean_/Dockerfile.complete _snafu_clean_
else
echo "# Note: Not building. Run with 'build' option to build."
fi
if [ "$1" = "release" ]
then
docker tag snafu jszhaw/snafu
docker tag snafucomplete jszhaw/snafucomplete
docker push jszhaw/snafu
docker push jszhaw/snafucomplete
else
echo "# Note: Not pushing. Run with 'release' option to push."
fi
```
javascript.py
```# Snafu: Snake Functions - JavaScript Parser
def activatefile(self, source, convention, SnafuFunctionSource):
if not self.quiet:
print("» javascript module:", source)
try:
import pyesprima.pyesprima3
except:
if not self.quiet:
print("Warning: javascript parser not ready for {}, skipping.".format(source), file=sys.stderr)
return
#pyesprima.pyesprima3.unichr = chr
try:
ast = pyesprima.pyesprima3.parse(open(source).read())
except Exception as e:
if not self.quiet:
print("Warning: {} is not parseable, skipping. [{}]".format(source, e), file=sys.stderr)
return
for body in ast.body:
if body.type == "FunctionDeclaration":
funcname = body["id"]["name"]
if funcname == "main":
funcname = os.path.basename(source).split(".")[0] + "." + funcname
if not self.quiet:
print(" function: {}".format(funcname))
sourceinfos = SnafuFunctionSource(source, scan=False)
funcparams = ["input"]
self.functions[funcname] = ([funcname] + funcparams, None, sourceinfos)
else:
if not self.quiet:
print(" skip function {}".format(funcname))
elif body.type == "ExpressionStatement":
if body.expression.left.type == "MemberExpression":
if body.expression.left.object.name == "exports":
funcname = body.expression.left.property.name
funcname = os.path.basename(source).split(".")[0] + "." + funcname
if not self.quiet:
print(" function: {}".format(funcname))
sourceinfos = SnafuFunctionSource(source, scan=False)
funcparams = ["req", "res"]
self.functions[funcname] = ([funcname] + funcparams, None, sourceinfos)
```
test-dist.sh
```#!/bin/bash
if [ -d ../dist ]
then
cd ..
fi
if [ ! -d dist ]
then
echo "Error: Needs to run from root directory." >&2
exit 1
fi
python3 setup.py bdist_egg
mkdir -p dist/test-dist
virtualenv -p python3 dist/test-dist
cp dist/snafu-0.0.0-py3.5.egg dist/test-dist
cd dist/test-dist
source bin/activate
easy_install -Z snafu-0.0.0-py3.5.egg
bash
```
javascript.py
```# Snafu: Snake Functions - JavaScript Executor
import subprocess
import time
import os.path
def execute(func, funcargs, envvars, sourceinfos):
sourcemodule = sourceinfos.source[:-3]
if "." in func:
func = func.split(".")[1]
# exports hack
sourcemodulemod = sourcemodule + ".js.export"
if not os.path.isfile(sourcemodulemod):
code = open(sourcemodule + ".js").read()
if not "exports" in code:
f = open(sourcemodulemod, "w")
f.write(code)
f.write("\n")
f.write("function mainwrapper(input){console.log(main(input));}\n")
f.write("exports.main = mainwrapper;\n")
sourcemodule = sourcemodulemod
else:
sourcemodule = sourcemodulemod
# message hack
if not "{" in funcargs[0]:
funcargs[0] = "\"{\"body\": {\"message\": \"%s\"}}\"" % funcargs[0]
if sourcemodulemod != sourcemodule:
cmd = "nodejs -e 'require(\"./%s\").%s(%s, {\"status\": function(x){return {\"send\": function(x){console.log(\"RET:\" + x)}}}})'" % (sourcemodule, func, funcargs[0])
else:
cmd = "nodejs -e 'require(\"./%s\").%s(%s)'" % (sourcemodule, func, funcargs[0])
stime = time.time()
p = subprocess.run(cmd, stdout=subprocess.PIPE, shell=True)
out = p.stdout.decode("utf-8")
dtime = time.time() - stime
success = False
res = []
for line in out.split("\n"):
if sourcemodulemod != sourcemodule:
if line.startswith("RET:"):
success = True
res = line[4:]
break
else:
success = True
res = line
break
return dtime, success, res
```
JavaExec.java
```import java.net.URL;
import java.net.URLClassLoader;
import java.net.MalformedURLException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.ArrayList;
class FunctionLoader
{
private Method function = null;
private Object object = null;
private boolean debug = false;
public FunctionLoader(boolean debug)
{
this.debug = debug;
}
private void logfail(String context, String s)
{
System.err.println("ERROR: [" + String.format("%12s", context) + "] " + s);
}
private void debug(String context, String s)
{
System.out.println("DEBUG: [" + String.format("%12s", context) + "] " + s);
}
public void load(String classname, String methodname)
{
URL url = null;
try
{
url = new URL("file://./" + classname + ".class");
}
catch(MalformedURLException e)
{
this.logfail(classname, "Inaccessible function: " + e.toString());
return;
}
URL[] urls = {url};
URLClassLoader loader = new URLClassLoader(urls);
Class plc = null;
try
{
plc = Class.forName(classname, true, loader);
}
catch(ClassNotFoundException e)
{
this.logfail(classname, "Invalid function: " + e.toString());
return;
}
Object plo = null;
try
{
plo = plc.newInstance();
}
catch(InstantiationException|IllegalAccessException e)
{
this.logfail(classname, "Function initialisation failure: " + e.toString());
return;
}
Method method = null;
//try
{
//method = plc.getMethod(methodname, Object.class, Object.class);
//method = plc.getMethod(methodname, new Class[]{});
Method[] methods = plc.getMethods();
for(Method cmethod : methods)
{
if(methodname.equals("SCAN"))
{
if((!cmethod.getName().equals("wait"))
&& (!cmethod.getName().equals("equals"))
&& (!cmethod.getName().equals("toString"))
&& (!cmethod.getName().equals("hashCode"))
&& (!cmethod.getName().equals("getClass"))
&& (!cmethod.getName().equals("notify"))
&& (!cmethod.getName().equals("notifyAll")))
{
Parameter[] parameters = cmethod.getParameters();
String params = "";
for(Parameter p : parameters)
params += " " + p.getName();
System.out.println(cmethod.getName() + params);
}
}
else if(cmethod.getName().equals(methodname))
{
method = cmethod;
}
}
}
/*catch(NoSuchMethodException e)
{
this.logfail(classname, "Method assignment failure: " + e.toString());
return;
}*/
if(method != null)
{
this.object = plo;
this.function = method;
}
}
public void exec(Object[] parametervalues)
{
String functionname = this.function.getName();
Parameter[] parametertypes = this.function.getParameters();
debug(functionname, this.function.toString());
debug(functionname, parametertypes.toString());
for(Parameter p : parametertypes)
debug(functionname, p.toString());
if(parametervalues.length != parametertypes.length)
{
this.logfail(functionname, "Non-matching parameter count.");
}
List<Object> parameterlist = new ArrayList<Object>();
for(int i = 0; i < parametervalues.length; i++)
{
Object p = parametervalues[i];
if(parametertypes[i].getType() == int.class)
p = Integer.parseInt((String)p);
parameterlist.add(p);
}
Object[] parameters = parameterlist.toArray();
Object result = null;
try
{
result = this.function.invoke(this.object, parameters);
}
catch(IllegalAccessException|InvocationTargetException e)
{
this.logfail(functionname, "Method invocation failure: " + e.toString());
return;
}
System.out.println(result);
}
}
public class JavaExec
{
public JavaExec()
{
}
public void init(String classname, String methodname, Object[] parametervalues)
{
FunctionLoader fl = new FunctionLoader(false);
fl.load(classname, methodname);
if(!methodname.equals("SCAN"))
{
fl.exec(parametervalues);
}
}
public final static void main(String[] args)
{
ArrayList<String> params = new ArrayList<String>();
for(int i = 2; i < args.length; i++)
params.add(args[i]);
JavaExec exec = new JavaExec();
exec.init(args[0], args[1], params.toArray());
}
}
```
inmemstateless.py
```# Snafu: Snake Functions - In-Memory Stateless (Isolated) Executor
import os
import time
import importlib.machinery
def execute(func, funcargs, envvars, sourceinfos):
loader = importlib.machinery.SourceFileLoader(os.path.basename(sourceinfos.source), sourceinfos.source)
loader.exec_module(sourceinfos.module)
for envvar in envvars:
os.environ[envvar] = envvars[envvar]
stime = time.time()
try:
res = func(*funcargs)
success = True
except Exception as e:
res = e
success = False
dtime = (time.time() - stime) * 1000
return dtime, success, res
```
setup.py
```# python3 setup.py sdist
# python3 setup.py bdist_wheel
# python3 setup.py bdist_egg
# twine upload dist/*.* [-r testpypi]
# -> automated in tools/make-dist.sh
from setuptools import setup
import os
with open("README", "r") as fh:
long_description = fh.read()
setup(
name="snafu",
description="Swiss Army Knife of Serverless Computing",
long_description=long_description,
version="0.0.3",
url="https://github.com/serviceprototypinglab/snafu",
author="Josef Spillner",
author_email="josef.spillner@zhaw.ch",
license="Apache 2.0",
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"Environment :: Console",
"Environment :: No Input/Output (Daemon)",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware"
],
keywords="cloud faas serverless functions",
packages=["snafulib", "snafulib.executors", "snafulib.loggers", "snafulib.authenticators", "snafulib.connectors"],
scripts=["snafu", "snafu-import", "snafu-accounts", "snafu-control"],
install_requires=["flask"]
)
```
helloworldpy2.py
```def helloworld():
return str(5 / 2)
```
python2stateful.py
```# Snafu: Snake Functions - Python2 Stateful Executor
#import json
import subprocess
#import pickle
#import base64
import threading
import queue
import os
import time
firstcall = {}
def asynccommand(command, commandprocess, qerr, qout, inputline, wait=True):
def queuethread(out, queue):
try:
for line in iter(out.readline, b""):
line = line.decode("utf-8").strip()
queue.put(line)
except Exception as e:
pass
if not commandprocess:
commandprocess = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
commandprocess.stdin.write(bytes(inputline + "\n", "utf-8"))
commandprocess.stdin.flush()
if not qout and not qerr:
qout = queue.Queue()
qerr = queue.Queue()
tout = threading.Thread(target=queuethread, args=(commandprocess.stdout, qout))
tout.daemon = True
tout.start()
terr = threading.Thread(target=queuethread, args=(commandprocess.stderr, qerr))
terr.daemon = True
terr.start()
if not wait:
return commandprocess, qerr, qout, ""
results = ""
had_output = False
counter = 0
while True:
both_empty = True
try:
line = qout.get(timeout=0.001)
except queue.Empty:
pass
else:
had_output = True
both_empty = False
results += line
try:
line = qerr.get(timeout=0.001)
except queue.Empty:
pass
else:
#had_output = True
both_empty = False
#results += "(err)" + line
if had_output and both_empty:
return commandprocess, qerr, qout, results
#counter += 1
#if counter > 100:
# return commandprocess, qerr, qout, results
def execute_internal(func, funcargs, envvars, sourceinfos):
global firstcall
import_stmt1 = "import os"
import_stmt2 = "os.chdir('{}')".format(os.path.dirname(sourceinfos.source))
module = os.path.basename(sourceinfos.source)[:-3]
import_stmt3 = "import {}".format(module)
funcargsfmt = []
for funcarg in funcargs:
if type(funcarg) in (dict, list, int, float):
funcargsfmt.append(str(funcarg))
else:
funcargsfmt.append("\"{}\"".format(str(funcarg)))
funcargsfmt = ",".join(funcargsfmt)
exec_stmt = "{}.{}({})".format(module, func.__name__, funcargsfmt)
callid = threading.get_ident()
if not callid in firstcall:
proc, qerr, qout, r1 = asynccommand("python2 -iu", None, None, None, import_stmt1, wait=False)
proc, qerr, qout, r2 = asynccommand(None, proc, qerr, qout, import_stmt2, wait=False)
proc, qerr, qout, r3 = asynccommand(None, proc, qerr, qout, import_stmt3, wait=False)
firstcall[callid] = proc, qerr, qout
else:
proc, qerr, qout = firstcall[callid]
proc, qerr, qout, r4 = asynccommand(None, proc, qerr, qout, exec_stmt)
#for i, funcarg in enumerate(funcargs):
# if "__class__" in dir(funcarg) and funcarg.__class__.__name__ == "SnafuContext":
# funcargs[i] = "pickle:" + base64.b64encode(pickle.dumps(funcarg, protocol=2)).decode("utf-8")
# + envvars
#funcargs = json.dumps(funcargs)
#envvars = json.dumps(envvars)
return r4.replace("'", "\"")
def execute(func, funcargs, envvars, sourceinfos):
stime = time.time()
try:
res = execute_internal(func, funcargs, envvars, sourceinfos)
success = True
except Exception as e:
res = e
success = False
dtime = (time.time() - stime) * 1000
return dtime, success, res
```
lxc.py
```# Snafu: Snake Functions - LXC Executor
import os
import time
import lxc
#import io
#import sys
import tempfile
#def wrapper(func, funcargs):
# print(func(*funcargs))
def wrapper(funcwithargs):
print(funcwithargs[1](*funcwithargs[2:]), file=funcwithargs[0])
def execute(func, funcargs, envvars, sourceinfos):
for envvar in envvars:
os.environ[envvar] = envvars[envvar]
c = lxc.Container("snafu")
c.create("download", 0, {"dist": "alpine", "release": "3.6", "arch": "amd64"})
success = c.start()
if not success:
raise Exception("LXC permissions insufficient")
#channel = io.StringIO()
channel = tempfile.TemporaryFile(mode="w+", buffering=1)
stime = time.time()
try:
c.attach_wait(wrapper, (channel, func, *funcargs))
channel.seek(0)
res = channel.read().strip()
success = True
except Exception as e:
res = e
success = False
dtime = (time.time() - stime) * 1000
return dtime, success, res
```
cli.py
```# Snafu: Snake Functions - CLI Connector
def request():
s = input("Function name:")
return s
def reply(s):
print(s)
```
sqlite.py
```# Snafu: Snake Functions - SQLite Logger
import sqlite3
import os
import configparser
def log(source, function, duration, success, configpath):
logurl = "/tmp/snafu.sqlite"
if not configpath:
configpath = "snafu.ini"
if os.path.isfile(configpath):
config = configparser.ConfigParser()
config.read(configpath)
if "snafu" in config and "logger.sqlite" in config["snafu"]:
logurl = config["snafu"]["logger.sqlite"]
init = False
if not os.path.isfile(logurl):
init = True
conn = sqlite3.connect(logurl)
c = conn.cursor()
if init:
c.execute("CREATE TABLE log (source text, function text, duration real, success bool)")
c.execute("INSERT INTO log (source, function, duration, success) VALUES ('{}', '{}', {}, '{}')".format(source, function, duration, success))
conn.commit()
conn.close()
```
snafu-import
```#!/usr/bin/env python3
#
# Snafu: Snake Functions - Import Utility Comand-Line Tool
import snafulib.snafuimport
snafulib.snafuimport.SnafuImportRunner()
```
lambdaenv.py
```import os
def lambda_handler(event, context):
return os.getenv("THEANSWER") or ""
```
snafu-control
```#!/usr/bin/env python3
#
# Snafu: Snake Functions - Control Plane Command-Line Tool
import snafulib.snafucontrol
snafulib.snafucontrol.SnafuControlRunner()
```
aws.py
```# Snafu: Snake Functions - Lambda Authenticator
import hmac
import hashlib
import base64
import os.path
import configparser
import binascii
def hmacsha256(secret, msg):
return hmac.new(secret, msg=msg, digestmod=hashlib.sha256).digest()
def authorise(flaskrequest):
auth = flaskrequest.headers.get("Authorization")
host = flaskrequest.headers.get("Host")
amzdate = flaskrequest.headers.get("X-Amz-Date")
if not auth or not host or not amzdate:
return False
path = flaskrequest.path
method = flaskrequest.method
auth = auth.split(" ")
if len(auth) != 4:
return False
algo, cred, sh, sig = auth
if algo != "AWS4-HMAC-SHA256":
return False
cred = cred.split("=")
sh = sh.split("=")
sig = sig.split("=")
if len(cred) != 2 or len(sh) != 2 or len(sig) != 2:
return False
if cred[0] != "Credential" or sh[0] != "SignedHeaders" or sig[0] != "Signature":
return False
cred = cred[1][:-1]
sh = sh[1][:-1]
sig = sig[1]
cred = cred.split("/")
if len(cred) != 5:
return False
keyid, date, region, service, request = cred
c = configparser.ConfigParser()
try:
accdb = os.path.expanduser("~/.snafu-accounts")
if os.getenv("HOME") == "/":
accdb = "/root/.snafu-accounts"
c.read(accdb)
except:
return False
sections = c.sections()
secretkey = None
for section in sections:
ckeyid = c.get(section, "access_key_id")
if ckeyid == keyid:
secretkey = c.get(section, "secret_access_key")
break
if not secretkey:
return False
enc = "utf-8"
b_secretkey = bytes("AWS4" + secretkey, enc)
b_date = bytes(date, enc)
b_region = bytes(region, enc)
b_service = bytes(service, enc)
b_request = bytes(request, enc)
ch = ""
ch += "host:{}".format(host) + "\n"
ch += "x-amz-date:{}".format(amzdate) + "\n"
# FIXME: check existing sh for required fields
#sh = "host" + ";" + "x-amz-date"
payload = flaskrequest.data
hp = hashlib.sha256(payload).hexdigest()
cr = ""
cr += method + "\n"
cr += path + "\n"
cr += "" + "\n"
cr += ch + "\n"
cr += sh + "\n"
cr += hp
hcr = base64.b16encode(hashlib.sha256(bytes(cr, "utf-8")).digest()).decode("utf-8").lower()
sts = ""
sts += algo + "\n"
sts += amzdate + "\n"
sts += "{}/{}/{}/{}".format(date, region, service, request) + "\n"
sts += hcr
b_string = bytes(sts, enc)
dig_dk = hmacsha256(b_secretkey, b_date)
dig_drk = hmacsha256(dig_dk, b_region)
dig_drsk = hmacsha256(dig_drk, b_service)
dig_sk = hmacsha256(dig_drsk, b_request)
dig_sig = hmacsha256(dig_sk, b_string)
signature = binascii.hexlify(dig_sig).decode("utf-8")
#print("SIGNATURE", signature)
#print("MATCH ", sig)
#return True
return keyid
```
filesystem.py
```# Snafu: Snake Functions - Filesystem Connector
import pyinotify
import threading
import os
import configparser
gcb = None
gf = None
class EventHandler(pyinotify.ProcessEvent):
def process_IN_CREATE(self, event):
event = {"file": event.pathname, "action": "create"}
gcb(gf, event=event)
def process_IN_DELETE(self, event):
event = {"file": event.pathname, "action": "delete"}
gcb(gf, event=event)
def initinternal(function, configpath):
global gcb
gf = function
connecturl = None
if not configpath:
configpath = "snafu.ini"
if not function:
function = "snafu"
if os.path.isfile(configpath):
config = configparser.ConfigParser()
config.read(configpath)
if function in config and "connector.filesystem" in config[function]:
connecturl = config[function]["connector.filesystem"]
if connecturl:
wm = pyinotify.WatchManager()
handler = EventHandler()
notifier = pyinotify.Notifier(wm, handler)
mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE
wdd = wm.add_watch(connecturl, mask, rec=True)
notifier.loop()
def init(cb, function=None, configpath=None):
global gcb
gcb = cb
t = threading.Thread(target=initinternal, daemon=True, args=(function, configpath))
t.start()
```
fib.py
```import time
import math
import json
import os
from boto3 import client as boto3_client
hostaccess = False
host = "localhost"
if hostaccess and os.path.isfile("/.dockerenv"):
host = "172.17.0.1"
lambda_client = boto3_client('lambda', endpoint_url='http://{}:10000'.format(host))
lambda_client._endpoint.timeout = 300 # comment for reaper
def fib(x):
msg = {"x": x}
import sys
fullresponse = lambda_client.invoke(FunctionName="fib.lambda_handler", Payload=json.dumps(msg))
response = json.loads(fullresponse["Payload"].read().decode("utf-8"))
return response["ret"]
def lambda_handler(event, context):
#time.sleep(0.1) # uncomment for reaper
x = event["x"]
if x in (1, 2):
return {"ret": 1}
ret = fib(x - 1) + fib(x - 2)
ret = {'ret': ret}
return ret
```
snafu
```#!/usr/bin/env python3
#
# Snafu: Snake Functions - Main Command-Line Tool
import snafulib.snafu
snafulib.snafu.SnafuRunner()
```
web.py
```# Snafu: Snake Functions - Web Connector
import flask
import threading
import os
import configparser
app = flask.Flask("snafu")
gcb = None
@app.route("/invoke/<function>")
def invoke(function):
response = gcb(function)
if not response:
flask.abort(500)
return response
def initinternal(function, configpath):
connectconfig = None
if not configpath:
configpath = "snafu.ini"
if not function:
function = "snafu"
if os.path.isfile(configpath):
config = configparser.ConfigParser()
config.read(configpath)
if function in config and "connector.web" in config[function]:
connectconfig = int(config[function]["connector.web"])
if connectconfig:
app.run(host="0.0.0.0", port=connectconfig)
def init(cb, function=None, configpath=None):
global gcb
gcb = cb
t = threading.Thread(target=initinternal, daemon=True, args=(function, configpath))
t.start()
```
messaging.py
```# Snafu: Snake Functions - Messaging Connector
import kombu
import threading
import time
import os
import configparser
gcb = None
def initinternal(function, configpath):
connecturl = None
if not configpath:
configpath = "snafu.ini"
if not function:
function = "snafu"
if os.path.isfile(configpath):
config = configparser.ConfigParser()
config.read(configpath)
if function in config and "connector.messaging" in config[function]:
connecturl = config[function]["connector.messaging"]
if not connecturl:
return
print("(messaging:connecting)")
connection = kombu.Connection(connecturl)
connection.connect()
print("(messaging:connected)")
queue = connection.SimpleQueue("sslq")
while True:
try:
message = queue.get(block=True, timeout=20)
except:
print("(messaging:pass)")
pass
else:
print("(messaging:received {})".format(message.payload))
message.ack()
# FIXME: send back response as AMQP message
response = gcb(function, event="{}")
queue.close()
def init(cb, function=None, configpath=None):
global gcb
gcb = cb
t = threading.Thread(target=initinternal, daemon=True, args=(function, configpath))
t.start()
```
java.py
```# Snafu: Snake Functions - Java Executor
#import json
#import pickle
#import base64
import subprocess
import os
import time
def execute(func, funcargs, envvars, sourceinfos):
classname = os.path.basename(sourceinfos.source).split(".")[0]
methodname = func.split(".")[1]
#print(">> call", classname, methodname, func, funcargs, envvars, sourceinfos.source)
#classname, methodname = func.split(".")
javacmd = "java -cp snafulib/executors/java/:{} JavaExec {} {} {}".format(os.path.dirname(sourceinfos.source), classname, methodname, " ".join(funcargs))
#print(">> javacmd", javacmd)
stime = time.time()
out, err = subprocess.Popen(javacmd, shell=True, stdout=subprocess.PIPE).communicate()
dtime = (time.time() - stime) * 1000
#print(">> result", out)
out = out.decode("utf-8").split("\n")[-2]
return dtime, True, out
```
snafuaccounts.py
```# Snafu: Snake Functions - Account Management
import sys
import os.path
import argparse
import configparser
class SnafuAccounts:
def __init__(self):
self.accounts = {}
def addaccount(self, key, secret, endpoint):
accdb = os.path.expanduser("~/.snafu-accounts")
if os.getenv("HOME") == "/":
accdb = "/root/.snafu-accounts"
c = configparser.ConfigParser()
try:
c.read(accdb)
except:
pass
acc = "account{}".format(len(c.sections()))
c.add_section(acc)
c.set(acc, "access_key_id", key)
c.set(acc, "secret_access_key", secret)
if endpoint:
c.set(acc, "endpoint", endpoint)
f = open(accdb, "w")
c.write(f)
def run(self):
parser = argparse.ArgumentParser(description="Snake Functions as a Service - Account Management")
parser.add_argument("-a", "--add", help="add an account", action="store_true")
parser.add_argument("-k", "--key-id", help="access key id")
parser.add_argument("-s", "--secret-access-key", help="secret access key")
parser.add_argument("-e", "--endpoint", help="tenant-specific static endpoint")
args = parser.parse_args()
if args.add:
if not args.key_id or not args.secret_access_key:
print("Error: Must specify both --key-id and --secret-access-key for --add.", file=sys.stderr)
return
self.addaccount(args.key_id, args.secret_access_key, args.endpoint)
else:
print("Error: Must specify --add.", file=sys.stderr)
return
class SnafuAccountsRunner:
def __init__(self):
sa = SnafuAccounts()
sa.run()
```
csv.py
```# Snafu: Snake Functions - CSV Logger
import os
import configparser
def log(source, function, duration, success, configpath):
logurl = "snafu.csv"
if not configpath:
configpath = "snafu.ini"
if os.path.isfile(configpath):
config = configparser.ConfigParser()
config.read(configpath)
if "snafu" in config and "logger.csv" in config["snafu"]:
logurl = config["snafu"]["logger.csv"]
# FIXME: this part must become mt-safe through a protected section
f = open(logurl, "a")
print("{},{},{:1.3f},{}".format(source, function, duration, success), file=f)
f.close()
```
cron.py
```# Snafu: Snake Functions - Cron Connector
import threading
import time
import os
import configparser
gcb = None
def initinternal(function, configpath):
connectconfig = None
if not configpath:
configpath = "snafu.ini"
if not function:
function = "snafu"
if os.path.isfile(configpath):
config = configparser.ConfigParser()
config.read(configpath)
if function in config and "connector.cron" in config[function]:
connectconfig = int(config[function]["connector.cron"])
if connectconfig:
while True:
time.sleep(connectconfig)
response = gcb(function, event="{}")
def init(cb, function=None, configpath=None):
global gcb
gcb = cb
t = threading.Thread(target=initinternal, daemon=True, args=(function, configpath))
t.start()
```
java.py
```# Snafu: Snake Functions - Java Parser
import os
import subprocess
def precheck():
r = subprocess.run("java 2>/dev/null", shell=True)
if r.returncode == 127:
return False
return True
def activatefile(self, source, convention, SnafuFunctionSource):
if not os.path.isfile("snafulib/executors/java/JavaExec.class"):
pwd = os.getcwd()
os.chdir("snafulib/executors/java")
os.system("javac JavaExec.java")
os.chdir(pwd)
funcname = None
configname = source.split(".")[0] + ".config"
if os.path.isfile(configname):
if not self.quiet:
print(" config:", configname)
config = json.load(open(configname))
if config:
funcname = config["FunctionName"]
else:
if convention == "lambda":
if not self.quiet:
print(" skip source {}".format(source))
return
if source.endswith(".java"):
binfile = source.replace(".java", ".class")
if not os.path.isfile(binfile):
if not self.quiet:
print("» java source:", source)
pwd = os.getcwd()
os.chdir(os.path.dirname(source))
os.system("javac {}".format(os.path.basename(source)))
os.chdir(pwd)
source = binfile
else:
return
if not self.quiet:
print("» java module:", source)
if funcname:
# FIXME: shortcut leading to non-executable code for Lambda-imported Java
if not self.quiet:
print(" function: {}".format(funcname))
sourceinfos = SnafuFunctionSource(source, scan=False)
self.functions[funcname] = ([funcname], None, sourceinfos)
return
#javacmd = "java -cp executors/java/:{} JavaExec {} fib 3".format(os.path.dirname(source), os.path.basename(source).split(".")[0])
#javacmd = "java JavaExec Hello myHandler 5 null"
#print("JAVA", javacmd)
javacmd = "java -cp snafulib/executors/java/:{} JavaExec {} SCAN".format(os.path.dirname(source), os.path.basename(source).split(".")[0])
#os.system(javacmd)
out, err = subprocess.Popen(javacmd, shell=True, stdout=subprocess.PIPE).communicate()
for funcname in out.decode("utf-8").split("\n"):
if not funcname:
continue
funcname, *funcparams = funcname.split(" ")
funcname = os.path.basename(source).split(".")[0] + "." + funcname
if not self.quiet:
print(" function: {}".format(funcname))
sourceinfos = SnafuFunctionSource(source, scan=False)
self.functions[funcname] = ([funcname] + funcparams, None, sourceinfos)
```
sleep.py
```import time
def sleep():
# > maximum timeout of Lambda
time.sleep(310)
def lambda_handler(event, context):
sleep()
```
localfib.py
```def fib(n):
if type(n) == str:
n = int(n)
if n in (1, 2):
return 1
return fib(n - 1) + fib(n - 2)
```
c.py
```# Snafu: Snake Functions - C Executor
import subprocess
import os
import time
def execute(func, funcargs, envvars, sourceinfos):
#print(">> call", func, funcargs, envvars, sourceinfos.source)
ccmd = "snafulib/executors/c/cexec {} {}".format(sourceinfos.source, " ".join(funcargs))
stime = time.time()
out, err = subprocess.Popen(ccmd, shell=True, stdout=subprocess.PIPE).communicate()
dtime = (time.time() - stime) * 1000
try:
out = out.decode("utf-8").split("\n")[-2]
success = True
except:
out = ""
success = False
return dtime, success, out
```
python3-trace-exec.py
```# Snafu: Snake Functions - Python3 Executor (Exec Module)
import sys
import os
import time
import json
import base64
import pickle
import psutil
import datetime
import uuid
class Context:
def __init__(self):
self.SnafuContext = self
# def __new__(self):
# self.SnafuContext = self
# return self
frame_time_dict = {'frame': time.time()}
open_connections_old = []
open_connections = []
open_files_old = []
open_files = []
saved_variables = {'last_line': 0, 'last_time': -1}
proc = psutil.Process(os.getpid())
time_now = datetime.datetime.fromtimestamp(time.time()).strftime('%y%m%d-%H%M')
short_uuid = uuid.uuid4().hex[0:8]
func_name = sys.argv[2]
file_to_print_to_name = "trace_log-" + func_name + \
"-" + time_now + '-' + short_uuid + ".log"
file_to_print_to = open(file_to_print_to_name, 'w')
print("Printing trace to " + file_to_print_to_name, file=sys.stderr)
def trace(frame, event, arg):
# Potential optimization: put caller_string and function_string into a
# dictionary
# getting what code was called
line_no = frame.f_lineno
funcname = frame.f_code.co_name
filename = frame.f_code.co_filename
function_string = str(filename) + '.' + str(funcname)
# monitor performance metrics
interval = 10
if saved_variables['last_time'] == -1:
proc.cpu_percent()
proc.memory_percent()
saved_variables['last_time'] = time.time()
if int(100 * (time.time() - saved_variables['last_time'])) > interval:
print('performance -- CPU: ' +
str(proc.cpu_percent()) +
'% - Memory: ' +
str(proc.memory_percent()) +
'%', file=file_to_print_to)
saved_variables['last_time'] = time.time()
# monitor network connections
open_conections = proc.connections()
# check for newly closed connections
for connection in open_connections_old:
if connection not in open_conections:
protocol = 'udp' if connection.status == psutil.CONN_NONE else 'tcp'
print('Connection CLOSED by ' + function_string + ': ' + protocol +
' connection from ' + connection.laddr.ip + ':' + str(connection.laddr.port) +
' to ' + connection.raddr.ip + ':' + str(connection.laddr.port), file=file_to_print_to)
open_connections_old.remove(connection)
# check for newly opened connections
for connection in open_conections:
if connection not in open_connections_old:
protocol = 'udp' if connection.status == psutil.CONN_NONE else 'tcp'
print('Connection OPENED by ' + function_string + ': ' + protocol +
' connection from ' + connection.laddr.ip + ':' + str(connection.laddr.port) +
' to ' + connection.raddr.ip + ':' + str(connection.laddr.port), file=file_to_print_to)
open_connections_old.append(connection)
open_files = proc.open_files()
for open_file in open_files_old:
if open_file not in open_files:
acces_type = open_file.mode
print(
'File CLOSED by ' +
function_string +
' - Path: ' +
open_file.path,
file=file_to_print_to) # TODO give more details about file
open_files_old.remove(open_file)
for open_file in open_files:
if open_file not in open_files_old:
acces_type = open_file.mode
print(
'File OPENED by ' +
function_string +
' in mode \'' +
acces_type +
'\' - Path: ' +
open_file.path,
file=file_to_print_to) # TODO give more details about file
open_files_old.append(open_file)
# getting who called the code
has_caller = frame.f_back is not None
caller_string = ''
if has_caller:
caller = frame.f_back
caller_funcname = caller.f_code.co_name
caller_filename = caller.f_code.co_filename
caller_string = caller_filename + '.' + caller_funcname
if event == 'call':
# inserting start time for the frame
frame_time_dict[frame] = time.time()
print(
'call from \t' +
caller_string +
' to ' +
function_string,
file=file_to_print_to)
if event == 'return':
# taking out the time for frame
time_elapsed_ms = round(
(time.time() - frame_time_dict[frame]) * 1000, 6)
print(
'return from \t' +
function_string +
' to ' +
caller_string +
' - time elapsed: ' +
str(time_elapsed_ms) +
"ms",
file=file_to_print_to)
if event == 'exception':
# TODO manually get traceback by calling the f_back objects and saving
# last called line per frame
print('exception in \t' + function_string + ' at line ' + \
str(saved_variables['last_line']) + ': ' + str(arg), file=file_to_print_to)
if event == 'line':
saved_variables['last_line'] = frame.f_lineno
# need to return tracefunc so that it still works after functioncalls
return trace
def execute(filename, func, funcargs, envvars):
funcargs = json.loads(funcargs)
envvars = json.loads(envvars)
for i, funcarg in enumerate(funcargs):
if type(funcarg) == str and funcarg.startswith("pickle:"):
sys.modules["lib"] = Context()
sys.modules["lib.snafu"] = Context()
#funcarg = pickle.loads(base64.b64decode(funcarg.split(":")[1]))
# FIXME: SnafuContext as in python2-exec module
funcarg = None
sys.path.append(".")
os.chdir(os.path.dirname(filename))
mod = __import__(os.path.basename(filename[:-3]))
func = getattr(mod, func)
for envvar in envvars:
os.environ[envvar] = envvars[envvar]
stime = time.time()
try:
# activate tracing
sys.settrace(trace)
res = func(*funcargs)
# deactivate tracing
sys.settrace(None)
success = True
except Exception as e:
res = e
success = False
dtime = (time.time() - stime) * 1000
# return dtime, success, res
return "{} {} {}".format(
dtime,
success,
"{}".format(res).replace(
"'",
"\""))
print(execute(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]))
```
openshift.py
```# Snafu: Snake Functions - OpenShift Executor
import requests
import os
import configparser
import subprocess
container = "jszhaw/snafu"
endpoints = {}
def executecontrol(flaskrequest, tenant):
if not tenant in endpoints:
username = os.getenv("OPENSHIFT_USERNAME")
password = os.getenv("OPENSHIFT_PASSWORD")
password = os.getenv("OPENSHIFT_PROJECT")
if not username or not password or not project:
return
os.system("oc login https://console.appuio.ch/ --username={} --password={}".format(username, password))
os.system("oc project {}".format(project))
os.system("oc new-app --name snafu-{} jszhaw/snafu".format(tenant))
p = subprocess.run("oc status | grep svc/snafu-{} | cut -d " " -f 3".format(tenant), shell=True, stdout=subprocess.PIPE)
endpoints[tenant] = "http://{}".format(p.decode("utf-8"))
# FIXME: mounting the tenant's volume container to /opt/functions-local
endpoint = endpoints[tenant]
headers = {}
headers["X-Amz-Date"] = flaskrequest.headers.get("X-Amz-Date")
data = flaskrequest.data.decode("utf-8")
#method=r.method -> requests.post
reply = requests.post(endpoint + flaskrequest.path, data=data, headers=headers)
if reply.status_code == 200:
return reply.content.decode("utf-8")
else:
return
```
python.py
```# Snafu: Snake Functions - Python Parser
import os
import ast
import importlib
import types
import sys
import json
def activatefile(self, source, convention, SnafuFunctionSource):
sourceinfos = None
try:
sourceinfos = SnafuFunctionSource(source)
sourcecode = sourceinfos.content
except:
print("Warning: {} is not parseable, skipping.".format(source), file=sys.stderr)
return
if not self.quiet:
print("» module:", source)
handler = None
config = None
configname = source.split(".")[0] + ".config"
if os.path.isfile(configname):
if not self.quiet:
print(" config:", configname)
config = json.load(open(configname))
if config:
if "Handler" in config:
handler = config["Handler"]
connectorconfig = None
connectorconfigname = source.split(".")[0] + ".ini"
if os.path.isfile(connectorconfigname):
if not self.quiet:
print(" connectors:", connectorconfigname)
connectorconfig = connectorconfigname
sourcetree = ast.parse(sourcecode)
loader = importlib.machinery.SourceFileLoader(os.path.basename(source), source)
mod = types.ModuleType(loader.name)
sourceinfos.module = mod
if not os.path.dirname(source) in sys.path:
sys.path.append(os.path.dirname(source))
try:
loader.exec_module(mod)
except Exception as e:
if not self.quiet:
print(" Warning: skipping due to import error: {}".format(e))
return
sourcename = os.path.basename(source).split(".")[0]
for node in ast.walk(sourcetree):
if type(node) == ast.FunctionDef:
if not handler:
handlername = "lambda_handler"
handlerbase = sourcename
else:
handlerbase, handlername = handler.split(".")
if convention not in ("lambda", "openwhisk") or (node.name == handlername and sourcename == handlerbase):
funcname = sourcename + "." + node.name
if config and "FunctionName" in config and convention in ("lambda", "openwhisk"):
funcname = config["FunctionName"]
try:
func = getattr(mod, node.name)
except:
print(" skip method {}.{}".format(sourcename, node.name))
else:
if not self.quiet:
print(" function: {}".format(funcname))
#if not node.name in self.functions:
# self.functions[node.name] = {}
#self.functions[node.name][sourcename] = (func, config, sourceinfos)
self.functions[funcname] = (func, config, sourceinfos)
if connectorconfig:
self.functionconnectors[funcname] = connectorconfig
else:
if not self.quiet:
print(" skip function {}.{}".format(sourcename, node.name))
```
proxy.py
```# Snafu: Snake Functions - Proxy Executor
import requests
import os
import configparser
def executecontrol(flaskrequest, tenant):
endpoint = None
if tenant:
c = configparser.ConfigParser()
try:
accdb = os.path.expanduser("~/.snafu-accounts")
if os.getenv("HOME") == "/":
accdb = "/root/.snafu-accounts"
c.read(accdb)
except:
return
sections = c.sections()
for section in sections:
ckeyid = c.get(section, "access_key_id")
if ckeyid == tenant:
endpoint = c.get(section, "endpoint")
break
else:
config = configparser.ConfigParser()
config.read("snafu.ini")
if "snafu" in config and "executor.proxy" in config["snafu"]:
endpoint= config["snafu"]["executor.proxy"]
if not endpoint:
return
headers = {}
headers["X-Amz-Date"] = flaskrequest.headers.get("X-Amz-Date")
data = flaskrequest.data.decode("utf-8")
#method=r.method -> requests.post
reply = requests.post(endpoint + flaskrequest.path, data=data, headers=headers)
if reply.status_code == 200:
return reply.content.decode("utf-8")
else:
return
```
inmemory.py
```# Snafu: Snake Functions - In-Memory Executor
import os
import time
def execute(func, funcargs, envvars, sourceinfos):
for envvar in envvars:
os.environ[envvar] = envvars[envvar]
stime = time.time()
try:
res = func(*funcargs)
success = True
except Exception as e:
res = e
success = False
dtime = (time.time() - stime) * 1000
return dtime, success, res
```
perfMetrics.py
```# Performance metrics generation, useful for testing python3trace executor
import psutil
import os
import sys
import socket
def waste_cpu():
for x in range(0,999999):
pass
def connect_tcp():
TCP_IP = '127.0.0.1'
TCP_PORT = 5006
BUFFER_SIZE = 1024
MESSAGE = b'Hello, World!'
#--
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()
#--
def open_file():
code = open('localfib.py','r')
content = code.read()
```
|
00s/lorn
|
00s/lorn
Diamond.js
```// Diamond CLass
var Diamond = (function () {
// constructor
function Diamond(x, y) {
this._width = 52;
this._height = 40;
// spriteSheet setup
this.data = {
images: [queue.getResult("diamond")],
frames: { width: this._width, height: this._height, regX: 26, regY: 20},
animations: {
glow: [0, 2, "glow", 0.3]
}
};
this.spriteSheet = new createjs.SpriteSheet(this.data);
this.animation = new createjs.Sprite(this.spriteSheet, "glow");
this.animation.scaleX = 0.5;
this.animation.scaleY = 0.5;
// x and y params used for seting the object in stage
this.animation.x = x;
this.animation.y = y;
stage.addChild(this.animation);
console.log("diamond added at " + x +", "+ y);
}
Diamond.prototype.update = function (sense, velocity) {
this.animation.x -= sense*(velocity);
}
Diamond.prototype.redefinePosition = function () {
this.animation.x = canvasW * 5;
}
FireBall.prototype.dismiss = function () {
stage.removeChild(this.animation);
}
return Diamond;
})();
```
Tree.js
```var BLUR_AMOUNT = 20;
var BLUR_RADIUS = 1;
var Tree = (function () {
function Tree (x, y, parallax) {
this.PARALLAX_FACTOR = 8;
this.parallax = parallax;
this.image = new createjs.Bitmap(queue.getResult("tree"));
this.width = this.image.getBounds().width;
this.height = this.image.getBounds().height;
var blur = new createjs.BlurFilter((1.2 - parallax) *BLUR_AMOUNT,(1.2 - parallax) *BLUR_AMOUNT,BLUR_RADIUS);
this.image.filters = [blur];
this.image.cache(0,0,this.width, this.height);
this.image.regX = this.width * 0.5;
this.image.regY = this.height;
this.image.scaleX *= parallax;
this.image.scaleY *= parallax;
this.image.x = x;
this.image.y = y;
stage.addChild(this.image);
}
Tree.prototype.move = function (sense) {
this.image.x -= sense*(this.parallax * this.PARALLAX_FACTOR);
}
return Tree;
})();```
game.js
```// ©
var stage;
var queue;
var canvas;
// ENUM for keys
Key = {
UP : 38,
LEFT : 37,
RIGHT : 39,
SPACE : 32,
P: 80,
I: 73,
O:79,
M: 77
}
// ENUM GAME STATE
Game = {
HOME : 0,
PLAYING : 1,
OVER : 2
}
// Game state
var state;
//controls
var controls
// reference for Instructions
var dejavu = false;
// gameOver obj
var endMessage
// soundtrack
var soundtrack;
// Game Objects
var display;
var lorn;
var diamond;
// FireBall Array
var fireballs = [];
// Tree Array
var trees = [];
// Cats Array
var cats = [];
// Game Constants
var TREE_NUM = 11;
var CAT_NUM = 4;
var GROUND_LEVEL = Math.max( window.innerHeight, document.body.clientHeight) - 35;
var PARALLAX = 8;
var LORN_REG_Y = 24;
var CAT_REG_Y = 16;
var TREE_REG_Y = 124;
var GAME_FONT = "VT323";
var FONT_SIZE = 22;
var FONT_COLOUR = "white";
function preload() {
queue = new createjs.LoadQueue();
queue.installPlugin(createjs.Sound);
queue.addEventListener("loadstart", loading);
queue.addEventListener("complete", init);
queue.loadManifest([
{ id: "diamond-song", src: "sounds/Lorn-Diamond.ogg" },
{ id: "thunder", src: "sounds/thunder.ogg" },
{ id: "engine", src: "sounds/engine.ogg" },
{ id: "lorn", src: "images/lorn.png" },
{ id: "fireball", src: "images/fireball.png" },
{ id: "cat", src: "images/cat.png"},
{ id: "tree", src: "images/tree.png"},
{ id: "diamond", src: "images/diamond.png"},
{ id: "brand", src: "images/gamebrand.png"},
{ id: "controls", src: "images/controls.png"}
]);
}
function loading(){
stage = new createjs.Stage(document.getElementById("canvas"));
canvas = document.getElementById("canvas");
canvas.width = document.body.clientWidth; //document.width is obsolete
canvas.height = GROUND_LEVEL; //document.height is obsolete
canvasW = canvas.width;
canvasH = canvas.height;
stage.addChild(new Display(". . .", 90, GAME_FONT, FONT_COLOUR, canvasW * 0.45, canvasH * 0.5));
}
function init() {
stage.removeAllChildren();
// game soundtrack
soundtrack = createjs.Sound.play("diamond-song");
soundtrack.stop();
soundtrack.addEventListener("complete", createjs.proxy(this.handleComplete, this));
soundtrack.volume = 0.1;
// handlers for keyboard inputs
window.addEventListener( "keydown", handleKeyDown, false );
window.addEventListener( "keyup", handleKeyUp, false );
//stage.enableMouseOver(20);
createjs.Ticker.setFPS(40);
createjs.Ticker.addEventListener("tick", gameLoop);
//gameStart();
state = Game.HOME;
}
// Game Loop
function gameLoop(event) {
// switches between game states
switch(state){
case Game.HOME:
homeScreen();
break;
case Game.PLAYING:
playing();
break;
case Game.OVER:
gameover();
break;
}
stage.update();
}
function getCentralizedBitmap(idOrUrl){
var bit = new createjs.Bitmap(queue.getResult(idOrUrl));
bit.regX = bit.getBounds().width * 0.5;
bit.regY = bit.getBounds().height * 0.5;
bit.x = canvasW * 0.5;
bit.y = canvasH * 0.5;
return bit;
}
function homeScreen () {
stage.clear();
var brand = getCentralizedBitmap("brand");
stage.addChild(brand);
}
function presentControls(){
if(!this.dejavu){
controls = getCentralizedBitmap("controls");
controls.y = canvasW * 0.10;
stage.addChild(controls);
setTimeout(function(){
stage.removeChild(controls);
this.dejavu = true;
}, 5000);
}
}
function playing(){
if(lorn.lives <= 0)
state = Game.OVER;
if(!lorn.hitten)
for (var count = 0; count < CAT_NUM; count++) {
if(rectCollisionDetection(lorn, cats[count])){
lorn.wasHitten();
console.log("Lorn lives: " + lorn.lives);
}
}
updateTrees();
lorn.update();
updateFireBalls();
diamond.update(lorn.getSense(true), PARALLAX);
if(rectCollisionDetection(lorn, diamond)){
lorn.colectDiamond();
diamond.redefinePosition();
}
for (var count = 0; count < CAT_NUM; count++) {
cats[count].update(lorn.getSense(true));
}
// get player status and update display screen
display.update(lorn.toString());
}
function gameover() {
// gameover
lastStatus = lorn.getTotalScore();
lastStatus = (lastStatus > 0) ? lastStatus : 0;
stage.clear();
stage.removeAllChildren();
soundtrack.stop();
fireballs = [];
trees = [];
cats = [];
var gameoverMsg = new Display("GAME OVER", 90, "VT323", "white", canvasW * 0.5, canvasH *0.2);
var scores = new Display("YOU SCORED "+ lastStatus, 85, "VT323", "white", canvasW * 0.5, canvasH *0.5);
var reminder = endMessage = new Display("press space to restart", 50, "VT323", "white", canvasW * 0.5, canvasH *0.8);
}
function updateTrees(){
for(var count = 0 ; count < TREE_NUM ; count++){
var tree = trees[count];
tree.move(lorn.getSense(true));
// reuse trees when they are out of the bounds
if(tree.image.x < -(canvasW * 0.5)){
tree.image.x = canvasW + canvasW * 0.25;
}
if(tree.image.x > canvasW + canvasW * 0.5){
tree.image.x = -(canvasW * 0.25)
}
}
}
function updateFireBalls(){
// update each fireball on stage and remove from stage the ones that are out of view.
for (i = 0; i < fireballs.length; i++) {
if(fireballs[i] !== undefined){
fireballs[i].update(lorn.getSense());
var dismissable = false;
if(fireballs[i].animation.x > canvasW || fireballs[i].animation.x < 0){
dismiss(fireballs[i], fireballs, i);
dismissable = true;
}
// check colision between fireballs and cats
for (var count = 0; count < CAT_NUM; count++) {
var cat = cats[count];
if(rectCollisionDetection(fireballs[i], cat)){
cat.randomizeCatDrop();
dismissable = true;
lorn.hitCat();
console.log("fireball has hitten a poor cat");
}
}
if(dismissable)
dismiss(fireballs[i], fireballs, i);
}
}
}
// Keyboard handlers
function handleKeyDown(event){
switch(event.keyCode){
case Key.UP:
console.log("Key.UP pressed");
lorn.startJump();
break;
case Key.LEFT:
console.log("Key.LEFT pressed");
lorn.moveLeft();
break;
case Key.RIGHT:
console.log("Key.RIGHT pressed");
lorn.moveRight();
break;
case Key.I:
// volume down
soundtrack.volume -= 0.05;
break;
case Key.O:
// volume up
soundtrack.volume += 0.05;
break;
case Key.M:
soundtrack.setMute(!soundtrack.getMute());
break;
case Key.P:
break;
}
}
function handleKeyUp(event){
if(state == Game.HOME){
state = Game.PLAYING;
gameStart();
}else{
switch(event.keyCode){
case Key.UP:
console.log("Key.UP released");
lorn.endJump();
break;
case Key.SPACE:
// RESTART GAME if state is Game.OVER
if(state == Game.OVER){
state = Game.PLAYING;
gameStart();
//init();
}
console.log("Key.SPACE released");
x = lorn.animation.x;
y = lorn.animation.y;
if(lorn.hasFireBalls()){
console.log("lorn's shooted");
fireballs.push(new FireBall(x, y, lorn.getSense(false)));
lorn.shoot();
stage.addChild(fireballs[fireballs.length - 1].animation);
}
break;
case Key.LEFT:
console.log("Key.LEFT released");
lorn.stopMovingLeft();
break;
case Key.RIGHT:
console.log("Key.RIGHT released");
lorn.stopMovingRight();
break;
}
}
}
// auxiliar function for removing object from list and animation from stage
function dismiss(obj, list, index){
stage.removeChild(obj.animation);
list.splice(index,1);
}
// Class for holding corner references of Animation objects
var AnimationBorder = (function(){
function AnimationBorder(obj){
// used to reduced the final area (in pixels)
var CORRECTION = 3;
var objW = obj._width;
var objH = obj._height;
this.leftBound = (obj.animation.x - (objW * 0.5)) + CORRECTION;
this.rightBound = (this.leftBound + objW) - CORRECTION;
this.topBound = (obj.animation.y - (objH * 0.5)) + CORRECTION;
this.bottomBound = (this.topBound + objH) - CORRECTION;
}
return AnimationBorder;
})();
function rectCollisionDetection(obj, target){
var frst = new AnimationBorder(obj);
var scnd = new AnimationBorder(target);
//console.log("borders: " + scnd.leftBound + ", "+ scnd.rightBound + ", " + scnd.topBound+ ", " + scnd.bottomBound)
var collision = true;
// If any side from FRST is outside of SCND
if( frst.bottomBound <= scnd.topBound || frst.topBound >= scnd.bottomBound || frst.rightBound <= scnd.leftBound|| frst.leftBound >= scnd.rightBound)
{
collision = false;
}
if(collision)
console.log("colision detected.");
return collision;
}
// Main Game Function
function gameStart() {
stage.clear();
stage.removeAllChildren();
soundtrack.play();
presentControls();
var zOrder = [];
// randomize values for parallax effect
for (var count = 0; count < TREE_NUM; count++) {
zOrder.push((Math.random() - 0.4)+0.7);
}
// sort results for setting up trees order
zOrder.sort();
// add trees at the stage based on zOrder list (in ascending order)
for (var count = 0; count < TREE_NUM; count++) {
console.log("parallax: " + zOrder[count]);
trees[count] = new Tree(Math.random()* canvasW * 1.25, GROUND_LEVEL, zOrder[count]);
}
lorn = new Lorn(canvasW * 0.5, GROUND_LEVEL - LORN_REG_Y);
diamond = new Diamond(canvasW + 30, GROUND_LEVEL - LORN_REG_Y);
for (var count = 0; count < CAT_NUM; count++) {
cats.push(new Cat());
}
display = new Display(".", FONT_SIZE, GAME_FONT, FONT_COLOUR, 15, 0);
}
```
Lorn.js
```var RECOVERING_TIME = 750;
var DISTANCE_PER_MOVE = 10;
var HIT_CAT_SCORE = 50;
var GRAVITY = 0.6;
var LIVES = 3;
// Auxiliar function for String Formating.
// src: http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format
if (!String.format) {
String.format = function(format) {
var args = Array.prototype.slice.call(arguments, 1);
return format.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}
// lorn Character
var Lorn = (function () {
// constructor
function Lorn(x, y) {
// variables for movement reference
this.jumping , this.movingLeft , this.movingRight = false;
this.velocityY = 0.0;
// PLAYER STATUS ATTRIBUTES
this.coveredDistance = 0;
this.score = 0;
this.lives = LIVES;
// Diamonds and Fireballs
this.fireballs = 0;
this.diamonds = 0;
// sprite size reference
this._width = 28;
this._height = 48;
// rectangle reference for collision detection
// SpriteSheet setup
this.data = {
images: [queue.getResult("lorn")],
frames: { width: this._width, height: this._height, regX: 14, regY: 24 },
animations: {
idle: { frames: [0,0], next: "walk"},
jump: { frames: [4,5], next: "walk"},
walk: [0, 8]
}
};
this.spriteSheet = new createjs.SpriteSheet(this.data);
this.animation = new createjs.Sprite(this.spriteSheet, "walk");
this.animation.x = x;
this.animation.y = y;
stage.addChild(this.animation);
}
Lorn.prototype.hasFireBalls = function () {
return (this.fireballs > 0)
}
Lorn.prototype.shoot = function () {
this.fireballs--;
}
// return Lives, distance, score, fireballs, diamonds
Lorn.prototype.getPlayerStatus = function () {
var status = [""+this.lives, ""+this.coveredDistance , ""+this.score, ""+this.fireballs, ""+this.diamonds];
return status;
}
Lorn.prototype.toString = function () {
var status = this.getPlayerStatus();
return String.format("\nLIVES: \t\t\t\t{0}\n\nFIREBALLS: {1}\n\nSCORE: \t\t\t\t{2}\n\nDIAMONDS: \t{3}\n\nDISTANCE: \t{4}",status[0],status[3],status[2],status[4],status[1]);
}
Lorn.prototype.hitCat = function () {
this.score += HIT_CAT_SCORE;
}
// set lorn for jumping
Lorn.prototype.startJump = function () {
if(!this.jumping){
console.log("jump started");
this.velocityY = -13.0;
this.jumping = true;
}
}
// set end of jumping move
Lorn.prototype.endJump = function () {
console.log("jump ended");
if(this.velocityY < -5.0){
this.velocityY = -5.0;
}
}
// set lorn for moving to the left
Lorn.prototype.moveLeft = function (){
lorn.animation.scaleX = -1;
this.movingLeft = true;
}
// set lorn for moving to the right
Lorn.prototype.moveRight = function (){
lorn.animation.scaleX = 1;
this.movingRight = true;
}
// set end of left move
Lorn.prototype.stopMovingLeft = function () {
this.movingLeft = false;
}
// set end of right move
Lorn.prototype.stopMovingRight = function () {
this.movingRight = false;
}
// return sense based on sprite scaleX variable
Lorn.prototype.getSense = function (considerIdle) {
return (this.isIdle() && considerIdle) ? 0 : this.animation.scaleX;
}
// if lorn wasHitten, check lives and set hitten delay
Lorn.prototype.wasHitten = function (state){
if(this.lives-- > 0){
this.animation.alpha = 0.5;
this.hitten = true;
var _this = this;
setTimeout( function(){
_this.animation.alpha = 1.0;
_this.hitten = false;
console.log("back to the game with " + _this.lives + " lives.")
}, RECOVERING_TIME);
}else{
// state = Game.OVER;
}
}
// check if lorn is not momving
Lorn.prototype.isIdle = function (){
return (!this.movingLeft && !this.movingRight && !this.jumping);
}
Lorn.prototype.colectDiamond = function (){
this.diamonds++;
this.fireballs += 10;
}
Lorn.prototype.getTotalScore = function (){
return this.coveredDistance * 0.1 + this.score;
}
Lorn.prototype.update = function () {
// apply GRAVITY to vertical velocity
this.velocityY +=GRAVITY;
// set lorn vertical position based on velocity
this.animation.y += this.velocityY;
// check if lorn is back to the ground and ends jump arch
if(this.animation.y > GROUND_LEVEL - LORN_REG_Y){
this.animation.y = GROUND_LEVEL - LORN_REG_Y;
this.velocityY = 0.0;
this.jumping = false;
}
if(this.jumping)
this.animation.gotoAndPlay("jump");
// verify and calculate horizontal moves
if(this.movingLeft)
this.coveredDistance -= DISTANCE_PER_MOVE;
if(this.movingRight)
this.coveredDistance += DISTANCE_PER_MOVE;
if(this.isIdle())
this.animation.gotoAndPlay("idle");
}
return Lorn;
})();
```
|
0100101001/PyTestKSED
| "0100101001/PyTestKSED\n\ntest_SZ.py\n```#!/bin/sh\n#!/usr/bin/python3\n# -*- encoding=utf8 -*-\n\n\(...TRUNCATED)
|
010V/frontend-project1
|
010V/frontend-project1
README.md
```# frontend-project1
Group project 1
```
|
014248120/poytasaha
| "014248120/poytasaha\n\nFileIO.java\n```package ohtu.io;\n\nimport java.io.BufferedReader;\nimport j(...TRUNCATED)
|
01Eddie/nodejs_esenciales
| "01Eddie/nodejs_esenciales\n\nprofile.js\n```module.exports = function (app) {\n app.get('/profil(...TRUNCATED)
|
01rucha/TASK2
| "01rucha/TASK2\n\nscript.js\n```// XML HTTP request\r\n// step1: create an instance of xml http \r\n(...TRUNCATED)
|
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 1,737