How to get ATR of a smard card from HID omnilkey - python-2.7

I want to get ATR of the smartcard. I am using HID omnikey 5321. I am following this link "http://pyscard.sourceforge.net/user-guide.html#requesting-any-card"
so far i have tried:
>>>from smartcard.CardType import AnyCardType
>>>from smartcard.CardRequest import CardRequest
>>>from smartcard.util import toHexString
>>>
>>> cardtype = AnyCardType()
>>> cardrequest = CardRequest( timeout=1, cardType=cardtype )
>>> cardservice = cardrequest.waitforcard()
>>>
>>>>>> cardservice.connection.connect()
i am getting error at the
cardservice.connection.connect()
error like:
raise CardConnectionException('Unable to connect with ptotocol[pcscprotocol] + . '+ScardGetErrorMessage(hresult)
CardConnectionException: Unable to conenct the card with T0 or T1 . Card is not responding to reset.

Because You dont specify the reader to connect:
r=readers()
#r[Number of reader list].
cardservice.connection = r[0].createConnection()
cardservice.connection.connect()
A simple Example:
from __future__ import print_function
from smartcard.Exceptions import NoCardException
from smartcard.System import readers
from smartcard.util import toHexString
for reader in readers():
try:
connection = reader.createConnection()
connection.connect()
print(reader, toHexString(connection.getATR()))
except NoCardException:
print(reader, 'no card inserted')
import sys
if 'win32' == sys.platform:
print('press Enter to continue')
sys.stdin.read(1)
-Another Selecting Reader:
from __future__ import print_function
from smartcard.Exceptions import NoCardException
from smartcard.System import readers
from smartcard.util import toHexString
from smartcard.CardType import AnyCardType
from smartcard.CardRequest import CardRequest
cardtype = AnyCardType()
r=readers()
cardrequest = CardRequest( timeout=10, cardType=cardtype )
cardservice = cardrequest.waitforcard()
print('Available Readers:')
for i in range(len(readers())):
print('[',i+1,']',r[i])
if(len(readers()) < 1):
print("\nNO AVAILABLE READERS!\n")
else:
print("Select you Reader: (Ctrl+C to Exit)")
my_input = input()
selectReader = clamp(int(my_input)-1,0,len(readers()))
print('Selected: ',r[selectReader])
cardservice.connection = r[selectReader].createConnection()
cardservice.connection.connect()
try:
print('Card ATR:',toHexString(cardservice.connection.getATR()),file=f)
except:
print("Cant not Get ATR")
.
Full Information:
https://pyscard.sourceforge.io/pyscard-framework.html#framework-samples
https://github.com/LudovicRousseau/pyscard
https://pyscard.sourceforge.io/user-guide.html

In python, you can use the pyscard library to interact with smart cards, there is an example that should help you display the ATR at http://pyscard.sourceforge.net/pyscard-framework.html#framework-samples

Related

use of upload_to function when creating on object in django

here is my model in django :
import os
def upload_location_buy(instance, filename):
ext = filename.split('.')[-1]
filename = '%s.%s' % (instance.name+"_"+str(random.randint(1000, 9999)), ext)
print(os.path.join('uploads', filename))
return os.path.join('uploads', filename)
class Buy(models.Model):
pic_front = models.ImageField(blank=True, upload_to=upload_location_buy,default='')
When i try :
b = Buy(pic_front="appartement_a.jpg")
b.save()
it does nothing exception linking the current pic in the current path, so not using the function in the model.
And when i do :
b = Buy(pic_front=upload_location_buy("appartement_a.jpg"))
b.save()
it give me an error because it seems to need the instance.
TypeError: upload_location_buy() missing 1 required positional
argument: 'filename'
How to create a buy object, giving it a picture and using the upload_location_buy whend doing it without the admin ?
When i upload a pic in the admin it works.
how to give it the instance name or do it correctly ?
this is this script :
import sys
import os
import django
from django.core.exceptions import ObjectDoesNotExist
sys.path.append("../../../testproject")
os.environ["DJANGO_SETTINGS_MODULE"] = "testproject.settings"
django.setup()
from on_plan.models import Buy
Buy.objects.all().delete()
b = Buy(pic_front=upload_location_buy("appartement_a.jpg"))
b.save()
The script is in the same directory as the file "appartement_a.jpg".
-on_plan/
-testproject/
-import_script.py
-appartement_a.jpg
-manage.py
if i do a :
file_to_save = open('appartement_a.jpg', 'r').read()
b = Buy(pic_front=file_to_save)
b.save()
i have a:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
if i do a :
file_to_save = open('appartement_a.jpg', 'rb').read()
b = Buy(pic_front=file_to_save)
b.save()
i have a:
AttributeError: 'bytes' object has no attribute '_committed'
the solution is here:
import requests
import urllib.parse
import sys
import os
import django
import csv
import time
import random
from django.core.exceptions import ObjectDoesNotExist
sys.path.append("../../../sample_estate")
os.environ["DJANGO_SETTINGS_MODULE"] = "sample_estate.settings"
django.setup()
from django.core.files.base import File
from on_plan.models import Buy
file_to_save = open('appartement_a.jpg', 'rb')
b = Buy(pic_front=File(file_to_save))
b.save()
When you create a Buy object you need to pass file-obejct into pic_front attribute, but you try to pass only name of file.
from django.core.files.base import File
file_to_save = open('/path/to/appartement_a.jpg', 'r').read()
b = Buy(pic_front=File(file_to_save))
b.save()
If you get file from a form you may upload it like that:
b = Buy(pic_front=request.FILES['file'])
b.save()
Anyway pic_front expect to getting a file-object not string
More about this case

python populate.py wont populate my database

After writing the following code and expecting the output to be an updated database with random names, websites, etc., I get no error message and no updated database
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'First_project.settings')
import django
django.setup()
import random
from first_app.models import AccessRecord,Webpage,Topic
from faker import Faker
fakegen = Faker()
topics = ['Search','Social','Marketplace','News','Games']
def add_topic():
t = Topic.object.get_or_create(top_name=random.choice(topics))[0]
t.save()
return t
def populate(N=5):
for entry in range(N):
top = add_topic()
fake_url = fakegen.url()
fake_date = fakegen.date()
fake_name = fakegen.company()
webpg = webpage.objects.get_or_create(topic=top, url=fake_ur, name=fake_name)[0]
acc_rec = AccessRecord.object.get_or_create(name=webpg,date=fake_date)[0]
if __name__ == ' __main__':
print("populate")
populate(20)
print("populating complete!")
please what do I do?
i ran the whole code in my terminal and it populated the database

