コード例 #1
0
    def exec(self, sym, data5min, ex1: Exchange, ord_log=None, strat_log=None):

        # print(data5min)
        # print("-----")
        # print(data1hour)
        # print("-------------------------")

        self.symbol = sym
        self.ex1 = ex1
        # print(str((float(data5min.iloc[101]['t1']))))
        if (len(data5min) == 252) and ((float(data5min.iloc[251]['t1']) -
                                        float(data5min.iloc[0]['t1']))
                                       == 251 * 5 * 60 * 1000):
            last_ts = float(data5min.iloc[251]['t1'])
            tsorder = util.Util().get_5min_order(last_ts)
            # print(str(tsorder))
            # if tsorder == float(1):
            if False:
                print("not checking 1st hour candle in 1 hour timeframe")
            else:
                # print("data ok")
                datac = n3data.Data()
                self.data = data5min
                self.datah = datac.geth(self.data)

                self.currentts = float(data5min.iloc[251]['t1'])
                #     print(data5min)
                #     self.ts = data5min.iloc[100]['t1']
                #     self.lasto = data5min.iloc[100]['open']
                #     self.lasth = data5min.iloc[100]['high']
                #     self.lastl = data5min.iloc[100]['low']
                self.lastc = data5min.iloc[251]['close']
                # # self.candles = "["+str(self.ts)+","+str(self.lasto)+","+str(self.lasth)+","+str(self.lastl)+","+str(self.lastc)+"]"
                #     self.candle = []
                #     self.candle.append(self.ts)
                #     self.candle.append(self.lasto)
                #     self.candle.append(self.lasth)
                #     self.candle.append(self.lastl)
                #     self.candle.append(self.lastc)

                self.symbol = sym.upper()
                # datac = data.Data()
                self.data = data5min
                # self.datah = datac.geth(self.data)
                # self.datah = self.datah.reindex(index=self.datah.index[::-1])

                # self.cch = data1hour['trend_cci']
                # self.cc5l = 0
                # self.cc5n = 0
                # self.ccbb = 0
                # self.cc5h = 0
                # self.ex = exch

                self.ord_log = ord_log
                self.strat_log = strat_log
                self.ta()
                self.decide()
                self.update_positions()
        else:
            print("data corrupt ..." + self.symbol)
コード例 #2
0
def generate(fontName, pointSize=12):
    pilFontFallback = ImageFont.truetype(util.fontFallback, pointSize)
    pilFont = ImageFont.truetype(fontName, pointSize)

    Util = util.Util(fontName, pointSize)

    # Range is exclusive, so + 1
    maxGridSize = round(Util.getTextWidth(9608))
    lineHeight = int(16.5)  # 22

    if not exists("img/"):
        mkdir("img")

    for c in range(0, 129995):
        size = Util.getTextWidth(c)
        ch = chr(c)
        if size is None or size > maxGridSize or combining(ch) or isRTL(ch):
            continue

        image = Image.new("L", (maxGridSize, lineHeight), (0))
        draw = ImageDraw.Draw(image)

        draw.text((0, 0),
                  ch,
                  font=(pilFont if c in Util.t and Util.t[c] in Util.s else
                        pilFontFallback),
                  fill=(255))

        bbox = image.getbbox()
        if not bbox:  # Image is empty
            continue

        image.save("img/{}.png".format(c))
        image.close()
コード例 #3
0
 def __init__(self, layer, n_input, n_output):
     self.util = u.Util()
     self.sess = tf.Session()
     self.layer = layer  # zero means random!
     self.n_input = n_input
     self.n_output = n_output
     self.train_step = self.layer_set()
