Example #1
0
File: main.py Project: Zantyr/Varia
def main():
    global DEFAULTSCRIPT, ASKFORFILE, MODESELECT, DEFAULTMODE, doIWannaListen, doIWannaLocal
    Menu()
    if doIWannaListen:
        script.server()
    else:
        if ASKFORFILE: filename = raw_input("Gimme da filnaem, n***a: ")
        else: filename = DEFAULTSCRIPT
        if doIWannaLocal:
            script.functions["!zapytaj"] = script.localGet
            script.functions["!wyjeb"] = script.localOut
            with open(filename, "r") as f**k:
                sendable = f**k.read()
            script.run(script.parseFile(sendable))
        else:
            Lnr = connect.createClient()
            with open(filename, "r") as f**k:
                sendable = f**k.read()
                connect.send(Lnr, sendable)
            print "\n\n>> File sent"
            while 1:
                data = connect.listen(Lnr)
                if (data == "CLOSE"): break
                if (data): script.localRun(Lnr, data)
                else: sleep(1)
            connect.shutdownListener(Lnr)
    return
Example #2
0
def server():
    Lnr = connect.createServer()
    sendable = "True"
    while (sendable):
        sendable = connect.listen(Lnr, 30)
        run(parseFile(sendable), Lnr)
    shutdownListener(Lnr)
Example #3
0
def insert_repository():
    if request.method == "POST":
        try:
            if not "owner" in request.json:
                return jsonify({
                    "error":
                    "É necessário que seja informado no body o dono do repositório a ser inserido!"
                })
            if not "repository" in request.json:
                return jsonify({
                    "error":
                    "É necessário que seja informado no body o nome do repositório a ser inserido!"
                })
            # if not "tokens" in request.json:
            #     return jsonify({
            #         "error": "É necessário que seja informada no body uma lista de tokens para correta execução da ferramenta!"
            #     })

            owner = request.json["owner"]
            repository = request.json["repository"]
            # tokens = request.json["tokens"]
            run(owner, repository)
            return jsonify({"success": True})
        except Exception as e:
            return jsonify({"error": e})
Example #4
0
def initiation():
    if (init == "Y"):
        run()
    elif (init == "N"):
        quit()
    else:
        print("Please enter either \'Y\' or \'N\'")
Example #5
0
def on_paint(cr):
    if client.width_mm == 0 or client.height_mm == 0:
        print("Wayland reports bogus monitor dimensions!")
        scale = Point(1, 1)
    else:
        scale = Point(client.width_pixels / client.width_mm,
                      client.height_pixels / client.height_mm)
    script.run(cr, scale, window)
Example #6
0
def form_post():
    #https://stackoverflow.com/questions/12277933/send-data-from-a-textbox-into-flask
    journal = request.form['journal'].upper()
    num_articles = request.form['num_articles']

    if pars.valid(journal, num_articles):
        script.run(journal, num_articles)
    else:
        return render_template('input_error.html')

    return "Complete!"
def test_create_update_delete():
    source_grafana_url = 'http://source_grafana/'
    target_grafana_url = 'http://target_grafana/'
    script.SOURCE_GRAFANA_URL = source_grafana_url
    script.TARGET_GRAFANA_URL = target_grafana_url

    responses.add(responses.GET,
                  url=f'{source_grafana_url}/api/alert-notifications',
                  status=200,
                  json=SOURCE_GRAFANA_RESPONSE)
    responses.add(responses.GET,
                  url=f'{target_grafana_url}/api/alert-notifications',
                  status=200,
                  json=TARGET_GRAFANA_RESPONSE)
    responses.add(
        responses.DELETE,
        url=
        f'{target_grafana_url}/api/alert-notifications/uid/some-uid-that-needs-to-be-deleted',
        status=200)
    responses.add(
        responses.PUT,
        f'{target_grafana_url}/api/alert-notifications/uid/some-uid-that-needs-to-be-updated',
        status=201)
    responses.add(responses.POST,
                  url=f'{target_grafana_url}/api/alert-notifications',
                  status=200)
    script.run()

    def get_request_by_url_and_method(url: str, method: str):
        for call in responses.calls:
            if call.request.method == method and call.request.url == url:
                return call
        return None

    update_call = get_request_by_url_and_method(
        f'{target_grafana_url}/api/alert-notifications/uid/some-uid-that-needs-to-be-updated',
        'PUT')
    assert update_call != None

    delete_call = get_request_by_url_and_method(
        f'{target_grafana_url}/api/alert-notifications/uid/some-uid-that-needs-to-be-deleted',
        'DELETE')
    assert delete_call != None

    # note this this test case contains a single create call
    create_call = get_request_by_url_and_method(
        f'{target_grafana_url}/api/alert-notifications', 'POST')
    assert create_call != None
    create_call_body = json.loads(create_call.request.body)
    assert create_call_body['uid'] == 'some-uid-in-source'