get "LogicError: explicit_context_dependent failed: invalid device context - no currently active context? " when running tensorRT in ROS

I have an inference code in TensorRT(with python). I want to run this code in ROS but I get the below error when trying to allocate buffer:
LogicError: explicit_context_dependent failed: invalid device context - no currently active context?
The code works well out of the ROS package. A ROS node publishes an image and the given code get the image to do inference. The inference code is shown below:
#!/usr/bin/env python
# Revision $Id$
import rospy
from std_msgs.msg import String
from cv_bridge import CvBridge
import cv2
import os
import numpy as np
import argparse
import torch
from torch.autograd import Variable
from torchvision import transforms
import torch.nn.functional as F
import torch._utils
from PIL import Image
from sensor_msgs.msg import Image as ImageMsg
import tensorrt as trt
import pycuda.driver as cuda
import pycuda.autoinit
import random
import sys
import common
import shutil
from itertools import chain
TRT_LOGGER = trt.Logger()
# cuda.init()
class ModelData(object):
def __init__(self):
self.MODEL_PATH = "./MobileNet_v2_Final.onnx" ## converted model from pytorch to onnx
self.batch_size = 1
self.num_classes = 3
self.engine = build_int8_engine(self.MODEL_PATH, self.batch_size)
self.context = self.engine.create_execution_context()
### ROS PART
self.bridge_ROS = CvBridge()
self.loop_rate = rospy.Rate(1)
self.pub = rospy.Publisher('Image_Label', String, queue_size=1)
print('INIT Successfully')
def callback(self, msg):
rospy.loginfo('Image received...')
cv_image = self.bridge_ROS.imgmsg_to_cv2(msg, desired_encoding="passthrough")
inputs, outputs, bindings, stream = common.allocate_buffers(context.engine)
[output] = common.do_inference(context, bindings=bindings, inputs=inputs, outputs=outputs, stream=stream, batch_size=effective_batch_size)
def listener(self):
rospy.Subscriber("chatter", ImageMsg, self.callback)
while not rospy.is_shutdown():
rospy.loginfo('Getting image...')
self.loop_rate.sleep()
def build_int8_engine(model_file, batch_size=32):
with trt.Builder(TRT_LOGGER) as builder, builder.create_network() as network, trt.OnnxParser(network, TRT_LOGGER) as parser:
builder.max_batch_size = batch_size
builder.max_workspace_size = common.GiB(1)
with open(model_file, 'rb') as model:
parser.parse(model.read(),)
return builder.build_cuda_engine(network)
if __name__ == '__main__':
rospy.init_node("listener", anonymous=True)
infer = ModelData()
infer.listener()
The error comes from the below class in stream = cuda.Stream():
#!/usr/bin/env python
# Revision $Id$
from itertools import chain
import argparse
import os
import pycuda.driver as cuda
import pycuda.autoinit
import numpy as np
import tensorrt as trt
# Simple helper data class that's a little nicer to use than a 2-tuple.
class HostDeviceMem(object):
def __init__(self, host_mem, device_mem):
self.host = host_mem
self.device = device_mem
def __str__(self):
return "Host:\n" + str(self.host) + "\nDevice:\n" + str(self.device)
def __repr__(self):
return self.__str__()
# Allocates all buffers required for an engine, i.e. host/device inputs/outputs.
def allocate_buffers(engine):
inputs = []
outputs = []
bindings = []
stream = cuda.Stream()
for binding in engine:
size = trt.volume(engine.get_binding_shape(binding)) * engine.max_batch_size
dtype = trt.nptype(engine.get_binding_dtype(binding))
# Allocate host and device buffers
host_mem = cuda.pagelocked_empty(size, dtype)
device_mem = cuda.mem_alloc(host_mem.nbytes)
# Append the device buffer to device bindings.
bindings.append(int(device_mem))
# Append to the appropriate list.
if engine.binding_is_input(binding):
inputs.append(HostDeviceMem(host_mem, device_mem))
else:
outputs.append(HostDeviceMem(host_mem, device_mem))
ctx.pop()
del ctx
return inputs, outputs, bindings, stream
# This function is generalized for multiple inputs/outputs.
# inputs and outputs are expected to be lists of HostDeviceMem objects.
def do_inference(context, bindings, inputs, outputs, batch_size=1):
# Transfer input data to the GPU.
[cuda.memcpy_htod_async(inp.device, inp.host, stream) for inp in inputs]
# [cuda.memcpy_htod(inp.device, inp.host) for inp in inputs]
# Run inference.
context.execute_async(batch_size=batch_size, bindings=bindings, stream_handle=stream.handle)
# context.execute(batch_size=batch_size, bindings=bindings)
# Transfer predictions back from the GPU.
[cuda.memcpy_dtoh_async(out.host, out.device, stream) for out in outputs]
# [cuda.memcpy_dtoh(out.host, out.device) for out in outputs]
# Synchronize the stream
stream.synchronize()
# Return only the host outputs.
return [out.host for out in outputs]
More info:
TensorRT: 6.1.5
Python: 2.7
rosversion: 1.14.3
rosdistro: melodic
You need to explicitly create Cuda Device and load Cuda Context in the worker thread i.e. your callback function, instead of using import pycuda.autoinit in the main thread, as follows
import pycuda.driver as cuda
import threading
def callback():
cuda.init()
device = cuda.Device(0) # enter your Gpu id here
ctx = device.make_context()
allocate_buffers() # load Cuda buffers or any other Cuda or TenosrRT operations
ctx.pop() # very important
if __name__ == "__main__":
worker_thread = threading.Thread(target=callback())
worker_thread.start()
worker_thread.join()
Note: do not forget to remove import pycuda.autoinit in both modules
This is also discussed in a question here
please init cuda.
As answers above.
import pycuda.driver as cuda in main.py or befor import cuda-XXX-process