コード例 #4
0
def main():
    u = util.Util()
    a = app.App()
    creds_b64 = a.get_creds("creds.json")
    plaintext_sudo_password = u.b64_decrypt(creds_b64["sudo_password"])
    plaintext_ssh_user = u.b64_decrypt(creds_b64["ssh_user"])
    plaintext_ssh_password = u.b64_decrypt(creds_b64["ssh_password"])
    all_cmds = a.get_array_cmd("cmds.json", plaintext_sudo_password)

    # File with IPs
    serv_lst = "srv.txt"

    # Open IP file
    with open(serv_lst, "r") as f:
        text = f.readlines()

    # for-loop for IP list
    for lineHost in text:
        lineHost = lineHost.replace("\n", "")

        # Connect SSH
        print("[+]Connecting Addr::" + lineHost)

        for c_cmd in all_cmds:
            ret = conn_ssh(lineHost, plaintext_ssh_user,
                           plaintext_ssh_password, c_cmd)

            with open("log.log", "a", encoding="utf-8") as fp:
                all_output = ret["stdout"] + ret["stderr"]
                fp.write(all_output)
                fp.close()

        print("SOC Output Results")
コード例 #5
0
ファイル: req_update.py プロジェクト: albertyw/req-update
 def __init__(self) -> None:
     self.install = False
     self.updated_files: Set[str] = set([])
     self.util = util.Util()
     self.python = python.Python()
     self.python.util = self.util
     self.node = node.Node()
     self.node.util = self.util
コード例 #6
0
ファイル: main.py プロジェクト: oPensyLar/pyvmomi-scripts
def get_config():
    a = app.App()
    utils = util.Util()
    config = a.get_creds("config.json")
    ip = config["ip"]
    esxi_dns_hostname = dns_resolver(ip)
    usr = utils.b64_decrypt(config["usr"])
    pwd = utils.b64_decrypt(config["passwd"])

    return {"server_ip":  ip, "server_dns_name": esxi_dns_hostname, "user_name": usr, "user_password": pwd}
コード例 #7
0
ファイル: util_test.py プロジェクト: wert23239/SmashBot
 def test_util_convert(self):
     utils=util.Util(logger=None)
     expected=0
     for i in range(len(utils.button_list)):
         for j in range(len(utils.y_list)):
             for k in range(len(utils.x_list)):
                 result = (
                     utils.convert_attack(utils.x_list[k],utils.y_list[j],utils.button_list[i]))
                 self.assertEqual(result, expected)
                 expected+=1    
コード例 #8
0
ファイル: util_test.py プロジェクト: wert23239/SmashBot
 def test_preprocess_rows_size(self):
     utils=util.Util(logger=None)
     reward_row=self.create_fake_row()
     reward_row["AI_Stock_Change"]=-1
     rows = [self.create_fake_row(),self.create_fake_row(),self.create_fake_row(),reward_row]
     Y_train,X_train,action_train=utils.preprocess_rows(rows)
     self.assertEqual(3,len(Y_train))
     self.assertEqual(Y_train[0],-.99**2)
     self.assertEqual(Y_train[1],-.99)
     self.assertEqual(Y_train[2],-1)
     self.assertEqual(len(X_train[0]),17)
コード例 #9
0
ファイル: util_test.py プロジェクト: wert23239/SmashBot
 def test_util_unconvert(self):
     utils=util.Util(logger=None)
     x_cord,y_cord,button_choice=utils.unconvert_attack(4)
     self.assertEqual(x_cord,1)
     self.assertEqual(y_cord,0)
     self.assertEqual(button_choice,None)
     x_cord,y_cord,button_choice=utils.unconvert_attack(5)
     self.assertEqual(x_cord,0)
     self.assertEqual(y_cord,.25)
     self.assertEqual(button_choice,None)
     x_cord,y_cord,button_choice=utils.unconvert_attack(26)
     self.assertEqual(x_cord,.25)
     self.assertEqual(y_cord,0)
     self.assertEqual(button_choice,melee.Button.BUTTON_B)  
コード例 #10
0
    def setUp(self):
        desired_caps = {}
        desired_caps['platformName'] = 'Android'
        desired_caps['platformVersion'] = Result["Androidversion"]
        desired_caps['deviceName'] = Result["SerialNo"]
        desired_caps['appPackage'] = el.Package['appPackage']
        desired_caps['appActivity'] = el.Package['appActivity']

        self.driver = webdriver.Remote('http://localhost:4723/wd/hub',
                                       desired_caps)
        self.pgutil = ul.Util(
            self.driver,
            parentFolder + "/screenshots/" + str(time.strftime("%Y%m%d")))
        self.pgmodule = module.Module(
            self.driver,
            parentFolder + "/screenshots/" + str(time.strftime("%Y%m%d")))