Example #8
0
def main():
    import time
    x = time.time()
    epsilon = 0.0000001
    num_experiments = 20

    # CartPole args
    cartpole_env = 'CartPole-v1'
    cartpole_state_space = list(range(8 * 8 * 10 * 10))
    cartpole_discretization = Discretization(cartpole_state_space, [
        np.linspace(-2.6 - epsilon, 2.6, 9, True),
        np.linspace(-5.0, 5.0, 9, True),
        np.linspace(-0.42, 0.42, 11, True),
        np.linspace(-4.01, 4.01, 11, True)
    ])
    cartpole_alpha = 0.1
    cartpole_gamma = 0.99
    cartpole_init_Q = 25
    cartpole_temperature = 2
    cartpole_num_episodes = 2000
    cartpole_num_test_episodes = 100

    # Run CartPole experiment
    rewards, q_tables, test_rewards = run(
        pool, cartpole_env, cartpole_state_space, cartpole_discretization,
        cartpole_alpha, cartpole_gamma, cartpole_init_Q, cartpole_temperature,
        cartpole_num_episodes, cartpole_num_test_episodes, num_experiments)

    print("Time", time.time() - x)

    np.savez_compressed("cp_rewards.npz", **rewards)
    np.savez_compressed("cp_qvalues.npz", **q_tables)
    np.savez_compressed("cp_test_rewards.npz", **test_rewards)
Example #9
0
def main():
    import time
    x = time.time()
    epsilon = 0.0000001
    num_experiments = 20

    # LunarLander args
    lunar_env = 'LunarLander-v2'
    lunar_state_space = list(range(4**6 * 4))

    # First 6 variables are continuous, discretized into four bins, and last two are binary 0, 1
    lunar_discretization = Discretization(
        lunar_state_space,
        [np.array([-np.inf, -0.5, 0, 0.5, np.inf])
         for i in range(6)] + [np.array([-0.1, 0.1, 1.5]) for i in range(2)])

    lunar_alpha = 0.1
    lunar_gamma = 0.99
    lunar_init_Q = 0
    lunar_temperature = 1.5
    lunar_num_episodes = 10000
    lunar_num_test_episodes = 1000

    # Run LunarLander experiment
    rewards, q_tables, test_rewards = run(
        pool, lunar_env, lunar_state_space, lunar_discretization, lunar_alpha,
        lunar_gamma, lunar_init_Q, lunar_temperature, lunar_num_episodes,
        lunar_num_test_episodes, num_experiments)

    print("Time", time.time() - x)

    np.savez_compressed("ll_rewards.npz", **rewards)
    np.savez_compressed("ll_qvalues.npz", **q_tables)
    np.savez_compressed("ll_test_rewards.npz", **test_rewards)
Example #10
0
def main():
    import time
    x = time.time()
    epsilon = 0.0000001
    num_experiments = 20

    # Mountain car args
    mc_env = 'MountainCar-v0'
    mc_state_space = list(range(40 * 40))
    mc_discretization = Discretization(mc_state_space, [
        np.linspace(-1.2 - epsilon, 0.6, num=41, endpoint=True),
        np.linspace(-0.07 - epsilon, 0.07, num=41, endpoint=True)
    ])
    mc_alpha = 0.01
    mc_gamma = 0.99
    mc_init_Q = -50
    mc_temperature = 1
    mc_num_episodes = 10000
    mc_num_test_episodes = 1000

    # Run Mountain Car experiment
    rewards, q_tables, test_rewards = run(pool, mc_env, mc_state_space,
                                          mc_discretization, mc_alpha,
                                          mc_gamma, mc_init_Q, mc_temperature,
                                          mc_num_episodes,
                                          mc_num_test_episodes,
                                          num_experiments)

    print("Time", time.time() - x)

    np.savez_compressed("mc_rewards.npz", **rewards)
    np.savez_compressed("mc_qvalues.npz", **q_tables)
    np.savez_compressed("mc_test_rewards.npz", **test_rewards)
