コード例 #1
0
def create_check(args):
    """ Specify command and define check logic """

    cmd = "show version"
    host = args.host
    url = "https://" + host + "/ins"
    username = args.username
    password = args.password

    response = reader(username, password, url, cmd)

    kick_start_image = response['result']['body']['kickstart_ver_str']
    chassis_id = response['result']['body']['chassis_id']
    hostname = response['result']['body']['host_name']
    uptime = (str(response['result']['body']['kern_uptm_days']) + " days " +
              str(response['result']['body']['kern_uptm_hrs']) + " hours " +
              str(response['result']['body']['kern_uptm_mins']) + " minutes")
    last_reload_reason = response['result']['body']['rr_reason']
    output = "Uptime: {0}, Chassis: {1}, Hostname: {2}, Software version: {3}, Last reload reason: {4}".format(
        uptime, chassis_id, hostname, kick_start_image, last_reload_reason)

    if args.warning:
        m_runtime = (
            int(response['result']['body']['kern_uptm_days']) *
            1440) + (int(response['result']['body']['kern_uptm_hrs']) *
                     60) + int(response['result']['body']['kern_uptm_mins'])

        if int(m_runtime) < int(args.warning):
            nagios_msg(1, "Warning: " + output)
        else:
            nagios_msg(0, "OK: " + output)
    else:
        nagios_msg(0, "OK: " + output)
コード例 #2
0
ファイル: version.py プロジェクト: jpajicek/nagios
def create_check(args):
    """ Specify command and define check logic """

    cmd = "show version"
    host = args.host
    url = "https://"+host+"/ins"
    username = args.username
    password = args.password
 
    response = reader(username, password, url, cmd)
    
    kick_start_image = response['result']['body']['kickstart_ver_str']
    chassis_id = response['result']['body']['chassis_id']
    hostname = response['result']['body']['host_name']
    uptime = (str(response['result']['body']['kern_uptm_days']) + " days " + 
              str(response['result']['body']['kern_uptm_hrs']) +  " hours " +
              str(response['result']['body']['kern_uptm_mins']) + " minutes")
    last_reload_reason = response['result']['body']['rr_reason']
    output = "Uptime: {0}, Chassis: {1}, Hostname: {2}, Software version: {3}, Last reload reason: {4}".format(uptime , chassis_id, hostname, kick_start_image, last_reload_reason)

    if args.warning:
      m_runtime = (int(response['result']['body']['kern_uptm_days']) * 1440) + (int(response['result']['body']['kern_uptm_hrs']) * 60) + int(response['result']['body']['kern_uptm_mins'])
      
      if int(m_runtime) < int(args.warning):
        nagios_msg(1, "Warning: " + output)
      else:
        nagios_msg(0, "OK: " + output)
    else:
      nagios_msg(0, "OK: " + output)
コード例 #3
0
def main():

    train_file = 'Data/train_data.txt'
    test_file = 'Data/test_data.txt'
    variables = [
        'ID', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10',
        'f11', 'class'
    ]
    #
    #
    print("========= Reading train dataset =========")
    # TO DO:
    # use the read data function you created to read the train data
    train_data = reader(train_file, variables)
    print("======== Done reading =========.\n")

    print("========= Reading test data =========")
    # TO-DO
    # Read the test  data
    test_data = reader(test_file, variables)
    print("========= Done reading =========.\n")

    print("==== Training classifier =====")
    # TO-DO
    # Initialize the classifier you built in model.py and return the necessary values
    model = RuleBasedModel()
    print("======== Done training classifier ===========.\n")

    print("========= Classifying test samples =======")
    # TO-DO
    # use your classifier to do predictions on all the test samples
    predictions = model.predict_all(test_data)
    for i in range(len(predictions)):
        test_data[i]['prediction'] = predictions[i]
    print("========== Done classifying =======")

    # TO-DO
    # Evalutate your classifier with the Accuracy function you implemented and return the necessary outputs
    accuracy, numCorrect, total_samples = model.accuracy(test_data)
    print(
        f"Model's Accuracy {round(accuracy)} %, model correctly predicted {numCorrect} out of {total_samples}"
    )
    print('================================================================')
    print("finished.\n")