コード例 #11
0
    def geth(self,dfi)-> pandas.DataFrame:
        # print(len(dfi))
        dfi = dfi.reindex(index=dfi.index[::-1])
        dfh = pandas.DataFrame(columns=["t1", "open", "high", "low", "close"])
        # print(dfi.iloc[0]['t1'])
        # print(dfi.iloc[251]['t1'])
        lenn = len(dfi)-1
        if (float(dfi.iloc[0]['t1']) == float(dfi.iloc[lenn]['t1']+lenn*300000)):
            # print("data is approved")
            ut = util.Util()
            over = ut.get_5min_order(dfi.iloc[0]['t1'])
            # print(over)

            ind=int(over)
            # print(dfi.loc[ind])
            i=0
            j=i+20
            ii=0


            while i<j:
                # bla bla

                dfh.at[ii, 't1'] = dfi.iloc[i*12+ind]['t1']
                dfh.at[ii, 'open'] = dfi.iloc[i * 12+11+ind]['open']
                dfh.at[ii, 'close'] = dfi.iloc[i * 12+ind]['close']
                dfh.at[ii, 'high'] = max([dfi.iloc[i * 12+0+ind]['high'], dfi.iloc[i * 12+1+ind]['high'],
                                        dfi.iloc[i * 12+2+ind]['high'], dfi.iloc[i * 12+3+ind]['high'],
                                        dfi.iloc[i * 12+4+ind]['high'], dfi.iloc[i * 12+5+ind]['high'],
                                        dfi.iloc[i * 12+6+ind]['high'], dfi.iloc[i * 12+7+ind]['high'],
                                        dfi.iloc[i * 12+8+ind]['high'], dfi.iloc[i * 12+9+ind]['high'],
                                        dfi.iloc[i * 12+10+ind]['high'], dfi.iloc[i * 12+11+ind]['high']])
                dfh.at[ii, 'low'] = min([dfi.iloc[i * 12 + 0+ind]['low'], dfi.iloc[i * 12 + 1+ind]['low'],
                                        dfi.iloc[i * 12 + 2+ind]['low'], dfi.iloc[i * 12 + 3+ind]['low'],
                                        dfi.iloc[i * 12 + 4+ind]['low'], dfi.iloc[i * 12 + 5+ind]['low'],
                                        dfi.iloc[i * 12 + 6+ind]['low'], dfi.iloc[i * 12 + 7+ind]['low'],
                                        dfi.iloc[i * 12 + 8+ind]['low'], dfi.iloc[i * 12 + 9+ind]['low'],
                                        dfi.iloc[i * 12 + 10+ind]['low'], dfi.iloc[i * 12 + 11+ind]['low']])

                i += 1
                ii+=1
            dfh = dfh.reindex(index=dfh.index[::-1])
            # print (dfh)
        else:
            print("data corrupt for : ", dfi)
        return dfh
コード例 #12
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-t",
                        action="store",
                        dest="t_p",
                        type=str,
                        help="Test path")
    parser.add_argument("-f",
                        action="store_true",
                        dest="f_d",
                        default=False,
                        help="Force detection")
    args = vars(parser.parse_args())
    test_path = args["t_p"]

    if test_path == "":
        print("No test path given!")
        return

    kpt_file_path = os.path.join(test_path, "kpt.txt")
    kpt_file_exists = os.path.isfile(kpt_file_path)
    force_detection = args["f_d"]
    img_format = "jpeg"

    ut = util.Util(test_path, roi=300, image_format=img_format)
    if not kpt_file_exists or force_detection:

        ut.processImage()

        demo.PRNet(test_path)

        shutil.rmtree(os.path.join(test_path, "temp"))

    ut.readKPT()
    head_pose = pose.Pose(test_path)
    head_pose.regress(curve=3)