python - telegram bot sendMessage in specific date

I am terribly new in python and my progress is like a snail:(
I want to make a telegram bot that send a message at specific date and time. I used apscheduler and telepot libraries for that. and this is my code:
import telepot
import sys
import time
from time import sleep
from datetime import datetime
from apscheduler.scheduler import Scheduler
import logging
bot = telepot.Bot("***")
logging.basicConfig()
sched = Scheduler()
sched.start()
exec_date = datetime(2017, 9, 12 ,1,51,0)
def handle(msg):
content_type,chat_type,chat_id = telepot.glance(msg)
print(content_type,chat_type,chat_id)
if content_type == 'text' :
bot.sendMessage(chat_id,msg['text'])
def sendSimpleText():
# content_type,chat_type,chat_id = telepot.glance(msg)
# print(content_type,chat_type,chat_id)
#
# if content_type == 'text' :
chat_id = telepot.
bot.sendMessage(chat_id,'faez')
def main():
job = sched.add_date_job(sendSimpleText, exec_date)
while True:
sleep(1)
sys.stdout.write('.'); sys.stdout.flush()
# bot.message_loop(handle)
# # job = sched.add_date_job(sendSimpleText, '2017-09-11 21:35:00', ['testFuckBot'])
# while True:
# time.sleep(10)
if __name__ == '__main__':
main()
my question is what do I pass to sendSimpleText as argument in add_date_job? in this line:
job = sched.add_date_job(sendSimpleText, exec_date)
I know that msg is the message that user is typed so for add_date_job I have nothing?
You are used an old (2.1.2) version of APScheduler.
New version has a new syntax.
A function add_date_job no more available.
This is a worked solution for you:
import telepot
import sys
import time
from datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler
from telepot.loop import MessageLoop
import logging
bot = telepot.Bot("***YOUR_BOT_TOKEN***")
logging.basicConfig()
sched = BackgroundScheduler()
exec_date = datetime(2017, 9, 12 ,3,5,0)
def handle(msg):
content_type,chat_type,chat_id = telepot.glance(msg)
print(content_type,chat_type,chat_id)
if content_type == 'text' :
bot.sendMessage(chat_id,msg['text'])
def sendSimpleText(chat_id):
bot.sendMessage(chat_id,'faez')
def main():
MessageLoop(bot, handle).run_as_thread()
job = sched.add_job(sendSimpleText, run_date=exec_date, args=['**YOUR_TELEGRAM_ID**'])
while True:
time.sleep(1)
sys.stdout.write('.'); sys.stdout.flush()
if __name__ == '__main__':
sched.start()
main()

Vectorizing Files using sklearn

I am trying to read 100 training files and vectorize them using sklean. The contents of these files are word representing system calls. Once vectorized, I would like to print the vectors out.
My first attempt was the following:
import re
import os
import sys
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
import numpy as np
import numpy.linalg as LA
trainingdataDir = 'C:\data\Training data'
def readfile():
for file in os.listdir(trainingdataDir):
trainingfiles = os.path.join(trainingdataDir, file)
if os.path.isfile(trainingfiles):
data = open(trainingfiles, "rb").read()
return data
train_set = [readfile()]
vectorizer = CountVectorizer()
transformer = TfidfTransformer()
trainVectorizerArray = vectorizer.fit_transform(train_set).toarray()
print 'Fit Vectorizer to train set', trainVectorizerArray
However, this only returns the vector for the last file.
I concluded that the print function should be placed in the for loop. So the second attempt:
def readfile():
for file in os.listdir(trainingdataDir):
trainingfiles = os.path.join(trainingdataDir, file)
if os.path.isfile(trainingfiles):
data = open(trainingfiles, "rb").read()
trainVectorizerArray = vectorizer.fit_transform(data).toarray()
print 'Fit Vectorizer to train set', trainVectorizerArray
However, this does not return anything.
Could you please assist me with this? Why am I not able to see the vectors being printed out?
The issue was because the list of data sets used to vectorize was empty. I managed to vectorize a set of 100 files. I first opened the files, then read each file and finally added them to a list. The list of data set is then used to by the 'tfidf_vectorizer'
import re
import os
import sys
import numpy as np
import numpy.linalg as LA
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
trainingdataDir = 'C:\\data\\Training data'
tfidf_vectorizer = TfidfVectorizer()
transformer = TfidfTransformer()
def readfile(trainingdataDir):
train_set = []
for file in os.listdir(trainingdataDir):
trainingfiles = os.path.join(trainingdataDir, file)
if os.path.isfile(trainingfiles):
data = open(trainingfiles, 'r')
data_set=str.decode(data.read())
train_set.append(data_set)
return train_set
tfidf_matrix_train = tfidf_vectorizer.fit_transform(readfile(trainingdataDir))
print 'Fit Vectorizer to train set',tfidf_matrix_train
print "cosine scores ==> ",cosine_similarity(tfidf_matrix_train[0:1], tfidf_matrix_train)