Example #11
0
def insert_repository():
    if request.method == "POST":
        try:
            if not "owner" in request.json:
                return jsonify({
                    "error":
                    "É necessário que seja informado no body o dono do repositório a ser inserido!"
                })
            if not "repository" in request.json:
                return jsonify({
                    "error":
                    "É necessário que seja informado no body o nome do repositório a ser inserido!"
                })

            owner = request.json["owner"]
            repository = request.json["repository"]
            run(owner, repository)
            return jsonify({"success": True})
        except Exception as e:
            return jsonify({"error": str(e)})
Example #12
0
def lambda_handler(event, context):
    """Sample pure Lambda function

    Parameters
    ----------
    event: dict, required
        API Gateway Lambda Proxy Input Format

        Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format

    context: object, required
        Lambda Context runtime methods and attributes

        Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html

    Returns
    ------
    API Gateway Lambda Proxy Output Format: dict

        Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
    """

    # try:
    #     ip = requests.get("http://checkip.amazonaws.com/")
    # except requests.RequestException as e:
    #     # Send some context about this error to Lambda Logs
    #     print(e)

    #     raise e

    try:
        result = run()
    except Exception as e:
        print(e)
        raise

    return {
        "statusCode": 200,
        "body": json.dumps({
            "message": "xambda works",
            "result": result,
        }),
    }
Example #13
0
def main():
    import time
    x = time.time()
    epsilon = 0.0000001
    num_experiments = 20

    # Acrobot args
    ac_env = 'Acrobot-v1'
    ac_state_space = list(range(10 * 10 * 10 * 10 * 8 * 8))
    ac_discretization = Discretization(ac_state_space, [
        np.linspace(-1 - epsilon, 1, 11, True),
        np.linspace(-1 - epsilon, 1, 11, True),
        np.linspace(-1 - epsilon, 1, 11, True),
        np.linspace(-1 - epsilon, 1, 11, True),
        np.linspace(-12.566371 - epsilon, 12.566371, 9, True),
        np.linspace(-28.274334 - epsilon, 28.274334, 9, True)
    ])
    ac_alpha = 0.25
    ac_gamma = 0.999
    ac_init_Q = 0
    ac_temperature = 1
    ac_num_episodes = 100000
    ac_num_test_episodes = 10000

    # Run Acrobot experiment
    rewards, q_tables, test_rewards = run(pool, ac_env, ac_state_space,
                                          ac_discretization, ac_alpha,
                                          ac_gamma, ac_init_Q, ac_temperature,
                                          ac_num_episodes,
                                          ac_num_test_episodes,
                                          num_experiments)

    print("Time", time.time() - x)

    np.savez_compressed("ac_rewards.npz", **rewards)
    np.savez_compressed("ac_qvalues.npz", **q_tables)
    np.savez_compressed("ac_test_rewards.npz", **test_rewards)
Example #14
0
def index():
    values = request.args
    agent = str(request.user_agent)
    if 'group' not in values or 'step' not in values:
        #add_history(u'Start Page// ' + agent)
        return render_template('index.html')
    if (not 'key' in values) or (values['key'] == ''):
        if 'lone' in str(values['group']) or 'givenchystyle' in str(
                values['group']):
            key = '1985'
        else:
            return jsonify({'error': 'The personal key isn\'t given'})
    else:
        key = str(values['key'])
    if not key in get_keys():
        return jsonify({'error': 'The key doesn\'t exist'})
    step = int(values['step'])
    screen_name = str(values['group'])
    if 'full' in values and int(values['full']) == 1:
        full = True
    else:
        full = False
    if 'extra' in values and int(values['extra']) == 1:
        extra = True
    else:
        extra = False
    add_history(
        u'Request. step:{}, screen_name:{}, full:{}, key:{}, extra:{} // '.
        format(*[str(n) for n in [step, screen_name, full, key, extra]]))
    #try:
    instas = run(step, screen_name, full=full, extra_data=extra)
    #except KeyError:
    #    return jsonify({'error': 'Invalid datas'})
    if instas == 'Out of range':
        return jsonify({'error': 'Out of range'})
    dic = {'count': len(instas), 'items': instas}
    return jsonify(dic)