コード例 #13
0
ファイル: main.py プロジェクト: RobT00/CS7CS4_Group
def run(training, threshold, model_arg, model_save=False, **kwargs):
    """
    Main function used to process data, create models and output predictions
    :param training: Boolean, if the model is being trained or being used to test output
    :param threshold: Threshold to be used for regression to classification predictions
    :param model_arg: Path to a pre-trained model
    :param model_save: Boolean to save trained model(s)
    :return:
    """
    data_man = util.Util(FILES)

    file_path = os.path.realpath(__file__)
    script_dir = os.path.dirname(file_path)
    root_dir = os.path.dirname(script_dir)
    os.chdir(root_dir)
    data_dir = os.path.join(root_dir, "Data")

    tmp_dir = os.path.join(root_dir, "tmp")
    if os.path.exists(tmp_dir):
        shutil.rmtree(tmp_dir)
    os.makedirs(tmp_dir)

    trained_model = False
    try:
        model_class = data_man.get_model_from_string(model_arg)
        model_class = model_class(
            training=training)  # Instantiate the class instance
        model = (
            model_class.build()
        )  # Construct the model -> can extend to specify params here, if desired
    except AttributeError:
        print(f"Loading model: {model_arg}")
        model = data_man.load_model_from_path(os.path.join(
            data_dir, model_arg))
        print("Loaded model")
        if type(model) is dict:
            model_class = data_man.get_multi_model_class()
            model_class = model_class(training=training, is_base=True)
        else:
            model_class = data_man.get_base_model_class()
            model_class = model_class(
                training=training)  # Instantiate the base model class
        trained_model = True

    # Getting the data upfront
    training_file = data_man.copy_file(data_dir, "training", tmp_dir)
    training_data = data_man.get_data(training_file)
    test_file = data_man.copy_file(data_dir, "test", tmp_dir)
    test_data = data_man.get_data(test_file)

    # Need to get stats for target encoder on test data
    x, y, stats = model_class.process_training(
        training_data,
        is_training=True,
        is_regression=model_class.regression,
        other_df=test_data,
    )
    if not trained_model:
        if training:
            x_train, x_val, y_train, y_val = model_class.ready_training(x, y)
            # Testing SMOTE, a data reducing function for imbalanced datasets
            if not model_class.regression:
                x_train, y_train = model_class.resample_train_data(
                    x_train, y_train, **kwargs)
        else:
            if not model_class.regression:
                x, y = model_class.resample_train_data(x, y, **kwargs)

        # Use training data
        if training:
            model = model_class.train(model, x_train, y=y_train)
        else:
            model = model_class.train(model, x, y=y)

        # Save the trained model
        if model_save:
            os.chdir(data_dir)
            data_man.model_save(model, model_class.name)
            os.chdir(tmp_dir)

    if training:
        if trained_model:
            y_pred = model_class.predict(model, x, is_training=training)
            model_class.model_stats(y, y_pred, model_class.regression)
        else:
            y_val_pred = model_class.predict(model,
                                             x_val,
                                             is_training=training)
            model_class.model_stats(y_val,
                                    y_val_pred,
                                    regression=model_class.regression)
    else:
        # Output test predictions
        stats.update({
            "other_df": training_data
        })  # Could pass in as another arg, but this is more fun...
        x_test, stats = model_class.process_testing(test_data, stats)
        y_test_pred = model_class.predict(model, x_test, is_training=training)
        if model_class.regression:
            y_test_pred = data_man.regression_threshold(y_test_pred, threshold)

        data_man.write_predictions(test_data, y_test_pred.astype(int),
                                   test_file, data_dir, tmp_dir)

    os.chdir(script_dir)
コード例 #14
0
import util, transform
ut = util.Util()
tr = transform.Transform()


class Marching_Cubes_2d():
    def check_threshold(self, pts4, threshold):

        pts4_tf = []
        count = 0

        for i in range(4):

            if pts4[i] < threshold:
                pts4_tf.append(0)
            else:
                pts4_tf.append(1)
                count += 1

        return pts4_tf, count

    def line_one(self, p0, p1, p3):

        vector_s = tr.vector_amp(tr.vector_2pt(p0, p1), 0.5)
        vector_e = tr.vector_amp(tr.vector_2pt(p0, p3), 0.5)

        point_s = tr.point_move(p0, vector_s)
        point_e = tr.point_move(p0, vector_e)

        return [point_s, point_e]