コード例 #4
0
ファイル: eigrp.py プロジェクト: jpajicek/Cisco-NX-API
def create_check(args):
	""" Specify command and define check logic """
	vrf_name = args.vrf
	cmd = "show ip eigrp neighbors vrf "+vrf_name
	host = args.host
	url = "https://"+host+"/ins"
	username = args.username
	password = args.password
	count = args.count
 	
	response = reader(username, password, url, cmd)
	check_result(count, eigrpNeighbors(response))
コード例 #5
0
ファイル: parsers.py プロジェクト: tspooner/rl_markets
    def __init__(self, path, days=None):
        self.path = path
        self.reader = reader(path)

        if days is not None:
            days = days if isinstance(days, list) else [days]

            self.days = days
            self.start_day = min(days)
            self.end_day = max(days)

        else:
            self.days = None
            self.start_day = date(1900, 1, 1)
            self.end_day = date(2200, 1, 1)
コード例 #6
0
ファイル: fex.py プロジェクト: jpajicek/Cisco-NX-API
def create_check(args):
    """ Specify command and define check logic """

    cmd = "show fex detail"
    host = args.host
    url = "https://" + host + "/ins"
    username = args.username
    password = args.password

    response = reader(username, password, url, cmd)

    status = fexStatus(response)
    long_msg = json.dumps(status).strip('{}')

    if bool(status['failed']):
        nagios_msg(1, 'Critical: {0}'.format(long_msg))
    if bool(status['failed_uplink']):
        nagios_msg(1, 'Warning: {0}'.format(long_msg))
    else:
        nagios_msg(0, 'OK: {0}'.format(long_msg))
コード例 #7
0
ファイル: fex.py プロジェクト: jpajicek/nagios
def create_check(args):
	""" Specify command and define check logic """

	cmd = "show fex detail"
	host = args.host
	url = "https://"+host+"/ins"	
	username = args.username
	password = args.password

	response = reader(username, password, url, cmd)
	
	status = fexStatus(response)
	long_msg = json.dumps(status).strip('{}')

	if bool(status['failed']):
		nagios_msg(1, 'Critical: {0}'.format(long_msg))
	if bool(status['failed_uplink']):
		nagios_msg(1, 'Warning: {0}'.format(long_msg))
	else:
		nagios_msg(0, 'OK: {0}'.format(long_msg))
コード例 #8
0
ファイル: vpc.py プロジェクト: jpajicek/nagios
def create_check(args):
	""" Specify command and define check logic """

	cmd = "show vpc brief"
	host = args.host
	url = "https://"+host+"/ins"
	username = args.username
	password = args.password
 	option = str(args.option)

 	response = reader(username, password, url, cmd)

	vpc_peer_status = response['result']['body']['vpc-peer-status']
	vpc_peer_status_reason = response['result']['body']['vpc-peer-status-reason']
	vpc_peer_keepalive_status = response['result']['body']['vpc-peer-keepalive-status']
	vpc_peer_consistency_status = response['result']['body']['vpc-peer-consistency-status']
	vpc_type_2_consistency_status = response['result']['body']['vpc-type-2-consistency-status']
	vpc_role = response['result']['body']['vpc-role']
	
	### Group options
	consistency_params = {'vpc_peer_status_reason':vpc_peer_status_reason,'vpc_peer_consistency_status':vpc_peer_consistency_status, 'vpc_type_2_consistency_status':vpc_type_2_consistency_status}
	peer_status_params = {'vpc_peer_status': vpc_peer_status, 'vpc_peer_keepalive_status': vpc_peer_keepalive_status, 'vpc_role': vpc_role, 'vpc_role_expected': args.role }

	vpc_params = {'peerStatus': peer_status_params, 'isSuccess': consistency_params }

	if option == "portchannel":
		status = vpcStatus(response)
		if bool(status['inconsistent']):
			nagios_msg(1, 'Warning: vPC portchannel(s) in inconsistent state: {0}'.format(status['inconsistent']))
		else:
			nagios_msg(0, 'OK: No consistency errors found - vPC portchannel(s) in UP state: {0}'.format(status['active']))
	else:
		long_msg = vpcDomainStatus(response)
		status = consistencyCheck(vpc_params)

		if bool(status['inconsistent']):
			nagios_msg(1, 'Critical: {0} -- Details: {1}'.format(str(status['inconsistent']), long_msg))
		else:
			nagios_msg(0, 'OK: {0}'.format(long_msg))
