I have written the SNMP agent code by configuring two different context names at the SnmpContext class instance. It will register a MIB tree under particular contextName like below,
class Test():
def readVars (self , varBinds, acInfo=(None, None)):
retItem = []
for ov in varBinds:
if str(ov[0]) == '1.3.6.1.4.1.26262.1.1.1.0':
retItem.extend([(ov[0], v2c.OctetString('%s' % 'value1'))])
elif str(ov[0]) == '1.3.6.1.4.1.26262.1.1.2.0':
retItem.extend([(ov[0], v2c.OctetString('%s' % 'value2'))])
.
.
.
return retItem
def readNextVars (self , varBinds, acInfo=(None, None)):
retItem = []
for ov in varBinds:
if str(ov[0]) == '1.3.6.1.4.1.26262.1.1.1.0':
retItem.extend([('1.3.6.1.4.1.26262.1.1.2.0', v2c.OctetString('%s' % 'value2'))])
elif str(ov[0]) == '1.3.6.1.4.1.26262.1.1.2.0':
retItem.extend([('1.3.6.1.4.1.26262.1.1.3.1.1.0', v2c.OctetString('%s' % 'value3'))])
.
.
.
.
else:
retItem.extend([('1.3.6.1.4.1.26262.1.1.1.0', v2c.OctetString('%s' % 'value1'))])
return retItem
mibTreeA = Test()
snmpContext.registerContextName(v2c.OctetString('context-a'), mibTreeA)
snmpContext.registerContextName(v2c.OctetString('context-b'), mibTreeA)
As in the example sample
Here next OID is returned by checking condition using if statement. But I have multiple OIDs and incrementing that using the if statement would be painful.
So I would like to know is there a way to increment the OIDs dynamically? Any example script will be helpful.
Thanks in advance.
May be an alternative approach could be to have a dict of OID-value pairs (where value can be a callable), then .nextKey method would do the increment part?
In other words, may be all those if conditions could be folded into some ordered data structure supporting essentially two operations:
get the next item
get the value associated with an item
Related
Here's my situation. I got two lists:
A list which comes from DF column (OS_names)
A list with the unique values of that column (OS_values)
OS_name = df['OS_name'].tolist()
OS_values = df.OS_name.unique().tolist()
I want to create several lists (one per value in OS_values) like this :
t = []
for i in range(0,len(OS_name)-1):
if OS_values[0] == OS_name[i]:
t.append(1)
else:
t.append(0)
I want to create a list per each value in OS_value, then store them into a dictionary, and at the end creating a df from my dictionary.
If you're able to insert the value as the key it would be great, but not necessary.
I read the defaultdict may be helpful but I cannot find a way to use it.
thanks for the help and have a great day!
I did it at the very end.
dict_stable_feature = dict()
for col in df_stable:
t1 = df[col].tolist()
t2 = df[col].unique().tolist()
for value in t2:
t = []
for i in range (0, len(t1)-1):
if value == t1[i]:
t.append(1)
else:
t.append(0)
cc = str(col)
vv = "_" + str(value)
cv = cc + vv
dict_stable_feature[cv] = t
OK so let's say I have a situation where I have a bunch of objects in different classifications and I need to know the total possible combinations of these objects so I end up with an input that looks like this
{'raw':[{'AH':['P','C','R','Q','L']},
{'BG':['M','A','S','B','F']},
{'KH':['E','V','G','N','Y']},
{'KH':['E','V','G','N','Y']},
{'NM':['1','2','3','4','5']}]}
Where the keys AH, BG, KH, NM constitute groups, the values are list that hold individual objects and a finished group would constitute one member of each list, in this example KH is listed twice so each finished group would have 2 members of KH in it. I build something that handles this, it looks like this.
class Builder():
def __init__(self, data):
self.raw = data['raw']
node = []
for item in self.raw:
for k in item.keys():
node.append({k:0})
logger.debug('node: %s' % node)
#Parse out groups#
self.groups = []
increment = -2
while True:
try:
assert self.raw[increment].values()[0][node[increment][node[increment].keys()[0]]]
increment = -2
for x in self.raw[-1].values()[0]:
group = []
for k in range(0,len(node[:-1])):
position = node[k].keys()[0]
player = self.raw[k].values()[0][node[k][node[k].keys()[0]]]
group.append({position:player})
group.append({self.raw[-1].keys()[0]:x})
if self.repeatRemovals(group):
self.groups.append(group)
node[increment][node[increment].keys()[0]]+=1
except IndexError:
node[increment][node[increment].keys()[0]] = 0
increment-=1
try:
node[increment][node[increment].keys()[0]]+=1
except IndexError:
break
for group in self.groups:
logger.debug(group)
def repeatRemovals(self, group):
for x in range(0, len(group)):
for y in range(0, len(group)):
if group[x].values()[0] == group[y].values()[0] and x != y:
return False
return True
if __name__ == '__main__':
groups = Builder({'raw':[{'AH':['P','C','R','Q','L']},
{'BG':['M','A','S','B','F']},
{'KH':['E','V','G','N','Y']},
{'KH':['E','V','G','N','Y']},
{'NM':['1','2','3','4','5']}]})
logger.debug("Total groups: %d" % len(groups.groups))
The output of running this should clearly state my intended goal, if I have failed to do so in text. My concern is the time it takes to handle large classification of objects, when a classification has some 40 something objects in it, it is in the matrix three times and there are 7 other classifications with comparable object sizes. I think the numpy library could help me, but I am new to scientific programming and am not sure how to go about it, or if it would be worth it, could anyone provide some insight? Thank you.
Try this:
Remove duplicated values
Calculate all possibilities using permutation and factorial
Like that:
https://www.youtube.com/watch?v=Oc50d2GqXx0
I created a list comprehension to provide me the following:
listoflists = [[] for i in range(252*5)]
I then simplified the list in variable newlists to contain only the number of lists in range(weeks) which is a dynamic variable.
I want to append each individual list in the following loop for a specified range with the append process moving through each list after its reached a specified length. The values are generated from an input function. For instance, if the first list in newlists exceeds a length of 5 I want the values following the 5th loop to then append to the next list and so on. The code I currently have is:
p = 0
singlist = []
listoflists = [[] for i in range(252*5)]
newlists= [listoflists[i] for i in range(weeks)]
while p<(int(people)*weeks): #fix appending process
for i in range(int(people)*weeks):
weekly =input("Put your hours: ")
singlist.append(int(weekly))
p += 1
if weekly.isalpha() == True:
print("Not a valid amount of time")
for i in range(0,weeks):
while len(newlists[i])<int(people):
newlists[i].append(singlist[i])
This code however appends the same values to all lists in range weeks. What is the most efficient way to fix this? Thank you!
if singlist = [10,15,20,25]
desire output for newlists is: [[10,15],[20,25]]
How I've structured the program:
import sys
import numpy as np
import pandas as pd
from datetime import tzinfo,timedelta,datetime
import matplotlib.pyplot as plt
import itertools as it
from itertools import count,islice
team = []
y = 0
while y == 0:
try:
people = input("How many people are on your engagement? ")
if people.isdigit() == True:
y += 1
except:
print("Not a number try again")
z= 0
while z<int(people):
for i in range(int(people)):
names = input("Name: ")
if names.isalpha() == False:
team.append(names)
z+=1
elif names.isdigit() == True:
print("Not a name try again")
ties = [] # fix looping for more than one person
e = 0
while e<int(people):
for i in range(int(people)):
title = input("What is their title: ")
if title.isdigit() == True:
print("Not a title try again")
else:
ties.append(title)
e+=1
values = [] #fix looping for more than one person
t= 0
while t <int(people):
for i in range(int(people)):
charge = input("How much are you charging for them: ")
if charge.isalpha() == True:
print("Not a valid rate")
else:
values.append(int(charge))
t +=1
weeks = int(input("How many weeks are you including: "))
days = []
x = 0
while x<weeks: #include a parameter for dates of a 7 day difference to only be permitted
try:
for i in range(int(weeks)):
dates = input("Input the dates (mm/dd/yy): ")
dt_start = datetime.strptime(dates,'%m/%d/%y')
days.append(dates)
x+=1
except:
print("Incorrect format")
p = 0
singlist = []
listoflists = [[] for i in range(252*5)]
newlists= [listoflists[i] for i in range(weeks)]
while p<(int(people)*weeks): #fix appending process
for i in range(int(people)*weeks):
weekly =input("Put your hours: ")
singlist.append(int(weekly))
p += 1
if weekly.isalpha() == True:
print("Not a valid amount of time")
def func(items,n):
items = iter(items)
for i in it.count():
out = it.islice(items,weeks*i,weeks*i+n)
if not out:
break
output = list(func(singlist,weeks))
# items = [1,2,3,...n]
# output = [[1,2],[3,4],..], n = 2 elements each
items_ = iter(items)
outiter = iter(lambda: [next(items_) for i in range(n)],[])
outlist = list(outiter)
You can do the same thing using while loop in place of count() and [a:b] slice operation on list instead of islice(). But using iterators is very efficient.
I am new to Python. I won't hide this is homework. I cannot figure out a way to iterate through multiple lists.
I originally wrote the below coding for one list ('lst') and it worked perfectly! Then I went back to add the other three lists and I don't know why I can't get it to work.
Any suggestions would be much appreciated. And if there are any tips on cleaning and refactoring, I'd appreciate it!.
result='False'
def magic(lst):
count=0
#Create a list.
if count == 0:
lst=[(4,9,2),(3,5,7),(8,1,6)]
count==1
result='True'
elif count==1:
lst=[(2,7,6),(9,5,1),(4,3,8)]
count==2
result='True'
elif count==2:
lst=[(1,2,3),(4,5,6),(7,8,9)]
count==3
result='True'
else:
lst=[(4,9,2),(3,5,5),(8,1,6)]
result='True'
return result
#set condition for magic square and print results
if is_row(let) and is_col(let) and is_diag(lst):
print('True')
else:
print("False")
#is_row function accepts a list as argument returns true or false
def is_row(lst):
if sum(lst[0]) == sum(lst[1]) == sum(lst[2]):
result_R = True
else:
result_R = False
return result_R
#is_col does the same thing as is_row
def is_col(lst):
for i in lst:
#select from the tuples in lst to make columns list
col1=[i[0] for i in lst]
col2=[i[1] for i in lst]
col3=[i[2] for i in lst]
if sum(col1) == sum(col2) == sum(col3):
result_C = True
else:
result_C = False
return result_C
def is_diag(lst):
#unpack all tuples into single list for easier indexing.
unpack1=[num for element in lst for num in element]
#Diagonal one slice
D1=unpack1[0:9:4]
#reverse list...simpler way of preparing for Diagonal Two
lst.reverse()
#unpack the reversed list
unpack2=[num for element in lst for num in element]
#Diagonal 2 slice
D2=unpack2[0:9:4]
#Condition for sum comparison
if sum(D1)==sum(D2):
result_D = True
else:
result_D = False
return result_D
magic(a,b,c,d)
So I have an Article class that models the articles in a store. When I create a new article, I want it to have an EAN 13 code. So I initialize the article with a 12 digits code and use the check_ean13() funtion to retrieve the control digit. It works but seems like in any moment, when the object is created, rewrite the ean13 attribute and replaces it for None. Any ideas?
Main
if __name__ == "__main__":
# create article
art1 = Article("123456789087", "Article 1", 145.6, 200.0)
print art1
print art1.get_ean13()
class Article
class Article:
def __init__(self, cod, art_name, cost, listprice):
self.ean13 = self.set_ean13(cod)
self.art_name = art_name
self.cost = cost
self.listprice = listprice
self.commission = None
self.promotion=[]
def get_ean13(self):
return self.ean13
def set_ean13(self,cod):
cd = self.check_ean13(cod)
ean13 = cod + str(cd)
self.ean13=ean13
def check_ean13(self, code):
checksum = 0
for i, digit in enumerate(reversed(code)):
checksum += int(digit) * 3 if (i % 2 == 0) else int(digit)
return (10 - (checksum % 10)) % 10
output:
None - Article 1 list price: 400.0
None
self.ean13 = self.set_ean13(cod)
set_ean13 doesn't return anything, so you're effectively doing self.ean13 = None here. Just call the method without assigning the result.
self.set_ean13(cod)