コード例 #15
0
import json
import time
import util
import hashlib
import pymongo
from lib import mongo
from flask.ext.cors import CORS
from flask import Flask, request
from bson.objectid import ObjectId
from flask.ext.socketio import SocketIO, emit, send

app = Flask(__name__)
CORS(app)
app.config['SECRET_KEY'] = "Hardcoded Temporary Key"
socketio = SocketIO(app)
util = util.Util()

@app.route('/')
def index():
    return "index"

# Registers a new user and logs them in
@app.route("/register", methods=['POST'])
def register():
    user = request.form['user']
    passw = request.form['passw']
    if "details" in request.form:
        details = request.form['details']
        details = json.loads(details)
    else:
        details = False
コード例 #16
0
ファイル: module.py プロジェクト: koichipan/Practice
 def __init__(self, mDevice, dir):
     self.driver = mDevice
     self.util = util.Util(self.driver, dir)
コード例 #17
0
    config = ConfigParser.ConfigParser()
    config.read(config_file)
    if isinstance(config_tags, list):
        config_data = {k: config.get(section, k) for k in config_tags}
    else:
        config_data = {config_tags: config.get(section, config_tags)}
    return config_data


if __name__ == "__main__":

    # Init github client
    creds = get_from_config(configFile, "gh_client",
                            ["username", "oauth_token"])
    ghc = ghhelper.GithubClient(credentials=creds, ignoring_errors=True)
    util = util.Util(ghc)

    outputDir = util.commentsDir

    print "Loading Travis data..."
    td = util.load_travis_data(util.filteredTravisData)

    projectNames = td["gh_project_name"]
    projectNames = projectNames.drop_duplicates()
    projectNames = projectNames.sort_values()

    startTime = time.time()
    print "Fetching comments..."
    index = 0
    for label, prj in projectNames.iteritems():
コード例 #18
0
ファイル: main.py プロジェクト: aiscong/HungrySFBay
 def __init__(self, un, ps):
     self.username = un
     self.password = ps
     self.util = util.Util()
     self.util.log_in(un, ps)
コード例 #19
0
ファイル: exe.py プロジェクト: azumag/gomoku-ai
#-*- coding: utf-8 -*-

import tensorflow as tf
import perceptron as nn
import util as u

#for i in range(1, 10):
n = nn.Perceptron(4, 81, 81)
n.load('./testsave/save.ckpt')
util = u.Util()
data_sample = util.load_data('../tmp/h-4v4')
result = n.execute(data_sample)