def runcmd(command):
    # Find a space. If one is found, put it in another variable.
    args = command.find(" ", 0, len(command))
    argsArr = ['']

    # Counters
    i = 0
    j = 0
    k = 0
    flag = 0
    flag2 = 0

    # Only do it if there is indeed a space
    if (args != -1):
        for i in command:
            # Only do this after a space
            if (j > args):

                # If the character is \, set a flag and remove the \. If not, turn off the flag
                if (i == "\\"):
                    flag = 1
                    if (i == "\\"):
                        continue

                # If we come across a space, add an item to the array of arguments and skip the rest,
                # unless the flag set before is set
                if ((i == " ") and (flag == 0)):
                    k += 1
                    argsArr.append("")
                    continue
                elif ((i == " " and (flag == 1))):
                    flag = 0

                # Take the current item in the args array and put in each character of the input
                # string, then delete that same character from the input string
                argsArr[k] = argsArr[k] + i
                command = command[0:j:]
            else:
                j += 1
    # Reset the counters
    i = 0
    j = 0
    k = 0

    # If we have at least 1 space, make sure you take out the last character
    # in the command variable that happens to be a space
    if (args != -1):
        command = command[:-1:]

    # If the value set in the system variable "varTrans" is set to true, then replace all
    # variables with their values. First, make sure it exists.
    varTrans = systemvariables.read("varTrans")
    j = 0
    l = 0
    i = 0
    if (varTrans != -1):
        if (varTrans == 1):
            for i in argsArr:
                var = 0
                varNam = ""
                k = ""
                for k in argsArr[j]:
                    # If this is the first character and it is a $, we are setting up to look
                    # at a possible variable.
                    if ((l == 0) and (k == "$")):
                        var = 1
                        l += 1
                        continue
                    if ((l >= 0) and (var != 1)):
                        break
                    else:
                        varNam = varNam + k
                # Check to make sure the variable called for exists. If it does, set this argument
                # to be the value in the variable.
                if (systemvariables.read(varNam) != -1):
                    argsArr[j] = systemvariables.read(varNam)
                j += 1

    # Commands
    if (command == "exit"):
        os.chdir(systemvariables.read("tmppath"))
        conts = ls.list()
        for i in conts:
            try:
                if (os.path.isfile(i) == True):
                    os.remove(i)
                elif (os.path.isdir(i) == True):
                    shutil.rmtree(i)
                else:
                    continue
            except Exception as e:
                print(
                    "Bash for Windows has run into a non-critical issue: TMP_DEL_ERR\nThe Error message is:\
\n" + str(e), "\nThis occured while deleting file", i,
                    "in the temp directory.\nPress Enter to Continue...")
                input("")
                continue
        print("Goodbye!")
        exit(0)
    elif (command == "ls"):
        ls.show(argsArr)
    elif (command == "cd"):
        cd.go(argsArr)
    elif (command == "pwd"):
        tofile.write(argsArr, os.getcwd())
    elif (command == "cat"):
        cat.show(argsArr)
    elif (command == "nano"):
        file = argsArr
        nano.write(file)
    elif (command == "vi"):
        file = argsArr
        nano.write(file)
    elif (command == "vim"):
        file = argsArr
        nano.write(file)
    elif (command == "emacs"):
        file = argsArr
        nano.write(file)
    elif (command == "clear"):
        os.system("cls")
    elif (command == "lsvar"):
        ls.vars(argsArr)
    elif (command == "echo"):
        echo.reg(argsArr)
    elif (command == "touch"):
        touch.write(argsArr)
    elif (command == "rm"):
        rm.remove(argsArr)
    elif (command == "mv"):
        file = argsArr[0]
        dstfile = argsArr[1]
        mv.move(file, dstfile)
    elif (command == "cp"):
        cp.copy(argsArr)
    elif (command == "pushd"):
        path = argsArr
        pushd.go(path)
    elif (command == "popd"):
        popd.go()
    elif (command == "uname"):
        uname.list(argsArr)
    elif (command == "mkdir"):
        mkdir.create(argsArr)
    elif (command == "date"):
        date.show(argsArr)
    elif (command == "restart"):
        # Debug Message
        if (systemvariables.read("debugMsg") == 1):
            print(systemvariables.color.YELLOW + systemvariables.color.BOLD +
                  "[Debug]" + systemvariables.color.END + " Bash: Restarting!")

        # Save current directory
        cwd = os.getcwd()
        os.chdir(systemvariables.read("tmppath"))
        file = open("lastcwd.bws", "w")
        file.write(str(cwd))
        file.close()
        systemvariables.modifyVoid("restart", 1)
        return 0
    else:
        if (argsArr[0] == "="):
            if (systemvariables.lookupIndex(command) == -1):
                systemvariables.init(command, argsArr[1])
            else:
                systemvariables.modifyVoid(command, argsArr[1])
        else:
            dirContents = ls.list()
            if (command == ""):
                sleep(0)
            elif (command in dirContents):
                if (".bwsh" in command):
                    if (os.path.exists(command) == True):
                        scriptContents = open(command, "r")
                        script.run(str(scriptContents.read()))
                        scriptContents.close()
                    else:
                        print(command + ": command not found")
                else:
                    print(command + ": command not found")
            else:
                print(command + ": command not found")