コード例 #9
0
conf = {
    'filename':file2,
    'nb_epoch':3000,
    'batch_size':5,
    'maxlen': 20,
    'sample_size':10000,
    'context_size':0,
    'input_dim':26,
    'hidden_size': 100,
    'learning_rate':0.05,
    'scale': 1
}

print "Begin to load data"
reader = reader(conf)
reader.get_data()
# reader.padding()
features = reader.features
targets = reader.targets
print "Load data complete"

print "Begin to build Networks"
network = lstm(conf)
network.build_net()
print "Build Networks complete"
# print  network.fit(features, targets)
print network.test(features, targets, reader.testset,reader.testtar)
# network.draw("model.png")

コード例 #10
0
ファイル: main.py プロジェクト: WillaFan/hypernymy-extraction
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('cmd')
    parser.add_argument('--params',help='Parameters for models.')
    parser.add_argument('--dset',help='Corpus path for hypernymy extraction.')
    parser.add_argument('--output',help='Output path for hypernymy pairs.')
    parser.add_argument('--evaluate',help='Evaluation for hypernymy extraction models.')
    args = parser.parse_args()

    if args.cmd == 'hearst':
        hp = hearst.HearstPatterns(extended=args.params)
        if args.dset == None:
            pass
        else:
            data = utils.reader(args.dset)
            pair_list = hp.find_hyponyms(data)
            if args.output is not None:
                utils.writer(args.output,pair_list)
                print('Finished ...')
            else:
                print('Do not specifiy output file, but still show 5 of the results here.')
                for i in range(5):
                    print(pair_list[i])
                print('Finished ...')

    elif args.cmd == 'PPMI':
        # Read prediction from precomputed file
        shutil.copyfile("./patternBased/result_ppmi.txt", args.output)
        with open(args.output) as f:
            print("======== PPMI : score ======== ")
            print("Print out first 5 examples.")
            for i in range(6):
                print(f.readline())
    elif args.cmd == 'PPMISVD':
        path = "result_SvdPpmi_"+str(args.params)+".txt"
        shutil.copyfile("./patternBased/"+path, args.output)
        with open(args.output) as f:
            print("======== PPMI-SVD : score ======== ")
            print("k = ", args.params)
            print("Print out first 5 examples.")
            for i in range(6):
                print(f.readline())

    elif args.cmd == 'dist':
        if args.evaluate is not None:
            res = pd.read_table("./distributional/data/results.txt", sep="\t")
            print("======== Distributional Model : score ======== ")
            print(res.head(6))

    elif args.cmd == 'embed':
        shutil.copyfile("./termEmbed/term_embed_result.txt", args.output)
        if args.evaluate is not None:
            res = pd.read_table("./termEmbed/results.txt", sep="\t")
            print("======== Term Embedding : score ======== ")
            print(res.head(10))

    elif args.cmd == 'Projection':
        if args.output == None:
            pass
        else:
            print("Loading model...\n")
            model = train_model('./projection/dumped.data','./projection/modLog.txt', 9510, use_gpu = False)
            # save_model('./projection/projectMod.pt', model)
            print("Loading test data...\n")
            data=joblib.load('./projection/dumped.data')
            candidates = data["candidates"]
            test_q_cand_ids = data["test_query_cand_ids"]
            test_q_embed = make_embedder(data["test_query_embeds"], grad=False,
                                         cuda=model.use_cuda, sparse=False)
            print("Writing predictions...")
            test_eval = Evaluator(model, test_q_embed, test_q_cand_ids)
            test_eval.write_predictions(args.output, list(candidates))
            print("Done.\n")
        if args.evaluate == 'True':
            Dev_score={}
            Dev_score['DevMAP'] = [];Dev_score['DevAP'] = [];Dev_score['DevMRR'] = []
            for line in open('./projection/modLog.txt',"r"):
                if line.split()[0] == 'Epoch':
                    # header, skip
                    continue
                else:
                    Dev_score['DevMAP'].append(float(line.split()[5]))
                    Dev_score['DevAP'].append(float(line.split()[6]))
                    Dev_score['DevMRR'].append(float(line.split()[7]))
            print("======== Projection Learning : score ======== ")
            print("SemEval2018 Task9.")
            print("DevMAP\tDevAP\tDevMRR")
            print(str(max(Dev_score['DevMAP']))+"\t"+str(max(Dev_score['DevAP']))+"\t"+str(max(Dev_score['DevMRR'])))

    elif args.cmd == 'BiLSTM':
        # use default test data
        if args.output == None:
            pass
        else:
            if args.evaluate is not None:
                print("======== BiLSTM Model : f1 score ======== ")
                with open("./BiLSTM/data/res.score.txt", "r") as score:
                    print(score.read())