print result
print len(result)
コード例 #20
0
    def __init__(self, folder):
        '''        
        Calculates the roll, pitch yaw based on facial keypoints.
        
        Angles are calculate based on slope of the line between two keypoints chosen.
        Chosen Keypoints:
            Roll : outside points of the eyes
            Pitch :  point on jaw on either side
            Yaw: point on the lip and point lying on the center of the line passing through two points used for pitch
        
        Results saved into pose.txt file

        '''
        self.folder = folder
        ut = util.Util()
        keypoints = np.loadtxt(os.path.join(self.folder, "kp.txt"))
        pose = np.array([]).reshape(-1, 3)
        for k in range(keypoints.shape[1] // 3):
            kp = keypoints[:, k * 3:k * 3 + 3]

            ## ROll
            eye0 = kp[36]
            eye1 = kp[45]

            if eye0[0] == 1000:  ## If no keypoints
                euler = np.array([1000., 1000., 1000.]).reshape(-1, 3)
                pose = np.vstack([pose, euler])
                continue

            points = np.array([eye0, eye1])
            eyeCenter = ut.getCenter(points)

            kp_roll = kp - eyeCenter

            eye0 = kp_roll[36]
            eye1 = kp_roll[45]
            points = np.array([eye0, eye1])
            eyeDist = ut.getDist(points, type_="roll")

            x = eyeDist / 2

            eye0_x = x * (abs(eye0[0]) / eye0[0])
            eye0_y = eye0[1]
            eye0_z = 0.

            eye1_x = x * (abs(eye1[0]) / eye1[0])
            eye1_y = eye1[1]
            eye1_z = 0.

            eye0 = np.array([eye0_x, eye0_y, eye0_z])
            eye1 = np.array([eye1_x, eye1_y, eye1_z])

            roll = ut.getAngle(eye0, type_="roll")

            ## YAW
            jaw0 = kp[3]
            jaw1 = kp[13]
            points = np.array([jaw0, jaw1])
            jawCenter = ut.getCenter(points)

            kp_yaw = kp - jawCenter

            jaw0 = kp_yaw[3]
            jaw1 = kp_yaw[13]
            points = np.array([jaw0, jaw1])
            jawDist = ut.getDist(points, type_="yaw")

            x = jawDist / 2

            jaw0_x = x * (abs(jaw0[0]) / jaw0[0])
            jaw0_y = 0.
            jaw0_z = jaw0[2]

            jaw1_x = x * (abs(jaw1[0]) / jaw1[0])
            jaw1_y = 0.
            jaw1_z = jaw1[2]

            jaw0 = np.array([jaw0_x, jaw0_y, jaw0_z])
            jaw1 = np.array([jaw1_x, jaw1_y, jaw1_z])

            yaw = ut.getAngle(jaw0, type_="yaw")
            yaw = yaw * -1

            ## PITCH
            jaw0 = kp[3]
            jaw1 = kp[13]
            points = np.array([jaw0, jaw1])
            jawCenter = ut.getCenter(points)

            kp_pitch = kp - jawCenter

            lip = kp_pitch[62]
            points = np.array([[0, 0, 0], lip])
            hypCenter = ut.getCenter(points)

            kp_pitch = kp_pitch - hypCenter

            lip = kp_pitch[62]
            jaw0 = kp_pitch[3]
            jaw1 = kp_pitch[13]
            points = np.array([jaw0, jaw1])
            jawCenter = ut.getCenter(points)

            points = np.array([lip, jawCenter])
            hypDist = ut.getDist(points, type_="pitch")

            z = hypDist / 2

            lip_x = 0.
            lip_y = lip[1]
            lip_z = z * (abs(lip[2]) / lip[2])

            jawCenter_x = 0.
            jawCenter_y = jawCenter[1]
            jawCenter_z = z * (abs(jawCenter[2]) / jawCenter[2])

            lip = np.array([lip_x, lip_y, lip_z])
            jawCenter = np.array([jawCenter_x, jawCenter_y, jawCenter_z])

            pitch = ut.getAngle(lip, type_="pitch")

            euler = np.array([roll, pitch, yaw]).reshape(-1, 3)
            pose = np.vstack([pose, euler])

        np.savetxt(os.path.join(self.folder, "pose.txt"), pose)
コード例 #21
0
ファイル: pc3.py プロジェクト: PythonJedi/pc3
        return json.dumps({
            "status": False,
            "message": "That is not a valid problem identifier!"
        })

    if request.method == "POST":
        return json.dumps({
            "status": False,
            "message": "Manual overrides not implemented yet"
        })


@app.route("/api/supervise/kill/<team>/<problem>/<run>")
@flaskutils.requires_auth  # See note on supervise_override
def supervise_kill(team, problem, run):
    """kill a malfunctioning run"""
    # I have no idea how this should be implemented.
    return json.dumps({
        "status": False,
        "message": "Action is not implemented yet."
    })


if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG)
    if len(sys.argv) == 2 and os.path.isdir(
            sys.argv[1]):  # overriding data directory
        dataDir = sys.argv[1]
    util = util.Util(dataDir)
    app.run(host='0.0.0.0')
コード例 #22
0
#   dolphin will hang waiting for input and never receive it
controller1.connect()
controller2.connect()

supportedcharacters = [melee.enums.Character.PEACH, melee.enums.Character.CPTFALCON, melee.enums.Character.FALCO, \
    melee.enums.Character.FOX, melee.enums.Character.SAMUS, melee.enums.Character.ZELDA, melee.enums.Character.SHEIK, \
    melee.enums.Character.PIKACHU, melee.enums.Character.JIGGLYPUFF, melee.enums.Character.MARTH]

cpu_state = menuhelper.CpuState.UNSET
cpu_char_state = menuhelper.CpuState.UNSET
is_ai = True
is_ai_2 = False

