def receive_request(self, msg, content): ''' If a "request" message is received, decode the task and the content and call the appropriate function to prepare the response. A reply "tell" message is then sent back. ''' content_list = cast(KQMLList, content) task_str = content_list.get(0).toString().upper() if task_str == 'ONT::PERFORM': subtask = cast(KQMLList,content_list.getKeywordArg(':content')) subtask_str = subtask.get(0).toString().upper() if subtask_str == 'ONT::BUILD-MODEL': reply_content = self.respond_build_model(content_list) elif subtask_str == 'ONT::EXPAND-MODEL': reply_content = self.respond_expand_model(content_list) else: self.error_reply(msg, 'unknown request subtask ' + subtask_str) return else: self.error_reply(msg, 'unknown request task ' + task_str) return reply_msg = KQMLPerformative('reply') reply_msg.setParameter(':content', cast(KQMLObject, reply_content)) self.reply(msg, reply_msg)
def on_view(self, instance, view): if self._old_view is not None: # XXX probably broken layout = cast(LinearLayout, self._old_view.getParent()) layout.removeView(self._old_view) self._old_view = None if view is None: return x, y, w, h = self._get_view_bbox() # XXX we assume it's the default layout from main.xml # It could break. parent = cast(LinearLayout, PythonActivity.mView.getParent()) parent.addView(view, 0, LayoutParams(w, h)) # we need to differenciate if there is interaction with our holder or # not. # XXX must be activated only if the view is displayed on the screen! PythonActivity.mView.setInterceptTouchListener(self._listener) view.setX(x) view.setY(y) self._old_view = view
def build(self): global SPORT game = CrazyBotGame() if Hardware is not None: try: import android import android.activity # noqa # test for an intent passed to us PythonActivity = autoclass('org.renpy.android.PythonActivity') UsbManager = autoclass('android.hardware.usb.UsbManager') UsbSerialPort = autoclass('com.hoho.android.usbserial.driver.UsbSerialPort') Context = autoclass('android.content.Context') activity = PythonActivity.mActivity intent = activity.getIntent() # intent_data = intent.getData() device = cast('android.hardware.usb.UsbDevice', intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)) print device Cp21xxSerialDriver = autoclass('com.hoho.android.usbserial.driver.Cp21xxSerialDriver') driver = Cp21xxSerialDriver(device) print driver manager = cast('android.hardware.usb.UsbManager', activity.getSystemService(Context.USB_SERVICE)) print manager port = cast('com.hoho.android.usbserial.driver.UsbSerialPort', driver.getPorts().get(0)) print port connection = cast('android.hardware.usb.UsbDeviceConnection', manager.openDevice(device)) print connection port.open(connection) port.setParameters(57600, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE) SPORT = port except Exception, e: print e game.device = "E " + str(e)
def receive_request(self, msg, content): ''' If a "request" message is received, decode the task and the content and call the appropriate function to prepare the response. A reply "tell" message is then sent back. ''' content_list = cast(KQMLList, content) task_str = content_list.get(0).toString().upper() if task_str == 'ONT::PERFORM': subtask = cast(KQMLList,content_list.getKeywordArg(':content')) subtask_str = subtask.get(0).toString().upper() if subtask_str == 'ONT::IS-DRUG-TARGET': reply_content = self.respond_is_drug_target(content_list) elif subtask_str == 'ONT::FIND-TARGET-DRUG': reply_content = self.respond_find_target_drug(content_list) elif subtask_str == 'ONT::FIND-DISEASE-TARGETS': reply_content = self.respond_find_disease_targets(content_list) elif subtask_str == 'ONT::FIND-TREATMENT': reply_content = self.respond_find_treatment(subtask) if reply_content is None: self.respond_dont_know(msg, '(ONT::A X1 :instance-of ONT::DRUG)') return else: self.error_reply(msg, 'unknown request subtask ' + subtask_str) return else: self.error_reply(msg, 'unknown request task ' + task_str) return reply_msg = KQMLPerformative('reply') reply_msg.setParameter(':content', cast(KQMLObject, reply_content)) self.reply(msg, reply_msg)
def receive_request(self, msg, content): ''' If a "request" message is received, decode the task and the content and call the appropriate function to prepare the response. A reply "tell" message is then sent back. ''' print msg content_list = cast(KQMLList, content) task_str = content_list.get(0).toString().upper() if task_str == 'ONT::PERFORM': subtask = cast(KQMLList,content_list.getKeywordArg(':content')) subtask_str = subtask.get(0).toString().upper() subtask.remove(0) arguments = self.request_arguments(subtask) if subtask_str == 'ONT::VERSION': reply_content = self.respond_version() elif subtask_str == 'ONT::PARSE': reply_content = self.respond_parse(arguments) elif subtask_str == 'ONT::START': reply_content = self.respond_start(arguments) elif subtask_str == 'ONT::STATUS': reply_content = self.respond_status(arguments) elif subtask_str == 'ONT::STOP': reply_content = self.respond_stop(arguments) else: message = '"'+'unknown request subtask ' + subtask_str + '"' self.error_reply(msg,message) return else: message = '"'+'unknown request task ' + task_str + '"' self.error_reply(msg,message) return reply_msg = KQMLPerformative('reply') reply_msg.setParameter(':content', cast(KQMLObject, reply_content)) self.reply(msg, reply_msg)
def _send(self, **kwargs): intent = Intent(Intent.ACTION_SEND) intent.setType('text/plain') recipient = kwargs.get('recipient') subject = kwargs.get('subject') text = kwargs.get('text') create_chooser = kwargs.get('create_chooser') if recipient: intent.putExtra(Intent.EXTRA_EMAIL, [recipient]) if subject: android_subject = cast('java.lang.CharSequence', AndroidString(subject)) intent.putExtra(Intent.EXTRA_SUBJECT, android_subject) if text: android_text = cast('java.lang.CharSequence', AndroidString(text)) intent.putExtra(Intent.EXTRA_TEXT, android_text) if create_chooser: chooser_title = cast('java.lang.CharSequence', AndroidString('Send message with:')) activity.startActivity(Intent.createChooser(intent, chooser_title)) else: activity.startActivity(intent)
def share_clicked(self, touch): from modules.core.android_utils import LogTestFairy action = touch.key Logger.info('ShareDialog: %s clicked' % action) LogTestFairy('Share post on %s' % action) from modules.core.tempstorage import get_temp_folder_prefix fname = get_temp_folder_prefix() + 'share.jpg' Logger.info('ShareDialog: Storing image to %s' % fname) try: self.item.texture.save(fname) except: Logger.info('ShareDialog: failed Storing %s' % fname) self.dispatch('on_close') return # make sure everyone can access it Logger.info('ShareDialog: Done Storing %s' % fname) provider = self.get_key_in_providers(action) from kivy import platform if platform == 'ios': from pyobjus import autoclass, objc_str ObjcClass = autoclass('ShareViewControllerINDR') self.o_instance = ObjcClass.alloc().init() self.o_instance.aTitle = objc_str(SHARE_LINK) self.o_instance.aFileName = objc_str(fname) self.o_instance.aApp = objc_str(action) self.o_instance.aURL = objc_str('http://insiderr.com') self.o_instance.shareImagePost() elif platform == 'android': from jnius import autoclass, cast AndroidString = autoclass('java.lang.String') Uri = autoclass('android.net.Uri') # start android intent stuff File = autoclass('java.io.File') sharedFile = File(fname) phototUri = Uri.fromFile(sharedFile) Intent = autoclass('android.content.Intent') shareIntent = Intent(Intent.ACTION_SEND) shareIntent.setType("image/*") shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) if provider: shareIntent.setPackage(provider) if 'facebook' in action: shareIntent.putExtra(Intent.EXTRA_TEXT, AndroidString("http://insiderr.com")) else: shareIntent.putExtra(Intent.EXTRA_TEXT, AndroidString(SHARE_LINK)) shareIntent.putExtra("sms_body", AndroidString(SHARE_LINK)) shareIntent.putExtra(Intent.EXTRA_STREAM, cast('android.os.Parcelable', phototUri)) PythonActivity = autoclass('org.renpy.android.PythonActivity') theActivity = PythonActivity.mActivity chooser_title = cast('java.lang.CharSequence', AndroidString('Share Via')) theActivity.startActivity(Intent.createChooser(shareIntent, chooser_title)) self.dispatch('on_close') LogTestFairy('Shared post successfully')
def remove_webview(self, *args): Logger.info('removing webview') from jnius import cast from jnius import autoclass webview = cast('android.widget.AbsoluteLayout', self._webview) webviewparent = webview.getParent() linearlayout = cast('android.widget.LinearLayout', webviewparent) linearlayout.removeView(webview) self._localserve.dispatch('on_webview_removed')
def createBeamUris(self, event): for x in range(0,5): print 'createBeams' if not self.changed: context = PythonActivity.mActivity currentApp = File((cast(mContext, context)).getPackageResourcePath()) self.uris[0] = cast(Uri, Uri.fromFile(currentApp)) print Uri.decode(self.uris[0].getEncodedPath()) return self.uris
def is_available(): if platform == 'android': from jnius import autoclass, cast PythonActivity = autoclass('org.renpy.android.PythonActivity') theActivity = cast('com.insiderr.uix.InsiderrActivity', PythonActivity.mActivity) Context = autoclass('android.content.Context') connectivityManager = cast( 'android.net.ConnectivityManager', theActivity.getSystemService(Context.CONNECTIVITY_SERVICE)) activeNetworkInfo = connectivityManager.getActiveNetworkInfo() return activeNetworkInfo is not None and activeNetworkInfo.isConnected() return True
def do_share(self, data, title): if platform != 'android': return from jnius import autoclass, cast JS = autoclass('java.lang.String') Intent = autoclass('android.content.Intent') sendIntent = Intent() sendIntent.setAction(Intent.ACTION_SEND) sendIntent.setType("text/plain") sendIntent.putExtra(Intent.EXTRA_TEXT, JS(data)) PythonActivity = autoclass('org.kivy.android.PythonActivity') currentActivity = cast('android.app.Activity', PythonActivity.mActivity) it = Intent.createChooser(sendIntent, cast('java.lang.CharSequence', JS(title))) currentActivity.startActivity(it)
def do_share(self): if platform != 'android': return from jnius import autoclass, cast Intent = autoclass('android.content.Intent') sendIntent = Intent() sendIntent.setAction(Intent.ACTION_SEND) sendIntent.putExtra(Intent.EXTRA_TEXT, self.get_URI()) sendIntent.setType("text/plain"); PythonActivity = autoclass('org.kivy.android.PythonActivity') currentActivity = cast('android.app.Activity', PythonActivity.mActivity) JS = autoclass('java.lang.String') it = Intent.createChooser(sendIntent, cast('java.lang.CharSequence', JS("Share Bitcoinaddress"))) currentActivity.startActivity(it)
def share(self, data=None): if platform == 'android': if data: PythonActivity = autoclass('org.renpy.android.PythonActivity') Intent = autoclass('android.content.Intent') String = autoclass('java.lang.String') intent = Intent() intent.setAction(Intent.ACTION_SEND) intent.putExtra(Intent.EXTRA_TEXT, cast('java.lang.CharSequence', String(data))) intent.setType('text/plain') currentActivity = cast('android.app.Activity', PythonActivity.mActivity) currentActivity.startActivity(intent)
def _open_file(self, **kwargs): ''' Running Android Activity is non-blocking and the only call that blocks is onActivityResult running in GUI thread .. versionadded:: 1.4.0 ''' # set up selection handler # startActivityForResult is async # onActivityResult is sync self._handle_selection = kwargs.pop( 'on_selection', self._handle_selection ) # create Intent for opening file_intent = Intent(Intent.ACTION_GET_CONTENT) file_intent.setType('*/*') file_intent.addCategory( Intent.CATEGORY_OPENABLE ) # bind a function for a response from filechooser activity activity.bind(on_activity_result=self._on_activity_result) # start a new activity from PythonActivity # which creates a filechooser via intent mActivity.startActivityForResult( Intent.createChooser(file_intent, cast( 'java.lang.CharSequence', String("FileChooser") )), self.select_code )
def ready(self): perf = KQMLPerformative('tell') content = KQMLList() content.add('module-status') content.add('ready') perf.setParameter(':content', cast(KQMLObject, content)) self.send(perf)
def build (self): if(myBTA.isEnabled() == False): intent = Intent() intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE) myActivity = cast('android.app.Activity', PythonActivity.mActivity) myActivity.startActivity(intent) return sm
def import_pyjnius(): """ PyJNIus can only be imported once per Python interpreter and one must set the classpath before importing... """ # Check if autoclass is already imported... if not jnius_config.vm_running: # Tested on Ubuntu 16.04 64bit with openjdk-8 JDK and JRE installed: # sudo apt install openjdk-8-jdk-headless openjdk-8-jre-headless # Set JAVA_HOME for this session try: os.environ['JAVA_HOME'] except KeyError: os.environ['JAVA_HOME'] = '/usr/lib/jvm/java-8-openjdk-amd64/' # Set path and import jnius for this session from jnius import autoclass elif hasattr(jnius_config, 'classpath_show_warning') and not jnius_config.classpath_show_warning: from jnius import autoclass # Warning already had shown. It is enough to show it only once! else: import sys from jnius import cast, autoclass class_loader = autoclass('java.lang.ClassLoader') cl = class_loader.getSystemClassLoader() ucl = cast('java.net.URLClassLoader', cl) urls = ucl.getURLs() cp = ':'.join(url.getFile() for url in urls) jnius_config.classpath_show_warning = False print('Warning: PyJNIus is already imported with the following classpath: {0} Please check if it is ok!'. format(cp), file=sys.stderr) # Return autoclass for later use... return autoclass
def take_picture(self): intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) self.last_fn = self.get_filename() self.uri = Uri.parse('file://' + self.last_fn) self.uri = cast('android.os.Parcelable', self.uri) intent.putExtra(MediaStore.EXTRA_OUTPUT, self.uri) PythonActivity.mActivity.startActivityForResult(intent, 0x123)
def getAllAps(): ''' Returns all applications installed [{'packageName':packageName, 'sourceDir':sourceDirectory}, etc] ''' infos = [] pythonService = autoclass("org.renpy.android.PythonService") PackageManager= autoclass("android.content.pm.PackageManager") ApplicationInfo= autoclass("android.content.pm.ApplicationInfo") activity = cast("android.app.Service", pythonService.mService) pm = activity.getPackageManager() packages = pm.getInstalledApplications(PackageManager.GET_META_DATA) for appNb in range(packages.size()): appInfo = packages.get(appNb) packageName = appInfo.packageName sourceDir = appInfo.sourceDir dataDir = appInfo.dataDir processName = appInfo.processName publicSourceDir = appInfo.publicSourceDir sharedLibraryFiles = appInfo.sharedLibraryFiles packagePerms = pm.getPackageInfo(appInfo.packageName, PackageManager.GET_PERMISSIONS) requestedPermissions = packagePerms.requestedPermissions permissions = [] if requestedPermissions != None: for i in range(len(requestedPermissions)): permissions.append(requestedPermissions[i]) infos.append({"packageName":packageName, "sourceDir":sourceDir, "dataDir":dataDir, "processName":processName, "publicSourceDir":publicSourceDir, "sharedLibraryFiles":sharedLibraryFiles, "permissions":permissions, }) return infos
def open_url(url): ''' Open a webpage in the default Android browser. ''' intent = Intent() intent.setAction(Intent.ACTION_VIEW) intent.setData(Uri.parse(url)) currentActivity = cast('android.app.Activity', context) currentActivity.startActivity(intent)
def __init__(self): super(BarometerSensorListener, self).__init__() service = activity.getSystemService(Context.SENSOR_SERVICE) self.SensorManager = cast('android.hardware.SensorManager', service) self.sensor = self.SensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE) self.value = None
def _process_purchase(self): Logger.info('in purchase') if not netcheck.connection_available(): Logger.info('no net avaiable') netcheck.ask_connect(self._connection_callback) elif not self.setup_complete: Logger.info('setup not complete') self._setup() else: Logger.info('doing the purchase') Logger.info(str(self.purchase_requested)) if self.purchase_requested is not None: sku = self.purchasing = self.purchase_requested else: self.purchasing = self.purchase_requested = None Logger.info('returning for no good reason') return if sku not in self.skus: raise AttributeError('The sku is not in the skus you initialized with') Logger.info('Starting purchase workflow for ' + sku) c = cast('android.app.Activity', context) r = self.r_code p = _OnPurchaseFinishedListener(self._purchase_finished) _protect_callback(p) self.helper.launchPurchaseFlow(c, sku, r, p)
def get_scaled_icon(icon): """ icon : name of icon file (png) without extension this function assumes that a 'Drawable' was regiseted, (see original post) it should be possible to create a bitmap dynamically, using a bitmap factory. Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image); """ Dimen = autoclass("android.R$dimen") Bitmap = autoclass("android.graphics.Bitmap") PythonService = autoclass('org.renpy.android.PythonService') service = PythonService.mService Drawable = autoclass("{}.R$drawable".format(service.getPackageName())) scaled_icon = getattr(Drawable, icon) scaled_icon = cast("android.graphics.drawable.BitmapDrawable", service.getResources().getDrawable(scaled_icon)) scaled_icon = scaled_icon.getBitmap() res = service.getResources() height = res.getDimension(Dimen.notification_large_icon_height) width = res.getDimension(Dimen.notification_large_icon_width) return Bitmap.createScaledBitmap(scaled_icon, width, height, False)
def ShareActivity(text, title=None): if not title: title = 'Share Via' if platform == 'android': try: from jnius import autoclass, cast AndroidString = autoclass('java.lang.String') Uri = autoclass('android.net.Uri') # start android intent stuff Intent = autoclass('android.content.Intent') shareIntent = Intent(Intent.ACTION_SEND) shareIntent.setType("text/plain") shareIntent.putExtra(Intent.EXTRA_TEXT, AndroidString(text)) PythonActivity = autoclass('org.renpy.android.PythonActivity') theActivity = PythonActivity.mActivity chooser_title = cast('java.lang.CharSequence', AndroidString(title)) theActivity.startActivity(Intent.createChooser(shareIntent, chooser_title)) except: print 'Failed sharing text -- %s' % text pass elif platform == 'ios': from pyobjus import autoclass, objc_str ObjcClass = autoclass('ShareViewControllerINDR') o_instance = ObjcClass.alloc().init() if not title: title = '' o_instance.aTitle = objc_str(title) o_instance.aApp = objc_str('link') o_instance.aURL = objc_str(text) o_instance.shareImagePost() else: print 'Sharing: %s -- %s' % (title, text)
def getSimState(): ''' Returns a string indicating the state of the default SIM card Returns None if an error ''' try: status="?" mContext = autoclass('android.content.Context') pythonActivity = autoclass('org.renpy.android.PythonService') TelephonyManager = autoclass('android.telephony.TelephonyManager') telephonyManager = cast('android.telephony.TelephonyManager', pythonActivity.mService.getSystemService(mContext.TELEPHONY_SERVICE)) simState = telephonyManager.getSimState() if simState == TelephonyManager.SIM_STATE_UNKNOWN: status = "unknown" elif simState == TelephonyManager.SIM_STATE_ABSENT: status = "absent" elif simState == TelephonyManager.SIM_STATE_PIN_REQUIRED: status = "pin_required" elif simState == TelephonyManager.SIM_STATE_PUK_REQUIRED: status = "puk_required" elif simState == TelephonyManager.SIM_STATE_NETWORK_LOCKED: status = "network_locked" elif simState == TelephonyManager.SIM_STATE_READY: status = "ready" return status except Exception,e: return None
def user_select_image(callback): """Open Gallery Activity and call callback with absolute image filepath of image user selected. None if user canceled. """ # PythonActivity.mActivity is the instance of the current Activity # BUT, startActivity is a method from the Activity class, not from our # PythonActivity. # We need to cast our class into an activity and use it currentActivity = cast('android.app.Activity', PythonActivity.mActivity) # Forum discussion: https://groups.google.com/forum/#!msg/kivy-users/bjsG2j9bptI/-Oe_aGo0newJ def on_activity_result(request_code, result_code, intent): if request_code != RESULT_LOAD_IMAGE: Logger.warning('user_select_image: ignoring activity result that was not RESULT_LOAD_IMAGE') return try: if result_code == Activity.RESULT_CANCELED: Clock.schedule_once(lambda dt: callback(None), 0) return if result_code != Activity.RESULT_OK: # This may just go into the void... raise NotImplementedError('Unknown result_code "{}"'.format(result_code)) selectedImage = intent.getData() # Uri filePathColumn = [MediaStore_Images_Media_DATA] # String[] # Cursor cursor = currentActivity.getContentResolver().query(selectedImage, filePathColumn, None, None, None) cursor.moveToFirst() # int columnIndex = cursor.getColumnIndex(filePathColumn[0]) # String picturePath = cursor.getString(columnIndex) cursor.close() Logger.info('android_ui: user_select_image() selected %s', picturePath) # This is possibly in a different thread? Clock.schedule_once(lambda dt: callback(picturePath), 0) finally: activity.unbind(on_activity_result=on_activity_result) # See: http://pyjnius.readthedocs.org/en/latest/android.html activity.bind(on_activity_result=on_activity_result) intent = Intent() # http://programmerguru.com/android-tutorial/how-to-pick-image-from-gallery/ # http://stackoverflow.com/questions/18416122/open-gallery-app-in-android intent.setAction(Intent.ACTION_PICK) # TODO internal vs external? intent.setData(Uri.parse('content://media/internal/images/media')) # TODO setType(Image)? currentActivity.startActivityForResult(intent, RESULT_LOAD_IMAGE)
def __init__(self): super(AccelerometerSensorListener, self).__init__() self.SensorManager = cast('android.hardware.SensorManager', activity.getSystemService(Context.SENSOR_SERVICE)) self.sensor = self.SensorManager.getDefaultSensor( Sensor.TYPE_ACCELEROMETER) self.values = [None, None, None]
def __init__(self): super(MagneticFieldSensorListener, self).__init__() self.SensorManager = cast('android.hardware.SensorManager', activity.getSystemService(Context.SENSOR_SERVICE)) self.sensor = self.SensorManager.getDefaultSensor( Sensor.TYPE_MAGNETIC_FIELD) self.values = [0, 0, 0]
def displayAndroidThumbnail(self, bmp, *largs): print 'display' print self.thumbnail img_view = ImageView(cast(Context, activity)) print 'created view' img_view.setImageBitmap(self.thumbnail) self.ids.android.view = img_view print "sem released"
def openInBrowser(self, link): "Opens a link in the browser" if platform == 'android': from jnius import autoclass, cast # import the needed Java class PythonActivity = autoclass('org.kivy.android.PythonActivity') Intent = autoclass('android.content.Intent') Uri = autoclass('android.net.Uri') # create the intent intent = Intent() intent.setAction(Intent.ACTION_VIEW) intent.setData(Uri.parse(link)) # PythonActivity.mActivity is the instance of the current Activity # BUT, startActivity is a method from the Activity class, not from our # PythonActivity. # We need to cast our class into an activity and use it currentActivity = cast('android.app.Activity', PythonActivity.mActivity) currentActivity.startActivity(intent) else: import webbrowser webbrowser.open(link)
def android_acquire_permissions(permission_list, timeout): import time import jnius PythonActivity = jnius.autoclass('org.kivy.android.PythonActivity') ContextCompat = jnius.autoclass('android.support.v4.content.ContextCompat') currentActivity = jnius.cast('android.app.Activity', PythonActivity.mActivity) if all( ContextCompat.checkSelfPermission(currentActivity, _p) == 0 for _p in permission_list): return currentActivity.requestPermissions(permission_list, 0) haveperms = False t0 = time.time() while time.time() - t0 < timeout and not haveperms: haveperms = all( ContextCompat.checkSelfPermission(currentActivity, _p) == 0 for _p in permission_list) if not haveperms: raise RuntimeError("Permissions not granted")
def _make_check_index(self, n, index_type, fields=('text',), meta=('docno', 'url', 'title')): from pyterrier.index import IndexingType it = ( {'docno': '1', 'url': 'url1', 'text': 'He ran out of money, so he had to stop playing', 'title': 'Woes of playing poker'}, {'docno': '2', 'url': 'url2', 'text': 'The waves were crashing on the shore; it was a', 'title': 'Lovely sight'}, {'docno': '3', 'url': 'url3', 'text': 'The body may perhaps compensates for the loss', 'title': 'Best of Viktor Prowoll'}, ) it = itertools.islice(it, n) indexref = self._create_index(it, fields, meta, index_type) index = pt.IndexFactory.of(indexref) self.assertIsNotNone(index) self.assertEqual(n, index.getCollectionStatistics().getNumberOfDocuments()) self.assertEqual(len(set(meta)), len(index.getMetaIndex().getKeys())) for m in meta: self.assertTrue(m in index.getMetaIndex().getKeys()) self.assertEqual(len(fields), index.getCollectionStatistics().numberOfFields) for f in fields: self.assertTrue(f in index.getCollectionStatistics().getFieldNames()) if index_type is IndexingType.CLASSIC: self.assertTrue(os.path.isfile(self.test_dir + '/data.direct.bf')) self.assertTrue(index.hasIndexStructure("direct")) else: self.assertFalse(os.path.isfile(self.test_dir + '/data.direct.bf')) inv = index.getInvertedIndex() lex = index.getLexicon() post = inv.getPostings(lex.getLexiconEntry('plai')) post.next() from jnius import cast post = cast("org.terrier.structures.postings.FieldPosting", post) if 'title' in fields: self.assertEqual(2, post.frequency) self.assertEqual(1, post.fieldFrequencies[0]) self.assertEqual(1, post.fieldFrequencies[1]) else: self.assertEqual(1, post.frequency) self.assertEqual(1, post.fieldFrequencies[0])
def take_picture(self, on_complete): self.on_complete = on_complete camera_intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) photo_file = self._create_image_file() if photo_file is not None: photo_uri = FileProvider.getUriForFile( self.currentActivity.getApplicationContext(), self.currentActivity.getApplicationContext().getPackageName(), photo_file ) parcelable = cast('android.os.Parcelable', photo_uri) activity.unbind(on_activity_result=self.on_activity_result) activity.bind(on_activity_result=self.on_activity_result) camera_intent.putExtra(MediaStore.EXTRA_OUTPUT, parcelable) self.currentActivity.startActivityForResult(camera_intent, self.CAMERA_REQUEST_CODE)
def clock_func(dt): if not self.busy: local_file_path = os.path.join(self.cache_folder, paper_dir, file_name) Logger.debug("Opening file %s" % local_file_path) if platform == 'android': Clock.unschedule(clock_func) PythonActivity = autoclass( 'org.kivy.android.PythonActivity') Intent = autoclass('android.content.Intent') Uri = autoclass('android.net.Uri') mimetype = mimetypes.guess_type(local_file_path)[0] file_uri = urlparse.urljoin('file://', local_file_path) intent = Intent() intent.setAction(Intent.ACTION_VIEW) intent.setDataAndType(Uri.parse(file_uri), mimetype) currentActivity = cast('android.app.Activity', PythonActivity.mActivity) currentActivity.startActivity(intent) elif platform == 'linux': Clock.unschedule(clock_func) webbrowser.open(local_file_path)
def on_new_intent(self, intent): ''' This functions is called when the application receives a new intent, for the ones the application has registered previously, either in the manifest or in the foreground dispatch setup in the nfc_init function above. ''' action_list = (NfcAdapter.ACTION_NDEF_DISCOVERED,) # get TAG #tag = cast('android.nfc.Tag', intent.getParcelableExtra(NfcAdapter.EXTRA_TAG)) #details = self.get_ndef_details(tag) if intent.getAction() not in action_list: print 'unknow action, avoid.' return rawmsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES) if not rawmsgs: return for message in rawmsgs: message = cast(NdefMessage, message) payload = message.getRecords()[0].getPayload() print 'payload: {}'.format(''.join(map(chr, payload)))
def to_background(): from jnius import cast from jnius import autoclass PythonActivity = autoclass('org.renpy.android.PythonActivity') currentActivity = cast('android.app.Activity', PythonActivity.mActivity) currentActivity.moveTaskToBack(True)
timestamp = time.strftime("%Y%m%d_%H:%M:%S") # If running on a Windows PC, run the following # timestamp = time.strftime("%Y%m%d_%H_%M_%S") # If running on an android device, set the right path to save the JSON file if platform == 'android': from jnius import autoclass, cast, JavaException try: PythonActivity = autoclass('org.kivy.android.PythonActivity') except JavaException: PythonActivity = autoclass('org.renpy.android.PythonActivity') Environment = autoclass('android.os.Environment') context = cast('android.content.Context', PythonActivity.mActivity) private_storage = context.getExternalFilesDir( Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath() store = JsonStore(".".join([private_storage, timestamp, 'json'])) # Linux / Windows OS else: store = JsonStore(".".join([timestamp, 'json'])) # Prepare dictionaries to save information subj_info = {} subj_anth = {} subj_trial_info = {} ''' These are Psi-Marginal Staircase related parameters
def getMobileNetworkType(): ''' Returns info about current mobile connection For mobile type Only (not for WiFi) If not using mobile connection or an error, returns None Return {'info':info, 'fast',fast} - Info: string - fast: True, False or None if unknow Help: https://gist.github.com/emil2k/5130324 ''' info, fast = "Error!", False try: mContext = autoclass('android.content.Context') pythonActivity = autoclass('org.renpy.android.PythonService') connectivityManager = autoclass('android.net.ConnectivityManager') telephonyManager = autoclass("android.telephony.TelephonyManager") cManager = cast( 'android.net.ConnectivityManager', pythonActivity.mService.getSystemService( mContext.CONNECTIVITY_SERVICE)) activeNetworkInfo = cManager.getActiveNetworkInfo() cType = activeNetworkInfo.getType() cSubType = activeNetworkInfo.getSubtype() if cType != connectivityManager.TYPE_MOBILE: return None if cSubType == telephonyManager.NETWORK_TYPE_1xRTT: info = "1xRTT: 50-100 kbps" fast = False if cSubType == telephonyManager.NETWORK_TYPE_CDMA: info = "CDMA: 14-64 kbps" fast = False if cSubType == telephonyManager.NETWORK_TYPE_EDGE: info = "EDGE: 50-100 kbps" fast = False if cSubType == telephonyManager.NETWORK_TYPE_EVDO_0: info = "EVDO_0: 400-1000 kbps" fast = True if cSubType == telephonyManager.NETWORK_TYPE_EVDO_A: info = "EVDO_A: 600-1400 kbps" fast = True if cSubType == telephonyManager.NETWORK_TYPE_GPRS: info = "GPRS: 100 kbps" fast = False if cSubType == telephonyManager.NETWORK_TYPE_HSDPA: info = "HSDPA: 2-14 Mbps" fast = True if cSubType == telephonyManager.NETWORK_TYPE_HSPA: info = "HSPA: 700-1700 kbps" fast = True if cSubType == telephonyManager.NETWORK_TYPE_HSUPA: info = "HSUPA: 1-23 Mbps" fast = True if cSubType == telephonyManager.NETWORK_TYPE_UMTS: info = "UMTS: 400-7000 kbps" fast = True if cSubType == telephonyManager.NETWORK_TYPE_EHRPD: #API level 11 info = "EHRPD: 1-2 Mbps" fast = True if cSubType == telephonyManager.NETWORK_TYPE_EVDO_B: #API level 9 info = "EVDO_B: 5 Mbps" fast = True if cSubType == telephonyManager.NETWORK_TYPE_HSPAP: #API level 13 info = "HSPAP: 10-20 Mbps" fast = True if cSubType == telephonyManager.NETWORK_TYPE_IDEN: #API level 8 info = "IDEN: 25 kbps" fast = False if cSubType == telephonyManager.NETWORK_TYPE_LTE: #API level 11 info = "LTE: 10+ Mbps" fast = True if cSubType == telephonyManager.NETWORK_TYPE_UNKNOWN: info = "UNKNOWN: ?" fast = None return {'info': info, 'fast': fast} except Exception, e: return {'info': info, 'fast': fast}
import sys import threading import time import timeit from .dm_collector import dm_collector_c, DMLogPacket, FormatError from .monitor import Monitor, Event is_android = False try: from jnius import autoclass, cast # For Android try: service_context = autoclass('org.kivy.android.PythonService').mService if not service_context: service_context = cast("android.app.Activity", autoclass( "org.kivy.android.PythonActivity").mActivity) except Exception as e: service_context = cast("android.app.Activity", autoclass( "org.kivy.android.PythonActivity").mActivity) is_android = True except Exception as e: # not used, but bugs may exist on laptop is_android = False ANDROID_SHELL = "/system/bin/sh" def get_cache_dir(): if is_android: return str(service_context.getCacheDir().getAbsolutePath())
if __name__ == "__main__": ArrayImgs = autoclass( 'net.imglib2.img.array.ArrayImgs' ) UnsafeUtil = autoclass( 'net.imglib2.img.basictypelongaccess.unsafe.UnsafeUtil' ) Arrays = autoclass( 'java.util.Arrays' ) OwningFloatUnsafe = autoclass( 'net.imglib2.img.basictypelongaccess.unsafe.owning.OwningFloatUnsafe' ) Fraction = autoclass( 'net.imglib2.util.Fraction' ) LongStream = autoclass('java.util.stream.LongStream') shape = ( 2, 3, 4 ) n_elements = int( np.prod( shape ) ) data_store = OwningFloatUnsafe( n_elements ) dim_array = LongStream.of( *shape ).toArray() print( Arrays.toString( dim_array ) ) rai = util.Helpers.toArrayImg( cast( util.Helpers.className( data_store ), data_store ), dim_array ) # rai = ArrayImgs.floats( *shape ) c = rai.cursor() count = 23 while c.hasNext(): c.next().setReal( count ) count += 1 print( util.Helpers.className( rai.randomAccess().get() ) ) print( util.Helpers.classNameSimple( rai.randomAccess().get() ) ) arr = ImgLibReferenceGuard( rai ) print( arr, arr.mean() ) c = rai.cursor() c.fwd() c.next().setReal( 0 ) print( arr, arr.mean() )
def transform(self, topics): """ Performs the retrieval with multiple features Args: topics: String for a single query, list of queries, or a pandas.Dataframe with columns=['qid', 'query'] Returns: pandas.Dataframe with columns=['qid', 'docno', 'score', 'features'] """ results = [] queries = Utils.form_dataframe(topics) docno_provided = "docno" in queries.columns docid_provided = "docid" in queries.columns scores_provided = "scores" in queries.columns if docno_provided or docid_provided: from . import check_version assert check_version(5.3) input_results = queries # query is optional, and functionally dependent on qid. # Hence as long as one row has the query for each qid, # the rest can be None queries = input_results[["qid", "query" ]].dropna(axis=0, subset=["query" ]).drop_duplicates() RequestContextMatching = autoclass( "org.terrier.python.RequestContextMatching") if queries["qid"].dtype == np.int64: queries['qid'] = queries['qid'].astype(str) for row in tqdm(queries.itertuples(), desc=self.name, total=queries.shape[0], unit="q") if self.verbose else queries.itertuples(): qid = str(row.qid) query = row.query srq = self.manager.newSearchRequest(qid, query) for control, value in self.controls.items(): srq.setControl(control, str(value)) # this is needed until terrier-core issue #106 lands if "applypipeline:off" in query: srq.setControl("applypipeline", "off") srq.setOriginalQuery(query.replace("applypipeline:off", "")) # transparently detect matchop queries if _matchop(query): srq.setControl("terrierql", "off") srq.setControl("parsecontrols", "off") srq.setControl("parseql", "off") srq.setControl("matchopql", "on") # this handles the case that a candidate set of documents has been set. if docno_provided or docid_provided: # we use RequestContextMatching to make a ResultSet from the # documents in the candidate set. matching_config_factory = RequestContextMatching.of(srq) input_query_results = input_results[input_results["qid"] == qid] if docid_provided: matching_config_factory.fromDocids( input_query_results["docid"].values.tolist()) elif docno_provided: matching_config_factory.fromDocnos( input_query_results["docno"].values.tolist()) if scores_provided: matching_config_factory.withScores( input_query_results["scores"].values.tolist()) matching_config_factory.build() srq.setControl( "matching", ",".join([ "FatFeaturedScoringMatching", "ScoringMatchingWithFat", srq.getControl("matching") ])) self.manager.runSearchRequest(srq) srq = cast('org.terrier.querying.Request', srq) fres = cast('org.terrier.learning.FeaturedResultSet', srq.getResultSet()) feat_names = fres.getFeatureNames() docids = fres.getDocids() scores = fres.getScores() metadata_list = [] for meta_column in self.metadata: metadata_list.append(fres.getMetaItems("docno")) feats_values = [] for feat in feat_names: feats_values.append(fres.getFeatureScores(feat)) rank = 0 for i in range(fres.getResultSize()): feats_array = [] for j in range(len(feats_values)): feats_array.append(feats_values[j][i]) feats_array = np.array(feats_array) meta = [] for meta_idx, meta_column in enumerate(self.metadata): meta.append(metadata_list[meta_idx][i]) results.append([qid, docids[i], rank] + meta + [scores[i], feats_array]) rank += 1 res_dt = pd.DataFrame( results, columns=["qid", "docid", "rank", "docno", "score", "features"]) return res_dt
def fb_login(self, *args): self.mLoginMgr.logInWithReadPermissions( cast(autoclass('android.app.Activity'), context), Arrays.asList("email", "public_profile"))
def onSessionReady(self): """ Executed whenever the main session completes the startup sequence. """ # CONNECT TO PROJECT SPECIFIC SIGNALS widget = self.widget('Explanation_explorer') self.debug('Connecting to project: %s', self.project.name) # FILL IN Explanation EXPLORER WITH DATA connect(self.sgnFakeExplanationAdded, widget.doAddExplanation) connect(self.sgnFakeAxiomAdded, widget.doAddAxiom) connect(self.sgnFakeItemAdded, widget.doAddNodeOREdge) if len(self.project.explanations_for_inconsistent_ontology ) > 0 and len( self.project.explanations_for_unsatisfiable_classes) > 0: LOGGER.error( 'Error, len(self.project.explanations_for_inconsistent_ontology) >0 and len(self.project.explanations_for_unsatisfiable_classes) >0:' ) sys.exit(0) #choose the explanation if len(self.project.explanations_for_inconsistent_ontology) > 0: explanations_for_widget = self.project.explanations_for_inconsistent_ontology else: if 'ConceptNode' in self.project.uc_as_input_for_explanation_explorer: unsatisfiable_entities = self.project.unsatisfiable_classes explanations_unsatisfiable_entity = self.project.explanations_for_unsatisfiable_classes elif 'AttributeNode' in self.project.uc_as_input_for_explanation_explorer: unsatisfiable_entities = self.project.unsatisfiable_attributes explanations_unsatisfiable_entity = self.project.explanations_for_unsatisfiable_attributes elif 'RoleNode' in self.project.uc_as_input_for_explanation_explorer: unsatisfiable_entities = self.project.unsatisfiable_roles explanations_unsatisfiable_entity = self.project.explanations_for_unsatisfiable_roles #print('self.project.uc_as_input_for_explanation_explorer',self.project.uc_as_input_for_explanation_explorer) #print('self.project.uc_as_input_for_explanation_explorer',self.project.uc_as_input_for_explanation_explorer) inp_node = None for n in self.project.nodes(): if str(n) == self.project.uc_as_input_for_explanation_explorer: inp_node = n OWL_term_uc_as_input_for_explanation_explorer = self.project.getOWLtermfornode( inp_node) index_uc = unsatisfiable_entities.index( OWL_term_uc_as_input_for_explanation_explorer) explanations_for_widget = explanations_unsatisfiable_entity[ index_uc] for explanation_count, e in enumerate(explanations_for_widget): self.sgnFakeExplanationAdded.emit(str(explanation_count + 1)) for explanation_count, e in enumerate(explanations_for_widget): axioms_for_iteration = [] if self.project.inconsistent_ontology is True: axioms_temp = e.getAxioms() axioms_temp_itr = axioms_temp.iterator() while (axioms_temp_itr.hasNext()): axiom_temp = axioms_temp_itr.next() axioms_for_iteration.append(axiom_temp) else: e_itr = e.iterator() while (e_itr.hasNext()): axiom_temp = e_itr.next() axioms_for_iteration.append(axiom_temp) for axiom_count, axiom_e in enumerate(axioms_for_iteration): q_exp_items = widget.model.findItems( 'Explanation - ' + str(explanation_count + 1), flags=QtCore.Qt.MatchExactly, column=0) if len(q_exp_items) != 1: LOGGER.error( 'multiple or 0 QStandardItems found for q_exp_item') sys.exit(0) cast(autoclass('org.semanticweb.owlapi.model.OWLAxiom'), axiom_e) self.sgnFakeAxiomAdded.emit(q_exp_items[0], axiom_e.toString()) q_axiom_item = q_exp_items[0].child(axiom_count, 0) nodes_and_edges = self.project.axioms_to_nodes_edges_mapping[ q_axiom_item.text()] nodes_to_add_in_widget = set() edges_to_add_in_widget = set() for ne in nodes_and_edges: if 'eddy.core.items.nodes' in str(type(ne)): nodes_to_add_in_widget.add(ne) elif 'eddy.core.items.edges' in str(type(ne)): edges_to_add_in_widget.add(ne) else: pass for node in nodes_to_add_in_widget: self.sgnFakeItemAdded.emit(node.diagram, node, q_axiom_item) for edge in edges_to_add_in_widget: self.sgnFakeItemAdded.emit(edge.diagram, edge, q_axiom_item) disconnect(self.sgnFakeExplanationAdded, widget.doAddExplanation) disconnect(self.sgnFakeAxiomAdded, widget.doAddAxiom) disconnect(self.sgnFakeItemAdded, widget.doAddNodeOREdge)
def open(self): self.close() activity = cast('android.content.Context', Context.mActivity) manager = activity.getSystemService("usb") usb_device_list = manager.getDeviceList().values().toArray() device = None log.info("UsbDevices: {}".format(usb_device_list)) for device in usb_device_list: if device and device.getDeviceName()==self.portstr: log.info("Found device {}".format(device.getDeviceName())) break if not device: raise SerialException("Device not present {}".format(self.portstr)) ACTION_USB_PERMISSION = "com.access.device.USB_PERMISSION" intent = Intent(ACTION_USB_PERMISSION) pintent = PendingIntent.getBroadcast(activity, 0, intent, 0) if not manager.hasPermission(device): manager.requestPermission(device, pintent) return connection = manager.openDevice(device) if not connection: raise SerialException("Failed to open device!") log.info("UsbDevice connection made {}!".format(connection)) self._device = device self._connection = connection for i in range(self._device.getInterfaceCount()): if i == 0: self._interface = self._device.getInterface(i) if self._connection.claimInterface(self._device.getInterface(i), True): log.info("Claim interface {} successful!".format(i)) else: raise SerialException("Could not claim interface {}.".format(i)) for i in range(self._interface.getEndpointCount()): ep = self._interface.getEndpoint(i) if ((ep.getDirection() == UsbConstants.USB_DIR_IN) and (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT)): log.debug("Found controlling endpoint({})".format(i)) self._control_endpoint = ep elif ((ep.getDirection() == UsbConstants.USB_DIR_IN) and (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)): log.debug("Found reading endpoint({})".format(i)) self._read_endpoint = ep elif ((ep.getDirection() == UsbConstants.USB_DIR_OUT) and (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)): log.debug("Found writing endpoint({})".format(i)) self._write_endpoint = ep #: Check that all endpoints are good if None in [self._write_endpoint, self._read_endpoint]: msg = "Could not establish all endpoints" log.debug(msg) raise SerialException(msg) self.is_open = True self._reconfigure_port()
"""Implementation Vibrator for Android.""" from jnius import autoclass, cast from plyer.facades import Vibrator from plyer.platforms.android import activity from plyer.platforms.android import SDK_INT Context = autoclass("android.content.Context") vibrator_service = activity.getSystemService(Context.VIBRATOR_SERVICE) vibrator = cast("android.os.Vibrator", vibrator_service) if SDK_INT >= 26: VibrationEffect = autoclass("android.os.VibrationEffect") class AndroidVibrator(Vibrator): """Android Vibrator class. Supported features: * vibrate for some period of time. * vibrate from given pattern. * cancel vibration. * check whether Vibrator exists. """ def _vibrate(self, time=None, **kwargs): if vibrator: if SDK_INT >= 26: vibrator.vibrate( VibrationEffect.createOneShot( int(1000 * time), VibrationEffect.DEFAULT_AMPLITUDE)) else: vibrator.vibrate(int(1000 * time))
def toast(text, length_long=False): duration = Toast.LENGTH_LONG if length_long else Toast.LENGTH_SHORT String = autoclass('java.lang.String') c = cast('java.lang.CharSequence', String(text)) t = Toast.makeText(context, c, duration) t.show()
def destroy_layout(self): if self.layout: parent = cast(ViewGroup, self.layout.getParent()) if parent is not None: parent.removeView(self.layout)
""" Contains methods to obtain special classes of android """ from jnius import autoclass, cast from kivy import platform from kivy.clock import mainthread if platform == "android": from android import activity PythonActivity = autoclass('org.kivy.android.PythonActivity') currentActivity = cast('android.app.Activity', PythonActivity.mActivity) context = cast('android.content.Context', currentActivity.getApplicationContext()) Intent = autoclass('android.content.Intent') Uri = autoclass('android.net.Uri') PackageInstaller = autoclass('android.content.pm.PackageInstaller') Build = autoclass('android.os.Build') def get_data_dir(): """Provides External Storage Directory: /storage/emulated/0/Android/data/<package-name>/files""" _external_storage_path = PythonActivity.getExternalFilesDir(None).getPath() return _external_storage_path def package_name(): """Provides package-name: org.dcindia.appupdater"""
def show_toast(text): t= Toast.makeText(context, cast(CharSequence, String(text)), Toast.LENGTH_SHORT) t.show()
def _initialize_clipboard(self): PythonActivity._clipboard = cast( 'android.app.Activity', PythonActivity.mActivity).getSystemService( Context.CLIPBOARD_SERVICE)
if response: content = response.read() import json data = json.loads(content) link = data['link'] # get android object PythonActivity = autoclass('org.renpy.android.PythonActivity') Intent = autoclass('android.content.Intent') Uri = autoclass('android.net.Uri') Toast = autoclass('android.widget.Toast') # play the url intent = Intent() intent.setAction(Intent.ACTION_VIEW) intent.setDataAndType(Uri.parse(link), 'video/*') currentActivity = cast('android.app.Activity', PythonActivity.mActivity) try: s = "Play Video: %s..." % link print(s) currentActivity.startActivity(intent) except JavaException: s = "Need install A8 Player App first" browser = AndroidBrowser() browser.open("http://play.tubebook.net/a8-video-player.html") else: print("Maybe network error, could not get the parameters for play")
def bind_camera(self,preview_view): self.preview_view = preview_view # CameraProvider context = cast('android.content.Context', PythonActivity.mActivity.getApplicationContext()) try: cpf = ProcessCameraProvider.getInstance(context) except Exception as e: print('ERROR CameraX.bind_camera():\n' + str(e)) self.cameraProvider = cpf.get() self.cameraProvider.unbindAll() # CameraSelector csb = CameraSelectorBuilder() csb.requireLensFacing(self.lens_facing) cameraSelector = csb.build() # ImageAnalysis if self.analysis: wm = PythonActivity.mActivity.getWindowManager() self.rotation = wm.getDefaultDisplay().getRotation() strategy = ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST self.ib = ImageAnalysisBuilder() if self.resolution: self.ib.setTargetResolution(Size(self.resolution[0], self.resolution[1])) else: self.ib.setTargetAspectRatio(self.aspect_ratio) self.ib.setBackpressureStrategy(strategy) self.ib.setTargetRotation(self.rotation) self.imageAnalysis = self.ib.build() if api_version < 28: self.te = ContextCompat.getMainExecutor(context) else: self.te = context.getMainExecutor() self.wrapper = CallbackWrapper(self.callback) self.iaa = ImageAnalysisAnalyzer(self.wrapper) self.imageAnalysis.setAnalyzer(self.te, self.iaa) # ImageCapture if self.capture: mActivity = PythonActivity.mActivity rot = mActivity.getWindowManager().getDefaultDisplay().getRotation() if self.video: self.cb = VideoCaptureBuilder() else: self.cb = ImageCaptureBuilder() self.cb.setFlashMode(self.flash_mode) self.cb.setCaptureMode(self.optimize) self.cb.setTargetAspectRatio(self.aspect_ratio) self.cb.setTargetRotation(rot) self.imageCapture = self.cb.build() # Preview pb = PreviewBuilder() if self.analysis and self.resolution: pb.setTargetResolution(Size(self.resolution[0], self.resolution[1])) elif self.capture or self.analysis: if self.aspect_ratio == AspectRatio.RATIO_4_3 or\ self.aspect_ratio == AspectRatio.RATIO_16_9: pb.setTargetAspectRatio(self.aspect_ratio) preview = pb.build() preview.setSurfaceProvider(preview_view.getSurfaceProvider()) # UseCase ucgb = UseCaseGroupBuilder() ucgb.addUseCase(preview) if self.capture: ucgb.addUseCase(self.imageCapture) if self.analysis: ucgb.addUseCase(self.imageAnalysis) #if previewview: ucgb.setViewPort(preview_view.getViewPort()) useCaseGroup = ucgb.build() # Bind self.cam = self.cameraProvider.bindToLifecycle(ProcessLifecycleOwner.get(), cameraSelector, useCaseGroup) self.cam.cameraControl.setLinearZoom(self.zoom) self.focus(0.5,0.5)
def transform(self, topics): """ Performs the retrieval with multiple features Args: topics: String for a single query, list of queries, or a pandas.Dataframe with columns=['qid', 'query'] Returns: pandas.Dataframe with columns=['qid', 'docno', 'score', 'features'] """ results = [] queries = coerce_queries_dataframe(topics) docno_provided = "docno" in queries.columns docid_provided = "docid" in queries.columns scores_provided = "score" in queries.columns if docno_provided or docid_provided: #re-ranking mode from . import check_version assert check_version(5.3) input_results = queries # query is optional, and functionally dependent on qid. # Hence as long as one row has the query for each qid, # the rest can be None queries = input_results[["qid", "query" ]].dropna(axis=0, subset=["query" ]).drop_duplicates() RequestContextMatching = autoclass( "org.terrier.python.RequestContextMatching") if not scores_provided and self.wmodel is None: raise ValueError( "We're in re-ranking mode, but input does not have scores, and wmodel is None" ) else: assert not scores_provided if self.wmodel is None: raise ValueError( "We're in retrieval mode, but wmodel is None. FeaturesBatchRetrieve requires a wmodel be set for identifying the candidate set. " + " Hint: wmodel argument for FeaturesBatchRetrieve, e.g. FeaturesBatchRetrieve(index, features, wmodel=\"DPH\")" ) if queries["qid"].dtype == np.int64: queries['qid'] = queries['qid'].astype(str) newscores = [] for row in tqdm(queries.itertuples(), desc=str(self), total=queries.shape[0], unit="q") if self.verbose else queries.itertuples(): qid = str(row.qid) query = row.query srq = self.manager.newSearchRequest(qid, query) for control, value in self.controls.items(): srq.setControl(control, str(value)) # this is needed until terrier-core issue #106 lands if "applypipeline:off" in query: srq.setControl("applypipeline", "off") srq.setOriginalQuery(query.replace("applypipeline:off", "")) # transparently detect matchop queries if _matchop(query): srq.setControl("terrierql", "off") srq.setControl("parsecontrols", "off") srq.setControl("parseql", "off") srq.setControl("matchopql", "on") # this handles the case that a candidate set of documents has been set. if docno_provided or docid_provided: # we use RequestContextMatching to make a ResultSet from the # documents in the candidate set. matching_config_factory = RequestContextMatching.of(srq) input_query_results = input_results[input_results["qid"] == qid] if docid_provided: matching_config_factory.fromDocids( input_query_results["docid"].values.tolist()) elif docno_provided: matching_config_factory.fromDocnos( input_query_results["docno"].values.tolist()) if scores_provided: if self.wmodel is None: # we provide the scores, so dont use a weighting model, and pass the scores through Terrier matching_config_factory.withScores( input_query_results["score"].values.tolist()) srq.setControl("wmodel", "Null") else: srq.setControl("wmodel", self.wmodel) matching_config_factory.build() srq.setControl( "matching", ",".join([ "FatFeaturedScoringMatching", "ScoringMatchingWithFat", srq.getControl("matching") ])) self.manager.runSearchRequest(srq) srq = cast('org.terrier.querying.Request', srq) fres = cast('org.terrier.learning.FeaturedResultSet', srq.getResultSet()) feat_names = fres.getFeatureNames() docids = fres.getDocids() scores = fres.getScores() metadata_list = [ fres.getMetaItems(meta_column) for meta_column in self.metadata ] feats_values = [fres.getFeatureScores(feat) for feat in feat_names] rank = FIRST_RANK for i in range(fres.getResultSize()): doc_features = np.array( [feature[i] for feature in feats_values]) meta = [metadata_col[i] for metadata_col in metadata_list] results.append([qid, docids[i], rank, doc_features] + meta) newscores.append(scores[i]) rank += 1 res_dt = pd.DataFrame(results, columns=["qid", "docid", "rank", "features"] + self.metadata) # if scores_provided and self.wmodel is None: # # we take the scores from the input dataframe, as ScoringMatchingWithFat overwrites them # # prefer to join on docid # if docid_provided: # res_dt = res_dt.merge(topics[["qid", "docid", "score"]], on=["qid", "docid"], how='right') # else: # assert docno_provided # res_dt = res_dt.merge(topics[["qid", "docno", "score"]], on=["qid", "docno"], how='right') # elif self.wmodel is not None: # # we use new scores obtained from Terrier # # order should be same as the results column # res_dt["score"] = newscores res_dt["score"] = newscores return res_dt
import operator from os.path import join from jnius import autoclass, cast, PythonJavaClass, java_method AndroidCamera = autoclass('android.hardware.Camera') CameraInfo = autoclass('android.hardware.Camera$CameraInfo') CameraArea = autoclass('android.hardware.Camera$Area') Surface = autoclass('android.view.Surface') File = autoclass('java.io.File') FileOutputStream = autoclass('java.io.FileOutputStream') Rect = autoclass('android.graphics.Rect') ArrayList = autoclass('java.util.ArrayList') Parameters = autoclass('android.hardware.Camera$Parameters') PythonActivity = autoclass('org.renpy.android.PythonActivity') theActivity = cast('org.renpy.android.PythonActivity', PythonActivity.mActivity) # Make sure the user controls the volume of the audio stream we're actually using AudioManager = autoclass('android.media.AudioManager') theActivity.setVolumeControlStream(AudioManager.STREAM_MUSIC) BuildVERSION = autoclass('android.os.Build$VERSION') api_version = int(BuildVERSION.SDK_INT) def map_List(func, l): res = [] if l is not None: it = l.iterator() while it.hasNext(): res.append(func(it.next()))
def __init__(self): if is_android(): ## reflect our activity with the main apps activity self.current_activity = cast("android.app.Activity", PythonActivity.mActivity) ## tell android where to send our speech results activity.bind(on_activity_result=self.on_activity_result)
import functools import os import shlex import sys import subprocess import time import traceback import re import datetime import shutil import stat import json from kivy.lib.osc import oscAPI as osc from kivy.logger import Logger current_activity = cast("android.app.Activity", autoclass("org.kivy.android.PythonActivity").mActivity) ANDROID_SHELL = "/system/bin/sh" File = autoclass("java.io.File") FileOutputStream = autoclass('java.io.FileOutputStream') Context = autoclass('android.content.Context') telephonyManager = current_activity.getSystemService(Context.TELEPHONY_SERVICE) androidOsBuild = autoclass("android.os.Build") class ChipsetType: """ Cellular modem type """ QUALCOMM = 0
def run_on_start(): print('single shot in event loop') ImageJ2 = autoclass('net.imagej.ImageJ') CommandInfo = autoclass('org.scijava.command.CommandInfo') MenuPath = autoclass('org.scijava.MenuPath') ij = ImageJ2() Factory = autoclass( 'net/imglib2/python/ArrayImgWithUnsafeStoreFactory'.replace( '/', '.')) factory = cast('net.imglib2.img.ImgFactory', Factory()) ImgOpener = autoclass('io.scif.img.ImgOpener') opener = ImgOpener(ij.getContext()) display = ij.display() PythonCommandInfo = autoclass('net.imglib2.python.PythonCommandInfo') RunnableCommand = autoclass( 'net.imglib2.python.PythonCommandInfo$RunnableCommand') runnable = Runnable(lambda: QtWidgets.QApplication.postEvent( widget, QtGui.QShowEvent())) command = RunnableCommand(runnable) command_info = PythonCommandInfo(command) command_info.setMenuPath(MenuPath("Plugins>Scripting>CPython REPL")) ij.module().addModule(command_info) SwingUtilities = autoclass('javax.swing.SwingUtilities') # This is only necessary because the command does not show in the menu anymore command.run() def open_imgs(path, t): """Open all images at location specified by path. Parameters ---------- path : str Location of images. """ return opener.openImgs(path, factory.imgFactory(t)) def open_img(path, t): """Open one image at location specified by path. Parameters ---------- path : str Location of image. """ return open_imgs(path, t).get(0) def show_img(img, title=''): """Show image using DisplayService of current ImageJ instance. Parameters ---------- img : numpy.ndarray or net.imglib2.RandomAccessibleInterval Image to be displayed. title : str Title of display. """ status = [False, None] def create_display(status): status[1] = display.createDisplay( title, imglyb.to_imglib(img) if isinstance(img, (np.ndarray, )) else img) status[0] = True SwingUtilities.invokeLater( Runnable(lambda: create_display(status))) def check_finished(status): while not status[0]: time.sleep(0.01) t = threading.Thread(target=lambda: check_finished(status)) t.start() t.join() return status[1] widget.add_more_variables(ij=ij, factory=factory, opener=opener, display=display, open_imgs=open_imgs, open_img=open_img, show_img=show_img) ij.launch() ui = ij.ui() def sleeper(): while ui.isVisible(): time.sleep(0.1) t = threading.Thread(target=sleeper) t.start()
def string_to_CharSequence(s): if platform == 'android': from jnius import cast, autoclass String = autoclass('java.lang.String') return cast('java.lang.CharSequence', String(s))
pass print('2: instantiate the class, with some data') a = TestImplem(*list(range(10))) print(a) print(dir(a)) print('tries to get a ListIterator') iterator = a.listIterator() print('iterator is', iterator) while iterator.hasNext(): print('at index', iterator.index, 'value is', iterator.next()) print('3: Do cast to a collection') a2 = cast('java/util/Collection', a.j_self) print(a2) print('4: Try few method on the collection') Collections = autoclass('java.util.Collections') #print Collections.enumeration(a) #print Collections.enumeration(a) ret = Collections.max(a) print("reverse") print(Collections.reverse(a)) print(a.data) print("before swap") print(Collections.swap(a, 2, 3)) print("after swap")
def isWiFiConnected(): mContext = autoclass('android.content.Context') pythonActivity = autoclass('org.renpy.android.PythonService') connectivityManager = autoclass('android.net.ConnectivityManager') cManager = cast('android.net.ConnectivityManager', pythonActivity.mService.getSystemService(mContext.CONNECTIVITY_SERVICE)) networkInfo = cManager.getNetworkInfo(connectivityManager.TYPE_WIFI) return networkInfo.isConnected()