コード例 #11
0
#!/usr/bin/env python

from __future__ import print_function

from utils import convolve
from utils import reader
from utils import score

if __name__ == '__main__':
    with open('data.txt', 'r') as f:
        acres = reader(f)

    for _ in range(10):
        acres = convolve(acres)

    print('Answer:', score(acres))
    # 589931
コード例 #12
0
ファイル: vpc.py プロジェクト: jpajicek/Cisco-NX-API
def create_check(args):
    """ Specify command and define check logic """

    cmd = "show vpc brief"
    host = args.host
    url = "https://" + host + "/ins"
    username = args.username
    password = args.password
    option = str(args.option)

    response = reader(username, password, url, cmd)

    vpc_peer_status = response['result']['body']['vpc-peer-status']
    vpc_peer_status_reason = response['result']['body'][
        'vpc-peer-status-reason']
    vpc_peer_keepalive_status = response['result']['body'][
        'vpc-peer-keepalive-status']
    vpc_peer_consistency_status = response['result']['body'][
        'vpc-peer-consistency-status']
    vpc_type_2_consistency_status = response['result']['body'][
        'vpc-type-2-consistency-status']
    vpc_role = response['result']['body']['vpc-role']

    ### Group options
    consistency_params = {
        'vpc_peer_status_reason': vpc_peer_status_reason,
        'vpc_peer_consistency_status': vpc_peer_consistency_status,
        'vpc_type_2_consistency_status': vpc_type_2_consistency_status
    }
    peer_status_params = {
        'vpc_peer_status': vpc_peer_status,
        'vpc_peer_keepalive_status': vpc_peer_keepalive_status,
        'vpc_role': vpc_role,
        'vpc_role_expected': args.role
    }

    vpc_params = {
        'peerStatus': peer_status_params,
        'isSuccess': consistency_params
    }

    if option == "portchannel":
        status = vpcStatus(response)
        if bool(status['inconsistent']):
            nagios_msg(
                1, 'Warning: vPC portchannel(s) in inconsistent state: {0}'.
                format(status['inconsistent']))
        else:
            nagios_msg(
                0,
                'OK: No consistency errors found - vPC portchannel(s) in UP state: {0}'
                .format(status['active']))
    else:
        long_msg = vpcDomainStatus(response)
        status = consistencyCheck(vpc_params)

        if bool(status['inconsistent']):
            nagios_msg(
                1, 'Critical: {0} -- Details: {1}'.format(
                    str(status['inconsistent']), long_msg))
        else:
            nagios_msg(0, 'OK: {0}'.format(long_msg))