Example #16
0
# -*- coding: utf-8 -*-
# GNU General Public License v2.0 (see COPYING or https://www.gnu.org/licenses/gpl-2.0.txt)
"""This is the UpNext script entry point"""

from __future__ import absolute_import, division, unicode_literals
import sys
import script

script.run(sys.argv)
Example #17
0
import script
import body

def read_orientation():
    while(True):
        orientation = body.readOrientation()
        print(orientation)

if __name__ == '__main__':
    script.run(read_orientation)

Example #18
0
from script import run
import sys
from display import clear_images

if len(sys.argv) == 2:
    sys.argv[1] = "files/" + sys.argv[1]
    clear_images()
    run(sys.argv[1])
    # print ("Please enter a valid file type (obj, mdl, ASCII stl).")
elif len(sys.argv) == 1:
    run(raw_input("Please enter the filename of a valid script file: \n"))
else:
    print("Too many arguments.")
Example #19
0
import script

if __name__ == "__main__":
    script.run()
Example #20
0
 def run_script(self, script, sprite):
     """Runs a script, and queues it up to run again if needs be"""
     script.run(sprite)
     if script.starts_on_trigger():
         self.queue(script.from_start(), sprite)
Example #21
0
import sys
import script
epochs=sys.argv[1]
script.preprocess()
script.run(int(epochs))
Example #22
0
from script import run
import sys

if len(sys.argv) == 2:
    run(sys.argv[1])
elif len(sys.argv) == 1:
    run(raw_input("please enter the filename of an mdl script file: \n"))
else:
    print "Too many arguments."
Example #23
0
from script import run
import sys

if len(sys.argv) == 2:
    run(sys.argv[1])
elif len(sys.argv) == 1:
    run(raw_input("enter mdl file name: \n"))
else:
    print "Too many arguments."
from script import run, mesh_file
import sys

if len(sys.argv) == 2:
    if len(sys.argv[1].split('.')) == 1:
        print "Please enter a file with an extension"
    else:
        if sys.argv[1].split(".")[1] == 'mdl':
            run(sys.argv[1])
        elif sys.argv[1].split(".")[1] == 'obj':
            print "Mesh file"
            print "Meshing file..."
            mesh_file(sys.argv[1])
        else:
            print "Unrecognized file format"
        
elif len(sys.argv) == 1:
    run(raw_input("Please enter the filename of a file: \n"))
else:
    print "Too many arguments."
Example #25
0
from script import run
import sys

if len(sys.argv) == 2:
    run(sys.argv[1])
elif len(sys.argv) == 1:
    run(raw_input("please enter the filename of an mdl script file: \n"))
else:
    print("Too many arguments.")
