def test_protocol_load(self): a = Adapter() a.interfaces = Mock(return_value=[1, 2, 3]) p = Protocol(a) p.load() a.interfaces.assert_called_once_with() self.assertEqual(len(p.elements), 3)
def test_signal_load(self): a = Adapter() a.functionParameters = Mock(return_value=[1, 2, 3]) s = Signal(a, None) s.load() a.functionParameters.assert_called_once_with(None) self.assertEqual(len(s.elements), 3)
def get_all(): with DB() as database: rows = Adapter.adapt_query(database.execute('''SELECT * FROM questions''').fetchall()) # convert the data into a list of lists rows = Adapter.adapt_question_rows(database, rows) return [Question(*row) for row in rows] # instantiate questions list
def generateDataframe(self): current_adapter = Adapter(self.retrieveFileName()) current_dataframe = current_adapter.retrieve_dataframe() self.generatedDataframe.setText( current_dataframe.dataframe_to_string()) print("Will generate the Dataframe here")
def __init__(self): self.utils = Utils() self.adapter = Adapter() self.current_date = datetime.now().strftime("%Y-%m-%d") dir_name = os.path.dirname(__file__) self.files_dir_name = os.path.join(dir_name, 'file') self.make_xls_file()
def test_method_load(self): a = Adapter() a.functionParameters = Mock(side_effect=[[1, 2, 3], [4, 5]]) m = Method(a, None, None) m.load() a.functionParameters.assert_called_with(None) self.assertEqual(a.functionParameters.call_count, 2) self.assertEqual(len(m.elements), 5)
class Rotten: """ Contains API calls for communicating with the Rotten Tomatoes API. """ # Initializes with Rotten Tomatoes base URL. def __init__(self, base_url=u'http://api.rottentomatoes.com/api/public/v1.0/', api_key=u''): self.base_url = base_url self.api_key = api_key self.adapter = Adapter(base_url) # Gets/sets the base URL for connecting to the Rotten Tomatoes API. @property def base_url(self): return self.base_url # API Methods # Gets box office information for movies def box_office(self, limit=u'16', country=u'us'): path = self.base_url + u'lists/movies/box_office.json?apikey=%s&limit=%s&country=%s' % ( self.api_key, limit, country) result = self.adapter.get_path(path) return result # Gets the latest movies in theaters def in_theaters(self, page_limit=u'16', page=u'1', country=u'us'): path = self.base_url + u'lists/movies/in_theaters.json?apikey=%s&page_limit=%s&page=%s&country=%s' % ( self.api_key, page_limit, page, country) print path result = self.adapter.get_path(path) return result # Get movie opening information def opening(self, limit=u'16', country=u'us'): path = self.base_url + u'lists/movies/in_theaters.json?apikey=%s&limit=%s&country=%s' % ( self.api_key, limit, country) result = self.adapter.get_path(path) return result # Gets upcoming movies def upcoming(self, page_limit=u'16', page=u'1', country=u'us'): path = self.base_url + u'lists/movies/in_theaters.json?apikey=%s&page_limit=%s&page=%s&country=%s' % ( self.api_key, page_limit, page, country) result = self.adapter.get_path(path) return result
def main(): objects = [] dog = Dog() objects.append(Adapter(dog, dict(make_noise=dog.bark))) cat = Cat() objects.append(Adapter(cat, dict(make_noise=cat.meow))) for obj in objects: print("A {0} goes {1}".format(obj.name, obj.make_noise()))
def find(id): with DB() as database: row = Adapter.adapt_query(database.execute('''SELECT * FROM questions WHERE id = ?''', (id,)).fetchall()) try: row = tuple(Adapter.adapt_question_rows(database, row)[0]) except IndexError as error: return None return Question(*row)
def main(): # Keep a reference to the original stdin. We then replace # stdin with an empty stream. This is to protect against # code from accessing sys.stdin directly and consuming the # request content. stdin = sys.stdin sys.stdin = cStringIO.StringIO('') # Keep a reference to the original stdout. We then replace # stdout with stderr. This is to protect against code that # wants to use 'print' to output debugging. If stdout wasn't # protected, then anything output using 'print' would end up # being sent as part of the response itself and interfere # with the operation of the CGI protocol. stdout = sys.stdout sys.stdout = sys.stderr # Use the original stderr as is for errors. stderr = sys.stderr # Use a copy of the process environment as we want to # populate it with additional WSGI specific variables and # don't want to be polluting the process environment # variables with those as they would then be inherited by # sub processes. environ = dict(os.environ.items()) # Target WSGI script file is dictated by value of the # variable SCRIPT_FILENAME in CGI environment. filename = environ['SCRIPT_FILENAME'] # Create adapter for the WSGI application contained in # the WSGI script file. application = Script(filename) # Create CGI/WSGI bridge wrapping the 'application' entry # point in the target WSGI script file along with the # current request context. We only use the object once and # then the process exits, so doesn't matter it isn't # reusable or thread safe. adapter = Adapter(application, environ, stdin, stdout, stderr) # Execute the application. adapter.handle_request()
class Rotten: """ Contains API calls for communicating with the Rotten Tomatoes API. """ # Initializes with Rotten Tomatoes base URL. def __init__(self, base_url=u'http://api.rottentomatoes.com/api/public/v1.0/', api_key=u''): self.base_url = base_url self.api_key = api_key self.adapter = Adapter(base_url) # Gets/sets the base URL for connecting to the Rotten Tomatoes API. @property def base_url(self): return self.base_url # API Methods # Gets box office information for movies def box_office(self, limit=u'16', country=u'us'): path = self.base_url + u'lists/movies/box_office.json?apikey=%s&limit=%s&country=%s' % (self.api_key, limit, country) result = self.adapter.get_path(path) return result # Gets the latest movies in theaters def in_theaters(self, page_limit=u'16', page=u'1', country=u'us'): path = self.base_url + u'lists/movies/in_theaters.json?apikey=%s&page_limit=%s&page=%s&country=%s' % (self.api_key, page_limit, page, country) print path result = self.adapter.get_path(path) return result # Get movie opening information def opening(self, limit=u'16', country=u'us'): path = self.base_url + u'lists/movies/in_theaters.json?apikey=%s&limit=%s&country=%s' % (self.api_key, limit, country) result = self.adapter.get_path(path) return result # Gets upcoming movies def upcoming(self, page_limit=u'16', page=u'1', country=u'us'): path = self.base_url + u'lists/movies/in_theaters.json?apikey=%s&page_limit=%s&page=%s&country=%s' % (self.api_key, page_limit, page, country) result = self.adapter.get_path(path) return result
def gesture(): data = json.loads(request.data) x = data['x'] y = data['y'] action = json.loads(data['action']) if matrix != None: coords = convert_coords(matrix, x, y) Adapter.send_gesture(coords[0] * 222 / 275, coords[1], action) return jsonify(result='ok') else: return jsonify(result='cannot draw points'), 404
def test_service(): '''should had paired first''' def device_discover_services(device): # discovery services services = device.discover_services() import re for key in services.keys(): p = re.compile(">.*?<") xml = p.sub("><", services[key].replace("\n", "")) print "[ 0x%5x ]" % (key) print xml print def device_get_services(device): # get services from device_service import DeviceService from utils import bluetooth_uuid_to_string for serv in device.get_services(): service = DeviceService(serv) uuid = service.get_uuid() print "uuid:%s" % uuid print bluetooth_uuid_to_string(uuid) def device_get_uuids(device): from utils import bluetooth_uuid_to_string for uuid in device.get_uuids(): print uuid print bluetooth_uuid_to_string(uuid) from manager import Manager from adapter import Adapter from device import Device manager = Manager() adapter = Adapter(manager.get_default_adapter()) device = Device(adapter.get_devices()[0]) if adapter.get_devices(): device = Device(adapter.get_devices()[0]) else: print "after paired, should exists devices" print "device_get_services" device_get_services(device) print "device_discover_services" device_discover_services(device) print "device_get_uuids" device_get_uuids(device) mainloop = gobject.MainLoop() mainloop.run()
def __init__(self, name=DEFAULT_NAME, topic=None, message_type=None, sub_topic=None, sub_message_type=None, queue_size=10, **kwargs): Adapter.__init__(self, name, **kwargs) msg_type_class = utils.attempt_import(message_type, _myvars=vars()) self._js_publisher = ROSPublisher(name=name, topic=topic, message_type=msg_type_class, queue_size=queue_size, **kwargs) if sub_topic is not None and sub_message_type is not None: sub_msg_type_class = utils.attempt_import(sub_message_type, _myvars=vars()) self._js_subscriber = rospy.Subscriber(sub_topic, sub_msg_type_class, self.callback) if sub_topic is not None else None self._js = None self._new_js = JointState()
def __init__(self): self.settings = Settings() self.adapter = Adapter(self) self.project = Project(self) self.gui = Gui(self) self.file_manager = FileManager(self) self.terminal = Terminal(self) self.function_queue = queue.Queue() self.work_thread = threading.Thread(target=self.execute_functions) self.work_thread.daemon = True self.work_thread.start() self.measuring = False self.gui_thread_is_free = True
def background(): if 'img' in request.files: print 'get bg-image file' #request.files['img'].save('file.jpg') img = request.files['img'].read() elif request.data: print 'get bg-base64 image' data = json.loads(request.data) img = grab_image(data['img']) else: print 'no image' return jsonify(result='empty request'), 500 Adapter.send_background(img) return jsonify(result='bg updated'), 200
def getAdapter(): parser = argparse.ArgumentParser( description= 'A supervised machine learning approach using SVM to diagnose patients with breast cancer.' ) parser.add_argument('--kernel', dest='kernel', choices=['linear', 'rbf'], type=str, default=DEFAULT_KERNEL, help='Select Kernel of SVM') # parser.add_argument('-cv', dest='crossVal', type=int, default=DEFAULT_CROSSVAL, help='Select Cross Validation Value') # parser.add_argument('--train', dest='train', default=DEFAULT_TRAIN, type=bool, help='Enable or disable the training of the model') parser.add_argument( '--plot', dest='turnPlot', default=DEFAULT_PLOT, type=bool, help='Turn on the plot (Test erros x C panalty parameter)') parser.add_argument('-i', dest='interactions', default=DEFAULT_INTER, type=int, help='Set numbers of interactions for plot') args = parser.parse_args() adapter = Adapter(args.kernel, args.turnPlot, args.interactions) return adapter
def call_adapter(): # this is where the node would call the external adapter. data = request.get_json() if data == '': data = {} adapter = Adapter(data) return jsonify(adapter.result)
def call_adapter(): data = request.get_json() if data == '': data = {} adapter = Adapter(data) # print(jsonify(adapter.result)) return jsonify(adapter.result)
def getAdapter(): parser = argparse.ArgumentParser( description= 'An Artificial Neural Network model comparison using MLP and FBR to recognise spam.' ) parser.add_argument('--algorithm', dest='algorithm', choices=['mlp', 'fbr'], type=str, default=DEFAULT_ALGORITHM, help='Select Learning Algorithm') # # parser.add_argument('-cv', dest='crossVal', type=int, default=DEFAULT_CROSSVAL, help='Select Cross Validation Value') # # parser.add_argument('-n', dest='number_of_trees', type=int, default=DEFAULT_NUMBER_OF_TREES, help='Number of trees in forest') # # parser.add_argument('--train', dest='train', default=DEFAULT_TRAIN, type=bool, help='Enable or disable the training of the model') # # parser.add_argument('--plot', dest='confPlot', default=DEFAULT_PLOT ,type=bool, help='Change how confusion matrices are plot.') # # parser.add_argument('-b', dest='best', default=DEFAULT_BEST ,type=bool, help='Use only the 5 best features') # args = parser.parse_args() # adapter = Adapter(args.algorithm) return adapter
def __call__(self, resourceName): handle = self._factoryFunction(resourceName) if self._useLegacy: print('using legacy library.') return Adapter(handle) else: return alternativeLibrary.FileObject(handle)
def pay(self, type: str): if type == 'classic': print('Tarjeta Classic: Pagando sin ningún tipo de Seguridad') elif type in ('gold', 'black'): Adapter().pay(type) else: raise TypeError('card type value unknown')
def main(fileHandle, useLegacyLib=False): if useLegacyLib: print('using legacy library.') fileObject = Adapter(fileHandle) else: fileObject = alternativeLibrary.FileObject(fileHandle) for data in fileObject: print(data)
def call_adapter(): if request.method == 'GET': return 'true' data = json.loads(request.data) if data == '': data = {} adapter = Adapter(data) return jsonify(adapter.result)
def main(): #plug in sockets = Socket() adapter = Adapter(sockets) kettle = ElectricKettle(adapter) kettle.boil() return 0
def call_adapter(): data = request.get_json() if data == '': data = {} app.logger.debug(data) adapter = Adapter(data) ret = jsonify(adapter.result) app.logger.debug(adapter.result) return ret
def test_structure_load(self): a = Adapter() p1 = Mock() p1.type = 'Integer' p2 = Mock() p2.type = 'Boolean' p3 = Mock() p3.type = 'Interface2.Struct2' a.structureParameters = Mock(return_value=[p1, p2, p3]) i = Mock() i.name = 'Struct1' i.interface = Mock() i.interface.name = 'Interface1' Structure.structures = { 'Interface2.Struct2': None } s = Structure(a, i) s.load() a.structureParameters.assert_called_once_with(i) self.assertEqual(len(s.elements), 3)
class Facade: def __init__(self): self._db = DataBase() self._analytics = Analytics() self._adapter = Adapter(self._analytics) def get_data(self) -> List[str]: data_from_db = self._db.get_from_db() result = self._adapter.analyze_data(data_from_db) return result
def add(tup): entries, begin, end = tup adapter = Adapter() not_implemented_error_count = 0 error = 0 #print (begin,end) for entry in entries[begin : end]: try: adapter.insert(entry) except cql.apivalues.OperationalError: print sys.exc_info() print entry error += 1 if not_implemented_error_count + error > 0: print begin, end, not_implemented_error_count, error adapter.close()
def EnumerateAdapters(self): """Enumerate all storage adapters on the system returns: An array of object paths for storage adapters """ l = list() for i in self.iface.EnumerateAdapters(): obj = Adapter(i) l.append(obj) return l
def handle(event, context): body = event['body'] if body == None: print("NONE") data = json.loads(event['body']) print(data) adapter = Adapter(data) return { "body": json.dumps(adapter.result, indent=2), "statusCode": 200, "headers": { "Content-Type": "application/json", } }
def test_interface_load(self): a = Adapter() a.enumerations = Mock(return_value=[1, 2]) s1 = Mock() s1.name = 'name' s1.interface = Mock() s1.interface.name = 'name' a.structures = Mock(return_value=[s1]) f1 = Mock() f1.type = 'notification' f2 = Mock() f2.name = 'method' f2.type = 'request' f3 = Mock() f3.name = 'method' f3.type = 'response' a.functions = Mock(return_value=[f1, f2, f3]) i = Interface(a, None) i.load() a.enumerations.assert_called_once_with(None) a.structures.assert_called_once_with(None) a.functions.assert_called_once_with(None) self.assertEqual(len(i.elements), 5)
class Controller: def __init__(self): self.adapter = Adapter() def insert(self, entry): self.adapter.insert(entry) def get(self, key): m = re.search('(\w+)-(\d+)', key) if m: key = m.groups()[0] extra = int(m.groups()[1]) entry = self.adapter.get(key, extra) return [entry] if entry else None entries = self.adapter.getmany(key) if not entries: return None if len(entries) is 1: entries[0]['extra'] = None return [entries[0]] return entries
def getAdapter(): parser = argparse.ArgumentParser( description= 'A KNN and LDA approach for recognising handwriting numbers using the MNIST Dataset.' ) parser.add_argument('--algorithm', dest='algorithm', choices=['knn', 'lda', 'both'], type=str, default=DEFAULT_ALGORITHM, help='Select Learning Algorithm') parser.add_argument('-k', dest='k', type=int, default=DEFAULT_K_VALUE, help='K value for the KNN Algorithm') parser.add_argument('--train', dest='train', default=DEFAULT_TRAIN, type=bool, help='Enable or disable the training of the model') parser.add_argument('--proc', dest='proc', default=DEFAULT_PROCESSING, choices=['binaryLines', 'normalLines', 'None'], type=str, help='Type of image processing before training') parser.add_argument('--confplot', dest='confPlot', default=DEFAULT_PLOT, choices=['False', 'normalized', 'cases'], type=str, help='Change how confusion matrice are plot.') args = parser.parse_args() adapter = Adapter(args.algorithm, args.k, args.train, args.proc, args.confPlot) return adapter
def getAdapter(): parser = argparse.ArgumentParser(description='A Random Forests approach for plant species recognition.') parser.add_argument('--algorithm', dest='algorithm', choices=[''], type=str, default=DEFAULT_ALGORITHM, help='Select Learning Algorithm') parser.add_argument('-cv', dest='crossVal', type=int, default=DEFAULT_CROSSVAL, help='Select Cross Validation Value') parser.add_argument('-n', dest='number_of_trees', type=int, default=DEFAULT_NUMBER_OF_TREES, help='Number of trees in forest') parser.add_argument('--train', dest='train', default=DEFAULT_TRAIN, type=bool, help='Enable or disable the training of the model') parser.add_argument('--plot', dest='confPlot', default=DEFAULT_PLOT ,type=bool, help='Change how confusion matrices are plot.') parser.add_argument('-b', dest='best', default=DEFAULT_BEST ,type=bool, help='Use only the 5 best features') args = parser.parse_args() adapter = Adapter(args.crossVal, args.confPlot, args.number_of_trees, args.best) return adapter
def __init__(self): self.adapter = Adapter() self.seconds = 0 self.opcao = 0 self.filepath = ''
@dbus.service.method("org.bluez.Agent", in_signature="", out_signature="") def Cancel(self): print("Cancel") def create_device_reply(device): print("New device (%s)" % (device)) mainloop.quit() def create_device_error(error): print("Creating device failed: %s" % (error)) mainloop.quit() if __name__ == '__main__': dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() path = "/test/agent" agent = Agent(path, bus) from manager import Manager from adapter import Adapter adptr = Adapter(Manager().get_default_adapter()) adptr.register_agent(path, "") mainloop = gobject.MainLoop() mainloop.run()
def test_passive(): def on_device_found(adapter, address, values): print "on device found" print "adapter", adapter print "address", address print "values", values def on_device_created(adapter, dev_path): print "on device created" print "adapter" ,adapter print "dev_path", dev_path from manager import Manager from adapter import Adapter manager = Manager() adapter = Adapter(manager.get_default_adapter()) adapter.set_powered(True) adapter.set_discoverable(True) adapter.set_pairable(True) # print "adapter properties:\n %s" % adapter.get_properties() adapter.connect("device-found", on_device_found) adapter.connect("device-created", on_device_created) mainloop = gobject.MainLoop() mainloop.run()
def test_phone(): '''must had paired first, use xiaomi for test''' def get_device_supported_services(device): services = [] from utils import bluetooth_uuid_to_string for uuid in device.get_uuids(): if bluetooth_uuid_to_string(uuid) != None: services.append(bluetooth_uuid_to_string(uuid)) else: continue return services def send_file(device, files): ###please see the example in obex_agent.py pass def browse_device(device): ###please see the example in utils.py pass ### test phone audio def connect_phone_audio(device): from device import AudioSource from device import Control ###AudioSource if "AudioSource" not in get_device_supported_services(device): print "device not support AudioSource" return audiosource = AudioSource(device.object_path) ###when connect, voice switch from phone to my'pc if audiosource.get_state() == "disconnected": audiosource.connect() ###Control if "A/V_RemoteControlTarget" not in get_device_supported_services(device): print "device not support A/V control" return control = Control(device.object_path) if not control.get_connected(): return for i in range(10): control.volume_up() ###HandsFreeGateway from device import HandsfreeGateway from handsfree_agent import HandsfreeAgent if not "HandsfreeAudioGateway" in get_device_supported_services(device): print "device not support handsfree gateway" return hfg = HandsfreeGateway(device.object_path) HandsfreeAgent("/org/bluez/HandsfreeAgent") hfg.register_agent("/org/bluez/HandsfreeAgent") if hfg.get_state() == "disconnected": hfg.connect() def connect_phone_network(adapter, device): '''for my phone, it's nap''' from device import Network from adapter import NetworkServer if "NAP" not in get_device_supported_services(device): print "device not support NAP" return network = Network(device.object_path) server = NetworkServer(adapter.object_path) server.register("nap", "wlan0") network.connect("nap") def connect_phone_serial(adapter, device): pass from manager import Manager from adapter import Adapter from device import Device manager = Manager() adapter = Adapter(manager.get_default_adapter()) if adapter.get_devices(): device = Device(adapter.get_devices()[0]) else: print "after paired, should exists devices" send_file(device, ["/home/zhaixiang/debug"]) #connect_phone_audio(device) # connect_phone_network(adapter, device) mainloop = gobject.MainLoop() mainloop.run()
class Command(): def __init__(self): self._command = None self._api = ApiTwip(keys.CONSUMER_KEY, keys.CONSUMER_SECRET) self._adapter = Adapter() self._timeline = None def dispatch(self, command): self._command = command if self._command in COMMAND_TIMELINE: content = self._api.get_home_time_line() # pragma: no cover if content: self._timeline = self._adapter.create_timeline_object(content) # pragma: no cover cli_adapter = CliAdapter(self._timeline) # pragma: no cover cli_adapter.get_statuses() # pragma: no cover elif self._command in COMMAND_VERSION: print version # pragma: no cover elif self._command in COMMAND_EXIT: pass # pragma: no cover elif self._command in COMMAND_HELP: print COMMAND_HELP_TEXT # pragma: no cover elif self._command in COMMAND_MENTIONS: content = self._api.get_mentions() # pragma: no cover if content: self._timeline = self._adapter.create_timeline_object(content) # pragma: no cover cli_adapter = CliAdapter(self._timeline) # pragma: no cover cli_adapter.get_statuses() elif self._command in COMMAND_FV: content = self._api.get_favs() # pragma: no cover if content: self._timeline = self._adapter.create_timeline_object(content) # pragma: no cover cli_adapter = CliAdapter(self._timeline) # pragma: no cover cli_adapter.get_statuses() # pragma: no cover elif self._command in COMMAND_DM: content = self._api.get_direct_messages() # pragma: no cover if content: self._timeline = self._adapter.create_dm_timeline_object(content) # pragma: no cover cli_adapter = CliAdapter(self._timeline) # pragma: no cover cli_adapter.get_direct_messages() # pragma: no cover elif len(self._command) > 2: com = self._command[:2].strip() text = self._command[2:].strip() self._send_info(com, text) else: print COMMAND_HELP_TEXT def _send_info(self, com, text): if com in COMMAND_UPDATE: self._api.update_status(text) elif com in COMMAND_REPLY: if not self._timeline: print 'Timeline is empty. Execute first "ht" or "m" command' return cli_adapter = CliAdapter(self._timeline) c_id = text[:2].strip() text = text[2:] if not reg_exp_only_numbers(c_id): print 'Bad reply id. Only numbers between 0 and 19' return c_id = int(c_id) if c_id < 0 or c_id > 19: print 'Bad reply id. Range: 0..19' return status = cli_adapter.get_status_from_id(c_id) self._api.update_status(text=text, reply_to=status.id_str) elif com in COMMAND_RT: c_id = self._command[2:].strip() if not reg_exp_only_numbers(c_id): print 'Bad tweet id. Range 0..19' return if not self._timeline: print 'Timeline is empty. Execute first "ht" or "m" command' return c_id = int(c_id) if c_id < 0 or c_id > 19: print 'Bad reply id. Range: 0..19' return cli_adapter = CliAdapter(self._timeline) status = cli_adapter.get_status_from_id(c_id) self._api.retweet(tweet_id=status.id_str) elif com in COMMAND_FV: if not self._timeline: print 'Timeline is empty. Execute first "ht" or "m" command' return cli_adapter = CliAdapter(self._timeline) c_id = text[:2].strip() text = text[2:] if not reg_exp_only_numbers(c_id): print 'Bad favorite id. Only numbers between 0 and 19' return c_id = int(c_id) if c_id < 0 or c_id > 19: print 'Bad favorite id. Range: 0..19' return status = cli_adapter.get_status_from_id(c_id) self._api.create_fav(tweet_id=status.id_str) elif com in COMMAND_DM: temp_text = text.split(' ') if len(temp_text) < 2: print 'Ups! Something wrong with the dm command. Did you write the @<screen user name> and the <text>?' return if -1 == temp_text[0].find('@') or len(temp_text[0]) < 2: print 'I don\'t know who I will send the message. Please add the "@" to the twitter user name' return screen_name = temp_text[0].strip() screen_name = screen_name[1:] text = text[len(screen_name)+1:].strip() self._api.send_direct_message(text=text, screen_name=screen_name)
def __init__(self): self.adapter = Adapter()
def test_cat_adapter_shall_make_noise(self): cat = Cat() cat_adapter = Adapter(cat, make_noise=cat.meow) noise = cat_adapter.make_noise() expected_noise = "meow!" self.assertEqual(noise, expected_noise)
def test_dog_adapter_shall_make_noise(self): dog = Dog() dog_adapter = Adapter(dog, make_noise=dog.bark) noise = dog_adapter.make_noise() expected_noise = "woof!" self.assertEqual(noise, expected_noise)
def test_found_pair(): '''test_found_pair''' def on_device_found(adapter, address, values): print "address of found device \n %s " % address if address not in adapter.get_address_records(): print "values of found device \n %s " % values print "now create device" return adapter.create_device(address) else: # print "device already exists" if adapter.get_discovering(): print "stop discovery" adapter.stop_discovery() pass def on_device_created(adapter, dev_path): print "path of created device \n %s" % dev_path device = Device(dev_path) pair(device) def pair(device): from agent import Agent path = "/org/bluez/agent" agent = Agent(path) agent.set_exit_on_release(False) device.set_trusted(True) if not device.get_paired(): print "create paired device" adapter.create_paired_device(device.get_address(), path, "DisplayYesNo", create_paired_reply, create_paired_error) def create_paired_reply(device): print "succeed paired device (%s)" % (device) def create_paired_error(error): print "paired device failed: %s" % (error) from manager import Manager from adapter import Adapter from device import Device manager = Manager() adapter = Adapter(manager.get_default_adapter()) adapter.set_powered(True) adapter.set_discoverable(True) adapter.set_pairable(True) # print "adapter properties:\n %s" % adapter.get_properties() adapter.connect("device-found", on_device_found) adapter.connect("device-created", on_device_created) for dev in adapter.get_devices(): print "DEBUG", dev adapter.remove_device(dev) else: pass print "begin discovery \n" adapter.start_discovery() mainloop = gobject.MainLoop() mainloop.run()
def __init__(self): self._command = None self._api = ApiTwip(keys.CONSUMER_KEY, keys.CONSUMER_SECRET) self._adapter = Adapter() self._timeline = None
class Gui: def __init__(self): self.adapter = Adapter() self.seconds = 0 self.opcao = 0 self.filepath = '' def run(self): app = Tk() app.title("Ajustador de Legendas") app.geometry('380x180') self.labelText2 = StringVar() self.labelText2.set("") label2 = Label(app, textvariable=self.labelText2, height=2, fg='blue') label2.pack(side='top', padx=1, pady=1) labelText = StringVar() labelText.set("Segundos") label1 = Label(app, textvariable=labelText, height=2) label1.pack() custName= StringVar(None) self.entrada = Entry(app, textvariable=custName) self.entrada.pack() self.var = IntVar() R1 = Radiobutton(app, text="Atrasar legenda", variable=self.var, value=1,command=self.sel) R1.pack() R2 = Radiobutton(app, text="Adiantar legenda", variable=self.var, value=2,command=self.sel) R2.pack() button1 = Button(app, text="Adaptar", width=10, command = self.changeLabel) button1.pack(side='bottom', padx=10, pady=10) menubar = Menu(app) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Selecionar Legenda", command=self.filechoose) filemenu.add_separator() filemenu.add_command(label="Exit", command=app.quit) menubar.add_cascade(label="Arquivo", menu=filemenu) aboutmenu = Menu(menubar, tearoff=0) aboutmenu.add_command(label="O App", command=self.newWindow) menubar.add_cascade(label="Sobre", menu=aboutmenu) app.config(menu=menubar) app.mainloop() def changeLabel(self): try: stringInput = self.entrada.get() self.seconds = int(stringInput) if self.opcao == 0: self.notSelected() else: self.adapter.adjust(self.filepath, self.seconds,self.opcao) self.pronto() except ValueError: self.wrongValue() except IOError: #traceback.print_exc() self.missingFile() #except: #self.unknowError() return def sel(self): self.opcao = self.var.get() def pronto(self): tkMessageBox.showinfo("Status", "Pronto!") def missingFile(self): tkMessageBox.showinfo("Status", "Arquivo nao selecionado!") def wrongValue(self): tkMessageBox.showinfo("Status", "Por favor insira apenas numeros!") def notSelected(self): tkMessageBox.showinfo("Status", "Selecione adiantar ou atrasar a legenda.") def unknowError(self): tkMessageBox.showinfo("Status", "Erro desconhecido!") def filechoose(self): self.filepath = askopenfilename() if self.filepath != '': self.labelText2.set(ntpath.basename(self.filepath)) def newWindow(self): top = Toplevel() top.title("O App") top.geometry('380x80') labelText = StringVar() labelText.set("Aplicativo desenvolvido em Python por Estevao Fonseca") label1 = Label(top, textvariable=labelText, height=2) label1.pack(side='top', padx=10, pady=15) top.mainloop()
def test_human_adapter_shall_make_noise(self): human = Human() human_adapter = Adapter(human, make_noise=human.speak) noise = human_adapter.make_noise() expected_noise = "'hello'" self.assertEqual(noise, expected_noise)
def test_car_adapter_shall_make_very_loud_noise(self): car = Car() car_adapter = Adapter(car, make_noise=car.make_noise) noise = car_adapter.make_noise(10) expected_noise = "vroom!!!!!!!!!!" self.assertEqual(noise, expected_noise)
def test_adapter_prop(): from manager import Manager from adapter import Adapter manager = Manager() adapter = Adapter(manager.get_default_adapter()) from device import Device device_address = Device(adapter.get_devices()[0]).get_address() print "find device:\n %s" % adapter.find_device(device_address) print "remove device:\n %s" % adapter.remove_device(adapter.find_device(device_address)) # print "create device:\n %s" % adapter.create_device(device_address) print "get devices:\n %s" % adapter.get_devices() adapter.set_name("Long Wei's PC") print "get name:\n %s" % adapter.get_name() adapter.set_powered(True) print "get powered:\n %s" % adapter.get_powered() adapter.set_discoverable(True) print "get discoverable:\n %s" % adapter.get_discoverable() print "get discovering:\n %s" % adapter.get_discovering() adapter.set_discoverable_timeout(120) print "get discoverable_timeout:\n %s" % adapter.get_discoverable_timeout() adapter.set_pairable(True) print "get pairable:\n %s" % adapter.get_pairable() adapter.set_pairable_timeout(180) print "get pairable timeout:\n %s" % adapter.get_pairable_timeout() print "get class:\n %s" % adapter.get_class() print "get address:\n %s" % adapter.get_address() print "get uuids:\n %s" % adapter.get_uuids()
def __init__(self, base_url=u'http://api.rottentomatoes.com/api/public/v1.0/', api_key=u''): self.base_url = base_url self.api_key = api_key self.adapter = Adapter(base_url)
def s_connect(self, pattern): return self.dbus_method("Connect", pattern) def connect_fd(self, pattern): return self.dbus_method("ConnectFD", pattern) def s_disconnect(self, device): return self.dbus_method("Disconnect", device) if __name__ == "__main__": from manager import Manager from adapter import Adapter adapter = Adapter(Manager().get_default_adapter()) device = Device(adapter.get_devices()[0]) # print "Name:\n %s" % device.get_name() # device.set_alias("Long's Phone") # print "Alias:\n %s" % device.get_alias() # print "Paired:\n %s" % device.get_paired() # print "Adapter:\n %s" % device.get_adapter() # print "Connected:\n %s" % device.get_connected() # print "UUIDs:\n %s" % device.get_uuids() # print "Address:\n %s" % device.get_address() # print "Find Device:\n %s" %adapter.find_device(device.get_address()) # print "Services:\n %s" % device.get_services() # print "Class:\n %s" % device.get_class() # device.set_blocked(True)