if is_ai:
    util1 = util.Util(
        dolphin.logger, controller1,
        config.Config('current_model', args.new, config.ModelType.BINARY))

if is_ai_2:
    util2 = util.Util(
        dolphin.logger, controller2,
        config.Config('model3', args.new, config.ModelType.BINARY))

if is_ai == True and is_ai_2 == True:
    score1, score2 = 0, 0

data_frame = 0
total_data_frames = 0
episode_size = 1000
buffer = experience_replay.ExperienceReplay(episode_size * 10)
#Main loop
コード例 #23
0
ファイル: python.py プロジェクト: albertyw/req-update
 def __init__(self) -> None:
     self.install = False
     self.updated_files: Set[str] = set([])
     self.util = util.Util()
#!/usr/bin/python
# coding:utf-8

from uiautomatorplug.android import device as d
import unittest
import commands
import string
import time
import sys
import util

u = util.Util()

PACKAGE_NAME = 'com.intel.android.gallery3d'
ACTIVITY_NAME = PACKAGE_NAME + '/.app.Gallery'

#Max X position
XMAX = 720
#Y postion for suboption when edit picture
YSUB = 980
#Per line items' count
ITEMCOUNT = 5
#Width for each item
XUNIT = XMAX / ITEMCOUNT
#X postion for the center of the first item
XITEM = XUNIT / 2


class GalleryTest(unittest.TestCase):
    def setUp(self):
        super(GalleryTest, self).setUp()
コード例 #25
0
def main():
    mail_notification = False

    c_wmi = wmi_class.WmiClass()
    ssh = ssh_client.SshClient()
    utils = util.Util()

    webservers_file_path = "webserver.txt"
    f_nam = "srv.txt"
    output_file_name = "another-name.html"
    hosts = []
    webserver_hosts = []

    config = load_config("config.json")

    # WMI user/pass
    wmi_user = utils.b64_decrypt(config.get("wmi").get("user"))
    wmi_pwd = utils.b64_decrypt(config.get("wmi").get("password"))

    ssh_user = utils.b64_decrypt(config.get("ssh").get("user"))
    ssh_pwd = utils.b64_decrypt(config.get("ssh").get("password"))
    ssh_port = config.get("ssh").get("port")
    ssh_payload = utils.b64_decrypt(config.get("ssh").get("payload"))
    print("[+] Payload length:: " + str(len(ssh_payload)))

    user = config.get("mail").get("smtp").get("user")

    serv = config.get("mail").get("smtp").get("server")
    port = config.get("mail").get("smtp").get("port")

    para = config.get("mail").get("to")
    subject = config.get("mail").get("subject")

    p = _parser.Parser()

    # with open("C:\\Users\\opensylar\\Desktop\\mem_parse.log", "r") as fp:
    #    l = fp.read()
    #    p.parse_mem(l)

    with open(webservers_file_path, "r") as f:
        ports = [80, 443]

        for c_addr in f:
            c_addr = c_addr.replace("\n", "")
            c_addr = c_addr.replace("\r", "")
            print("[+] Sending web tests to " + c_addr)
            status_web = check_web(c_addr, ports)
            webserver_hosts.append(status_web)

    with open(f_nam, "r") as f:
        for c_addr in f:
            c_addr = c_addr.replace("\n", "")
            c_addr = c_addr.replace("\r", "")

            if is_ip_range(c_addr) > 0x0:
                net1 = ip_network(c_addr, strict=False)

                for addr in net1:
                    addr = str(addr)
                    hosts.append({"hostname": addr})

            else:
                hosts.append({"hostname": c_addr})

    # Setea las variables del dict
    for h in hosts:
        print("\r\n[+] Checking " + h.get("hostname"))

        std_out, std_error = run_ping2(h.get("hostname"))
        ping_vals = parse_output_ping(std_out)

        h.update(ip_addr=h.get("hostname"))

        if ping_vals["ttl"] is not 0x0:
            html_path = "report-details/details-" + h.get("hostname") + ".html"
            h.update(status="up")

            # dns_nam = dns_resolver(h.get("hostname"))

            try:
                dns_nam = socket.gethostbyaddr(h.get("hostname"))
                dns_nam = dns_nam[0]

            except socket.herror:
                dns_nam = "Unknow"

            os_nam = os_detect(ping_vals["ttl"])
            # print("TTL:: " + str(ping_vals["ttl"]))

            h.update(dns_name=dns_nam)
            h.update(os=os_nam)
            h.update(html_path=html_path)

            s = socket_client.SocketClient()
            html_rpt = html_report.HtmlReport()
            html_rpt.set_path("report-details")

            if os_nam == "Windows":
                print("[+] Sending WMI query..")

                c_wmi.send_query(h.get("hostname"), wmi_user, wmi_pwd, 0x1)
                c_wmi.send_query(h.get("hostname"), wmi_user, wmi_pwd, 0x2)
                c_wmi.send_query(h.get("hostname"), wmi_user, wmi_pwd, 0x3)
                c_wmi.send_query(h.get("hostname"), wmi_user, wmi_pwd, 0x4)

                h.update(status_agent="1")
                html_rpt.build(h.get("hostname"), c_wmi, html_path, False)

            else:
                h.update(status_agent="1")
                print("[+] Sending SSH payload..")

                c_ssh = ssh.send_query(h.get("hostname"), ssh_port, ssh_user,
                                       ssh_pwd, ssh_payload)

                html_rpt.build(h.get("hostname"), c_ssh, html_path, True)

        # Offline
        else:
            print("[!] " + h.get("hostname") + " offline")
            h.update(status_agent="0")
            h.update(status="down")  # Dead

            try:
                dns_nam = socket.gethostbyaddr(h.get("hostname"))
                dns_nam = dns_nam[0]

            except socket.herror:
                dns_nam = "Unknow"

            except socket.gaierror:
                print("[!] " + h.get("hostname") + " is bad host")
                exit(-1)

            h.update(dns_name=dns_nam)
            h.update(os="Unknow")

    createhtml(output_file_name, hosts, webserver_hosts)

    c_path = os.getcwd()
    file_output = c_path + "\\reports.zip"
    build_zip(c_path, file_output, output_file_name)

    if mail_notification is True:
        print("[+] Sending mail to SMTP relay server")

        u = {"sender": user}
        s = {"serv": serv, "port": port}
        m = {
            "to": para,
            "subject": subject,
            "attach": file_output,
            "body": "Report"
        }
        send_mail(m, u, s)

    print("[+] Finish!")