Example #26
0
#     def handle_inv(self, message_header, message):
#         print("Handling inv")
#         getdata = messages.GetData()
#         getdata.inventory = message.inventory
#         self.send_message(getdata)

#     def handle_message_header(self, message_header, payload):
#         print("<- %s" % message_header)

#     def handle_send_message(self, message_header, message):
#         print("-> %s" % message_header)

print("1. Fetching addresses...")
# AddressBook.bootstrap()
# AddressBook.keep_updated()
print("   Got %s initial addresses." % len(AddressBook.addresses))

print("2. Synchronizing all blocks...")
# Synchronizer.synchronize()

print("3. Done!")

from script import run

run()

# while True:
#     client = BTCClient(random.choice(seed_addresses), coin='bitcoin_testnet3')
#     client.handshake()
#     client.loop()
Example #27
0
from script import run

result = run()
print(result)
Example #28
0
# -*- coding: utf-8 -*-
# GNU General Public License v2.0 (see COPYING or https://www.gnu.org/licenses/gpl-2.0.txt)
''' This is the Up Next script entry point '''

from __future__ import absolute_import, division, unicode_literals
from sys import argv
from script import run

run(argv)
Example #29
0
#         print("Handling inv")
#         getdata = messages.GetData()
#         getdata.inventory = message.inventory
#         self.send_message(getdata)

#     def handle_message_header(self, message_header, payload):
#         print("<- %s" % message_header)

#     def handle_send_message(self, message_header, message):
#         print("-> %s" % message_header)

print("1. Fetching addresses...")
# AddressBook.bootstrap()
# AddressBook.keep_updated()
print("   Got %s initial addresses." % len(AddressBook.addresses))

print("2. Synchronizing all blocks...")
# Synchronizer.synchronize()

print("3. Done!")

from script import run
run()



# while True:
#     client = BTCClient(random.choice(seed_addresses), coin='bitcoin_testnet3')
#     client.handshake()
#     client.loop()
Example #30
0
import json

from pathlib import Path
from script import run

with open(Path(__file__).parent.parent / 'input' / 'test_event.json') as f:
    event = json.load(f)
result = run(event, {})
print(result)
Example #31
0
from script import run, mesh_file
import sys

if len(sys.argv) == 2:
    if len(sys.argv[1].split('.')) == 1:
        print "Please enter a file with an extension"
    else:
        if sys.argv[1].split(".")[1] == 'mdl':
            run(sys.argv[1])
        elif sys.argv[1].split(".")[1] == 'obj':
            print "Mesh file"
            print "Meshing file..."
            mesh_file(sys.argv[1])
        else:
            print "Unrecognized file format"

elif len(sys.argv) == 1:
    run(raw_input("Please enter the filename of a file: \n"))
else:
    print "Too many arguments."
Example #32
0
def send(s):
    # monkeypatch to make send/sendline go to tmux
    global p
    s = p._coerce_send_string(s)
    b = p._encoder.encode(s, final=False)
    return tmux_send_keys(prep_string(b))


tmux_info = TmuxInfo(session=sys.argv[1], window=sys.argv[2], pane=sys.argv[3])

s = "Listening in this pane. Target: session: %s, window: %s, pane: %s (%s)" % \
        (tmux_info.session, tmux_info.window, tmux_info.pane, tmux_info)

print(s)
tmux_display_msg(s)

p = fdpexpect.fdspawn(sys.stdin)
# monkeypatch
p.send = send

# aux monkeypatch, enable feedback from the script
p.tmux_display_msg = tmux_display_msg

# Run the script
import script
while script.run(p):
    pass

p.close()
print("Bye")
Example #33
0
    body.reset()
    
    for i in range(0,2):

        sleep(0.2)

        body.moveBy(body.SE1, -10)
        body.moveBy(body.SE2, 10)

        body.moveBy(body.NE1, 20)
        body.moveBy(body.NE2, -10)

        sleep(0.4)

        body.moveBy(body.SW1, -20)
        body.moveBy(body.SW2, 20)

        body.moveBy(body.NW1, 30)
        body.moveBy(body.NW2, -20)

        body.moveBy(body.SE1, -10)
        body.moveBy(body.SE2, 10)

        sleep(0.4)

        body.reset()


if __name__ == '__main__':
    script.run(simple_walking)