I bought a MCP23017 for my Raspberry Pi to increase the GPIO pins.
With the help of you guys I was able to install and read from the device. That means, I've interfaced with the MCP23017 and set the bus to 0x20 as I have A0-A3 connected to ground. Then, I've set the GPA and GPB with pull-up resistors.
The script looks as follows:
import smbus
import time
mcp = 0x20
address_map = {
0x12: 'GPIOA', 0x13: 'GPIOB',
}
register_map = {value: key for key, value in address_map.iteritems()}
max_len = max(len(key) for key in register_map)
def print_values(bus):
for addr in address_map:
value = bus.read_byte_data(mcp, addr)
print "%-*s: 0x%02X" % (max_len, address_map[addr], value)
bus = smbus.SMBus(1)
bus.write_byte_data(mcp, int(12), 0xFF)
bus.write_byte_data(mcp, int(13), 0xFF)
while True:
print_values(bus)
time.sleep(0.1)
This will print out the GPA or GPB in Hex per bank, like so if nothing is connected:
>>> GPIOA = 0xFF
>>> GPIOB = 0xFF
But if I connect GPB0 to GND for example, it becomes:
>>> GPIOA = 0xFF
>>> GPIOB = 0xFE
So the question is, how can I from this Hex (0000 0000 1111 1110) to assigning a dictionary so that I can tell which pin is which?
You could use bitstruct.
>>> GPIOA = 0xf0
>>> gpa = list(reversed(bitstruct.unpack('b1'*8, chr(GPIOA))))
>>> gpa
[False, False, False, False, True, True, True, True]
>>> gpa[3]
False
>>> gpa[4]
True
>>> GPIOA = 0x18
>>> gpa = list(reversed(bitstruct.unpack('b1'*8, chr(GPIOA))))
>>> gpa[5]
False
>>> gpa[4]
True
>>> gpa
[False, False, False, True, True, False, False, False]
This allows you to access the bits by index. Unfortunately, you have to reverse the resulting tuple for the indexes to be right, but it does work.
There is also a manual way:
>>> gpa = [False]*8
>>> GPIOA = 0xf0
>>> for i in range(8):
... gpa[i] = bool((1 << i) & GPIOA)
...
>>> gpa
[False, False, False, False, True, True, True, True]
With either method, you can get it into a dictionary like this:
>>> names = ['GPIOA0', 'GPIOA1', 'GPIOA2', 'GPIOA3', 'GPIOA4', 'GPIOA5', 'GPIOA6', 'GPIOA7']
>>> gpadict = dict(zip(names, gpa))
>>> gpadict
{'GPIOA4': True, 'GPIOA5': True, 'GPIOA6': True, 'GPIOA7': True, 'GPIOA0': False, 'GPIOA1': False, 'GPIOA2': False, 'GPIOA3': False}
Related
I'm trying to use this code in Webots for one of the universal robots. The code works well until I try to the "ikResults" in line 49. The program is trying to use the least_squares.py but I'm getting the error for "'x0' is infeasible". This is the code I'm using:
import sys
import tempfile
try:
import ikpy
from ikpy.chain import Chain
import math
from controller import Supervisor
IKPY_MAX_ITERATIONS = 4
supervisor = Supervisor()
timeStep = int(4 * supervisor.getBasicTimeStep())
filename = None
with tempfile.NamedTemporaryFile(suffix='.urdf', delete=False) as file:
filename = file.name
file.write(supervisor.getUrdf().encode('utf-8'))
armChain = Chain.from_urdf_file(filename, active_links_mask=[False, True, True, True, True,
True, True, False, True, True, True])
motors = []
for link in armChain.links:
if 'joint' in link.name and link.name !="wrist_3_link_gripper_joint":
motor = supervisor.getDevice(link.name)
motor.setVelocity(1.0)
position_sensor = motor.getPositionSensor()
position_sensor.enable(timeStep)
motors.append(motor)
target = supervisor.getFromDef('TARGET')
arm = supervisor.getSelf()
while supervisor.step(timeStep) != -1:
targetPosition = target.getPosition()
armPosition = arm.getPosition()
x = targetPosition[0] - armPosition[0]
y = targetPosition[1] - armPosition[1]
z = targetPosition[2] - armPosition[2]
initial_position = [0] + [m.getPositionSensor().getValue() for m in motors] + [0]
ikResults = armChain.inverse_kinematics([x, y, z], max_iter=IKPY_MAX_ITERATIONS,
initial_position=initial_position)`
I've tried incrementing the iterations, changing the target's position, changing the status for the links in armChain (true or false), but nothing seemed to solve this issue. Reading other similar forums, it seems to do something with the bounds, not sure how to check on this.
I have the following sample DataFrame:
data = {'ID': ['14','15','16','18','19','20','21'],
'LOB': ["BNK", "BNK", "BNK", "BNK", "XYZ", "XYZ", "XYZ",],
'US_ALL': [False, False, True, True, True, False, True],
'US_50_States': [True, False, True, False, True, False, False],
'Primary': [False, True, True, False, True, False, True],
'Secondary': [True, False, True, False, False, True, True]}
I have the following defined function. My goal is to pass arguments based on the LOB column using conditional results.
def logic_for_bnk():
# Country and State Flag Logic
country_state_flag_conditions = [
(df['US_ALL'] == True) & (df['US_50_States'] == True),
(df['US_ALL'] == False) & (df['US_50_States'] == False),
(df['US_ALL'] == True) & (df['US_50_States'] == False),
(df['US_ALL'] == False) & (df['US_50_States'] == True),
]
country_state_flag_values = [
"""%keep(criteria="country = 'US' and states_50 = 1", desc="Keep only US and in 50 states customers");""",
"",
"""%keep(criteria="country = 'US'",desc="Keep customers in the US");""",
"""%keep(criteria="states_50 = 1", desc="Keep customers in 50 states");"""
]
df['Country_State_Logic'] = np.select(country_state_flag_conditions, country_state_flag_values, None)
# Primary and Secondary Logic
primary_secondary_flag_conditions = [
(df['Primary'] == True) & (df['Secondary'] == True),
(df['Primary'] == False) & (df['Secondary'] == False),
(df['Primary'] == True) & (df['Secondary'] == False),
(df['Primary'] == False) & (df['Secondary'] == True)
]
primary_secondary_flag_values = [
"""%keep(criteria="acct_ownership = '1' or acct_ownership = '2'",desc="Keep primary and secondary ownership");""",
"""%keep(criteria="acct_ownership = '1' or acct_ownership = '2'",desc="Keep primary and secondary ownership");""",
"""%keep(criteria="acct_ownership = '1'",desc="Keep primary ownership");""",
"""%keep(criteria="acct_ownership = '2'",desc="Keep secondary ownership");"""
]
df['Primary_Secondary_Logic'] = np.select(primary_secondary_flag_conditions, primary_secondary_flag_values, None)
# concatenating columns with SAS language output
df['SAS'] = df['Country_State_Logic'].astype(str) + df['Primary_Secondary_Logic'].astype(str)
# replacing all 'None' values with empty string ""
df.fillna("",inplace=True)
Following the function, I have the following which is where I am having issues. I'm trying to pass the logic_for_bnk() function into the following new column using np.where():
df['SAS Program Language'] = np.where((df['LOB'] == "BNK"), logic_for_bnk(),
np.where(df['LOB'] == "XYZ", "Pending XYZ Logic",
0))
I want my output to have 3 columns: ID, LOB, and SAS Program Language so I'm then adding the following drop argument to remove excess columns in the DataFrame:
df.drop(['US_ALL','US_50_States','Primary', 'Secondary','Country_State_Logic','Primary_Secondary_Logic'], axis = 1, inplace = True)
The issue here is that the resulting DataFrame contains 4 columns: ID LOB SAS SAS Program Language.
SAS is coming from the def logic_for_bnk() while SAS Program Language is coming from the new column I'm using along with np.where() arguments.
The SAS Program Language is passing None for BNK=LOB instead of the concatenated df['SAS'] and looks like this:
ID LOB SAS SAS Program Language
0 14 BNK %keep(criteria="states_50 = 1", desc="Keep cus... None
1 15 BNK %keep(criteria="acct_ownership = '1'",desc="Ke... None
2 16 BNK %keep(criteria="country = 'US' and states_50 =... None
3 18 BNK %keep(criteria="country = 'US'",desc="Keep cus... None
4 19 XYZ %keep(criteria="country = 'US' and states_50 =... Pending XYZ Logic
5 20 XYZ %keep(criteria="acct_ownership = '2'",desc="Ke... Pending XYZ Logic
6 21 XYZ %keep(criteria="country = 'US'",desc="Keep cus... Pending XYZ Logic
My goal is for the SAS Program Language column to have the concatenation defined in def logic_for_bnk() where LOB=BNK and have Pending XYZ Logic where LOB=XYZ.
Your function doesn't return anything! Add return df to the last line of your function. Other than that, it seems pd.DataFrame.apply is enough to create your desired output
sas_lang = df.LOB.apply(lambda x: logic_for_bnk() if x == 'BNK' else "Pending XYZ Logic")
sas_lang.name = 'SAS Program Language'
new_df = df.join(sas_lang)
Your desired output:
new_df[['ID', 'LOB', 'SAS Program Language']]
I'm trying to make a simple button that wiil set global animation preferences in maya.
The script is supposed to change the animation preferences of DEFAULT IN TANGENT , DEFAULT OUT TANGENT and DEFAULT TANGENT WEIGHT.
so far this is what I got:
import pymel.core as pm
def setBlockingPrefs():
pm.keyTangent(edit = True, g = True, itt = 'clamped')
pm.keyTangent(edit = True, g = True, ott = 'step')
pm.keyTangent(edit = True, g = True, weightedTangents = 1)
def setSpliningPrefs():
pm.keyTangent(edit = True, g = True, itt = 'auto')
pm.keyTangent(edit = True, g = True, ott = 'auto')
pm.keyTangent(edit = True, g = True, weightedTangents = 1)
I get no error with this code, but then, i get nothing at all, the preferences are not changed.
What am I missing?
Thank you
I would like to implement a Naive Bayes classifier for German. I am using NLTK and basically copying the code from the NLTK cookbook. I have put together a little corpus. I have a folder with two subfolders called neg and pos (like the movie review corpus). I am using a bag of word model.
This is how I process the corpus:
def bag_of_words(words):
return dict([(word, True) for word in words])
def bag_of_words_not_in_set(words, badwords):
return bag_of_words(set(words) - set(badwords))
def bag_of_words_without_stopwords(words):
badwords = stopwords.words("german")
return bag_of_words_not_in_set(words, badwords)
def label_feats_from_corpus(corp, feature_detector=bag_of_words_without_stopwords):
label_feats = collections.defaultdict(list)
for label in corp.categories():
for fileid in corp.fileids(categories=[label]):
feats = feature_detector(corp.words(fileids=[fileid]))
label_feats[label].append(feats)
return label_feats
def label_feats_from_corpus(corp, feature_detector=bag_of_words_without_stopwords):
label_feats = collections.defaultdict(list)
for label in corp.categories():
for fileid in corp.fileids(categories=[label]):
print (label + " >> " + fieldid)
feats = feature_detector(corp.words(fileids=[fileid]))
print(feats)
label_feats[label].append(feats)
return label_feats
reader = CategorizedPlaintextCorpusReader('D:/corpus/', r'.*\.txt', cat_pattern=r'(\w+)/*')
For
print (label + " >> " + fieldid)
print(feats)
I get
neg >> neg/fdfdg.txt
{'autorisierten': True, 'durchführen': True, 'Sicherheit': True, 'Fachwerkstatt': True, 'Arbeiten': True, 'in': True, 'Lassen': True, 'im': True, 'Interesse': True}
neg >> neg/fdffdf.txt
{'Arbeiten': True, 'Fachkenntnisse': True, 'gekennzeichnet': True, 'Verständnis': True, 'technisches': True, 'erfordern': True, 'Symbol': True}
neg >> neg/fgfdgdgdg.txt
{'Arbeiten': True, 'Spezialwerkzeuge': True, 'notwendig': True}
neg >> neg/fgff.txt
{'aussetzen': True, 'niemals': True, 'Flüssigkeiten': True, 'Regen': True, 'Salzwasser': True, 'Feuchtigkeit': True, 'Nässe': True, 'Batterien': True, ').': True}
which means that feature selection worked, right? (Irrespecitive of whether they already are the best features)
I am just interested at this point to correctly read in the corpus and get the bag-of-words feature selction right.
Thanks for any help and feedback!
I'm writing a Nagios plugin that calculate that calculate SSL score based on Qualys Server Rating Guide: https://www.ssllabs.com/projects/rating-guide/
To do it, I need to find out which is the worst/best protocol and weakest/strongest cipher that a server supported.
Here're my code that use sslyze:
from plugins import PluginOpenSSLCipherSuites
from nassl import SSLV2, SSLV3, TLSV1, TLSV1_1, TLSV1_2
shared_settings = {'certinfo': 'basic', 'starttls': None, 'resum': True, 'resum_rate': None, 'http_get': True, 'xml_file': '/tmp/example.com_443.xml', 'compression': True, 'tlsv1': True, 'targets_in': None, 'keyform': 1, 'hsts': None, 'sslv3': True, 'sslv2': True, 'https_tunnel': None, 'nb_retries': 4, 'heartbleed': True, 'sni': None, 'https_tunnel_host': None, 'regular': False, 'key': None, 'reneg': True, 'tlsv1_2': True, 'tlsv1_1': True, 'hide_rejected_ciphers': True, 'keypass': '', 'cert': None, 'certform': 1, 'timeout': 5, 'xmpp_to': None}
target = ('example.com', '1.2.3.4', 443, TLSV1_2)
cipher_plugin = PluginOpenSSLCipherSuites.PluginOpenSSLCipherSuites()
cipher_plugin._shared_settings = shared_settings
protocols = ['sslv2', 'sslv3', 'tlsv1', 'tlsv1_1', 'tlsv1_2']
for p in protocols:
cipher_result = cipher_plugin.process_task(target, p, None)
cipher_result = cipher_plugin.process_task
if any('Accepted' in c for c in cipher_result.get_txt_result()):
worst_protocol = p
break
for p in reversed(protocols):
cipher_result = cipher_plugin.process_task(target, p, None)
if any('Accepted' in c for c in cipher_result.get_txt_result()):
best_protocol = p
break
print(worst_protocol)
print(best_protocol)
ciphers = []
for protocol in ('sslv2', 'sslv3', 'tlsv1', 'tlsv1_1', 'tlsv1_2'):
cipher_result = cipher_plugin.process_task(target, protocol, None)
for e in cipher_result.get_txt_result():
if 'bits' in e:
ciphers.append(e.split()[1])
print(sorted(ciphers)[0])
print(sorted(ciphers)[-1])
but since there are a few loops, it took some time to complete.
With the following code, the execution time has been decreased from ~ 50s to ~ 40s. Is there anything else that I can turn to make it run faster?
protocols = ['sslv2', 'sslv3', 'tlsv1', 'tlsv1_1', 'tlsv1_2']
ciphers = []
for p in protocols[:]:
cipher_result = cipher_plugin.process_task(target, p, None)
for c in cipher_result.get_txt_result():
if 'rejected' in c:
protocols.remove(p)
if 'bits' in c:
ciphers.append(c.split()[1])
worst_protocol = protocols[0]
best_protocol = protocols[-1]
weakest_cipher_strength = min(ciphers)
strongest_cipher_strength = max(ciphers)