コード例 #26
0
ファイル: train.py プロジェクト: azumag/gomoku-ai
#-*- coding: utf-8 -*-

import tensorflow as tf
import perceptron as nn
import util as u

accuracies = []

#for i in range(1, 10):
n = nn.Perceptron(4, 81, 81)
n.train('../tmp/h-4v4', '../tmp/a-4v4', 1)
data_sample = u.Util().load_data('../tmp/h-4v4')
result = n.execute(data_sample)
accuracies.append(result)

n.save('./testsave/save.ckpt')

print accuracies
コード例 #27
0
        # print(stdin)

        str_output = ''.join(str(e) for e in stdout)
        str_err_output = ''.join(str(e) for e in stderr)
        print()

        return {"stdout": str_output, "stderr": str_err_output}

        # print(stdout)
        # print(stderr)
        repeat = False


a = app.App()
utils = util.Util()
remote_folder = "/tmp/"
ssh_port = 22
creds_b64 = a.get_creds("creds.json")
usr = utils.b64_decrypt(creds_b64["ssh_user"])
pwd = utils.b64_decrypt(creds_b64["ssh_password"])
plaintext_sudo_password = utils.b64_decrypt(creds_b64["ssh_password"])
upload = True

array_cmds = a.get_array_cmd("cmds.json", plaintext_sudo_password)

with open("srv.txt") as fp:
    lines = fp.readlines()

    for c_line_hst in lines:
コード例 #28
0
ファイル: S1.py プロジェクト: vewe-richard/sd-wan-controller
import time
import spec
import util

if __name__ == "__main__":
    thespec = spec.Spec()
    theutil = util.Util()

    theutil.http_post("/tunnel/create", thespec.spec())

    time.sleep(1)