file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
volumeops.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2010 Citrix Systems, Inc. # Copyright (c) 2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Management class for Storage-related functions (attach, detach, etc). """ from nova import exception from nova.openstack.common import log as logging from nova.virt.xenapi import vm_utils from nova.virt.xenapi import volume_utils LOG = logging.getLogger(__name__) class VolumeOps(object): """ Management class for Volume-related tasks """ def __init__(self, session): self._session = session def attach_volume(self, connection_info, instance_name, mountpoint, hotplug=True): """Attach volume storage to VM instance.""" vm_ref = vm_utils.vm_ref_or_raise(self._session, instance_name) # NOTE: No Resource Pool concept so far LOG.debug(_("Attach_volume: %(connection_info)s, %(instance_name)s," " %(mountpoint)s") % locals()) driver_type = connection_info['driver_volume_type'] if driver_type not in ['iscsi', 'xensm']: raise exception.VolumeDriverNotFound(driver_type=driver_type) connection_data = connection_info['data'] dev_number = volume_utils.get_device_number(mountpoint) self._connect_volume(connection_data, dev_number, instance_name, vm_ref, hotplug=hotplug) LOG.info(_('Mountpoint %(mountpoint)s attached to' ' instance %(instance_name)s') % locals()) def _connect_volume(self, connection_data, dev_number, instance_name, vm_ref, hotplug=True): sr_uuid, sr_label, sr_params = volume_utils.parse_sr_info( connection_data, 'Disk-for:%s' % instance_name) # Introduce SR if not already present sr_ref = volume_utils.find_sr_by_uuid(self._session, sr_uuid) if not sr_ref: sr_ref = volume_utils.introduce_sr( self._session, sr_uuid, sr_label, sr_params) try: # Introduce VDI if 'vdi_uuid' in connection_data: vdi_ref = volume_utils.introduce_vdi( self._session, sr_ref, vdi_uuid=connection_data['vdi_uuid']) elif 'target_lun' in connection_data: vdi_ref = volume_utils.introduce_vdi( self._session, sr_ref, target_lun=connection_data['target_lun']) else: # NOTE(sirp): This will introduce the first VDI in the SR vdi_ref = volume_utils.introduce_vdi(self._session, sr_ref) # Attach vbd_ref = vm_utils.create_vbd(self._session, vm_ref, vdi_ref, dev_number, bootable=False, osvol=True) if hotplug: self._session.call_xenapi("VBD.plug", vbd_ref) except Exception: # NOTE(sirp): Forgetting the SR will have the effect of cleaning up # the VDI and VBD records, so no need to handle that explicitly. volume_utils.forget_sr(self._session, sr_ref) raise def
(self, connection_info, instance_name, mountpoint): """Detach volume storage to VM instance.""" LOG.debug(_("Detach_volume: %(instance_name)s, %(mountpoint)s") % locals()) device_number = volume_utils.get_device_number(mountpoint) vm_ref = vm_utils.vm_ref_or_raise(self._session, instance_name) try: vbd_ref = vm_utils.find_vbd_by_number( self._session, vm_ref, device_number) except volume_utils.StorageError: # NOTE(sirp): If we don't find the VBD then it must have been # detached previously. LOG.warn(_('Skipping detach because VBD for %(instance_name)s was' ' not found') % locals()) return # Unplug VBD if we're NOT shutdown unplug = not vm_utils._is_vm_shutdown(self._session, vm_ref) self._detach_vbd(vbd_ref, unplug=unplug) LOG.info(_('Mountpoint %(mountpoint)s detached from instance' ' %(instance_name)s') % locals()) def _get_all_volume_vbd_refs(self, vm_ref): """Return VBD refs for all Nova/Cinder volumes.""" vbd_refs = self._session.call_xenapi("VM.get_VBDs", vm_ref) for vbd_ref in vbd_refs: other_config = self._session.call_xenapi( "VBD.get_other_config", vbd_ref) if other_config.get('osvol'): yield vbd_ref def _detach_vbd(self, vbd_ref, unplug=False): if unplug: vm_utils.unplug_vbd(self._session, vbd_ref) sr_ref = volume_utils.find_sr_from_vbd(self._session, vbd_ref) vm_utils.destroy_vbd(self._session, vbd_ref) # Forget SR only if not in use volume_utils.purge_sr(self._session, sr_ref) def detach_all(self, vm_ref): """Detach any external nova/cinder volumes and purge the SRs.""" # Generally speaking, detach_all will be called with VM already # shutdown; however if it's still running, we can still perform the # operation by unplugging the VBD first. unplug = not vm_utils._is_vm_shutdown(self._session, vm_ref) vbd_refs = self._get_all_volume_vbd_refs(vm_ref) for vbd_ref in vbd_refs: self._detach_vbd(vbd_ref, unplug=unplug) def find_bad_volumes(self, vm_ref): """Find any volumes with their connection severed. Certain VM operations (e.g. `VM.start`, `VM.reboot`, etc.) will not work when a VBD is present that points to a non-working volume. To work around this, we scan for non-working volumes and detach them before retrying a failed operation. """ bad_devices = [] vbd_refs = self._get_all_volume_vbd_refs(vm_ref) for vbd_ref in vbd_refs: sr_ref = volume_utils.find_sr_from_vbd(self._session, vbd_ref) try: # TODO(sirp): bug1152401 This relies on a 120 sec timeout # within XenServer, update this to fail-fast when this is fixed # upstream self._session.call_xenapi("SR.scan", sr_ref) except self._session.XenAPI.Failure, exc: if exc.details[0] == 'SR_BACKEND_FAILURE_40': vbd_rec = vbd_rec = self._session.call_xenapi( "VBD.get_record", vbd_ref) bad_devices.append('/dev/%s' % vbd_rec['device']) else: raise return bad_devices
detach_volume
identifier_name
volumeops.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2010 Citrix Systems, Inc. # Copyright (c) 2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Management class for Storage-related functions (attach, detach, etc). """ from nova import exception from nova.openstack.common import log as logging from nova.virt.xenapi import vm_utils from nova.virt.xenapi import volume_utils LOG = logging.getLogger(__name__) class VolumeOps(object): """ Management class for Volume-related tasks """ def __init__(self, session): self._session = session def attach_volume(self, connection_info, instance_name, mountpoint, hotplug=True): """Attach volume storage to VM instance.""" vm_ref = vm_utils.vm_ref_or_raise(self._session, instance_name) # NOTE: No Resource Pool concept so far LOG.debug(_("Attach_volume: %(connection_info)s, %(instance_name)s," " %(mountpoint)s") % locals()) driver_type = connection_info['driver_volume_type'] if driver_type not in ['iscsi', 'xensm']: raise exception.VolumeDriverNotFound(driver_type=driver_type) connection_data = connection_info['data'] dev_number = volume_utils.get_device_number(mountpoint) self._connect_volume(connection_data, dev_number, instance_name, vm_ref, hotplug=hotplug) LOG.info(_('Mountpoint %(mountpoint)s attached to' ' instance %(instance_name)s') % locals()) def _connect_volume(self, connection_data, dev_number, instance_name, vm_ref, hotplug=True): sr_uuid, sr_label, sr_params = volume_utils.parse_sr_info( connection_data, 'Disk-for:%s' % instance_name) # Introduce SR if not already present sr_ref = volume_utils.find_sr_by_uuid(self._session, sr_uuid) if not sr_ref: sr_ref = volume_utils.introduce_sr( self._session, sr_uuid, sr_label, sr_params) try: # Introduce VDI if 'vdi_uuid' in connection_data: vdi_ref = volume_utils.introduce_vdi( self._session, sr_ref, vdi_uuid=connection_data['vdi_uuid']) elif 'target_lun' in connection_data: vdi_ref = volume_utils.introduce_vdi( self._session, sr_ref, target_lun=connection_data['target_lun']) else: # NOTE(sirp): This will introduce the first VDI in the SR vdi_ref = volume_utils.introduce_vdi(self._session, sr_ref) # Attach vbd_ref = vm_utils.create_vbd(self._session, vm_ref, vdi_ref, dev_number, bootable=False, osvol=True) if hotplug: self._session.call_xenapi("VBD.plug", vbd_ref) except Exception: # NOTE(sirp): Forgetting the SR will have the effect of cleaning up # the VDI and VBD records, so no need to handle that explicitly. volume_utils.forget_sr(self._session, sr_ref) raise def detach_volume(self, connection_info, instance_name, mountpoint): """Detach volume storage to VM instance.""" LOG.debug(_("Detach_volume: %(instance_name)s, %(mountpoint)s") % locals()) device_number = volume_utils.get_device_number(mountpoint) vm_ref = vm_utils.vm_ref_or_raise(self._session, instance_name) try: vbd_ref = vm_utils.find_vbd_by_number( self._session, vm_ref, device_number) except volume_utils.StorageError: # NOTE(sirp): If we don't find the VBD then it must have been # detached previously. LOG.warn(_('Skipping detach because VBD for %(instance_name)s was' ' not found') % locals()) return # Unplug VBD if we're NOT shutdown unplug = not vm_utils._is_vm_shutdown(self._session, vm_ref) self._detach_vbd(vbd_ref, unplug=unplug) LOG.info(_('Mountpoint %(mountpoint)s detached from instance' ' %(instance_name)s') % locals()) def _get_all_volume_vbd_refs(self, vm_ref): """Return VBD refs for all Nova/Cinder volumes.""" vbd_refs = self._session.call_xenapi("VM.get_VBDs", vm_ref) for vbd_ref in vbd_refs: other_config = self._session.call_xenapi( "VBD.get_other_config", vbd_ref) if other_config.get('osvol'): yield vbd_ref def _detach_vbd(self, vbd_ref, unplug=False): if unplug: vm_utils.unplug_vbd(self._session, vbd_ref) sr_ref = volume_utils.find_sr_from_vbd(self._session, vbd_ref) vm_utils.destroy_vbd(self._session, vbd_ref) # Forget SR only if not in use volume_utils.purge_sr(self._session, sr_ref) def detach_all(self, vm_ref): """Detach any external nova/cinder volumes and purge the SRs.""" # Generally speaking, detach_all will be called with VM already # shutdown; however if it's still running, we can still perform the # operation by unplugging the VBD first. unplug = not vm_utils._is_vm_shutdown(self._session, vm_ref) vbd_refs = self._get_all_volume_vbd_refs(vm_ref) for vbd_ref in vbd_refs: self._detach_vbd(vbd_ref, unplug=unplug) def find_bad_volumes(self, vm_ref): """Find any volumes with their connection severed. Certain VM operations (e.g. `VM.start`, `VM.reboot`, etc.) will not work when a VBD is present that points to a non-working volume. To work around this, we scan for non-working volumes and detach them before retrying a failed operation. """ bad_devices = [] vbd_refs = self._get_all_volume_vbd_refs(vm_ref) for vbd_ref in vbd_refs:
return bad_devices
sr_ref = volume_utils.find_sr_from_vbd(self._session, vbd_ref) try: # TODO(sirp): bug1152401 This relies on a 120 sec timeout # within XenServer, update this to fail-fast when this is fixed # upstream self._session.call_xenapi("SR.scan", sr_ref) except self._session.XenAPI.Failure, exc: if exc.details[0] == 'SR_BACKEND_FAILURE_40': vbd_rec = vbd_rec = self._session.call_xenapi( "VBD.get_record", vbd_ref) bad_devices.append('/dev/%s' % vbd_rec['device']) else: raise
conditional_block
volumeops.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2010 Citrix Systems, Inc. # Copyright (c) 2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Management class for Storage-related functions (attach, detach, etc). """ from nova import exception from nova.openstack.common import log as logging from nova.virt.xenapi import vm_utils from nova.virt.xenapi import volume_utils LOG = logging.getLogger(__name__) class VolumeOps(object): """ Management class for Volume-related tasks """ def __init__(self, session): self._session = session def attach_volume(self, connection_info, instance_name, mountpoint, hotplug=True): """Attach volume storage to VM instance.""" vm_ref = vm_utils.vm_ref_or_raise(self._session, instance_name) # NOTE: No Resource Pool concept so far LOG.debug(_("Attach_volume: %(connection_info)s, %(instance_name)s," " %(mountpoint)s") % locals()) driver_type = connection_info['driver_volume_type'] if driver_type not in ['iscsi', 'xensm']: raise exception.VolumeDriverNotFound(driver_type=driver_type) connection_data = connection_info['data'] dev_number = volume_utils.get_device_number(mountpoint) self._connect_volume(connection_data, dev_number, instance_name, vm_ref, hotplug=hotplug) LOG.info(_('Mountpoint %(mountpoint)s attached to' ' instance %(instance_name)s') % locals()) def _connect_volume(self, connection_data, dev_number, instance_name, vm_ref, hotplug=True): sr_uuid, sr_label, sr_params = volume_utils.parse_sr_info( connection_data, 'Disk-for:%s' % instance_name) # Introduce SR if not already present sr_ref = volume_utils.find_sr_by_uuid(self._session, sr_uuid) if not sr_ref: sr_ref = volume_utils.introduce_sr( self._session, sr_uuid, sr_label, sr_params) try: # Introduce VDI if 'vdi_uuid' in connection_data: vdi_ref = volume_utils.introduce_vdi( self._session, sr_ref, vdi_uuid=connection_data['vdi_uuid']) elif 'target_lun' in connection_data: vdi_ref = volume_utils.introduce_vdi( self._session, sr_ref, target_lun=connection_data['target_lun']) else: # NOTE(sirp): This will introduce the first VDI in the SR vdi_ref = volume_utils.introduce_vdi(self._session, sr_ref) # Attach vbd_ref = vm_utils.create_vbd(self._session, vm_ref, vdi_ref, dev_number, bootable=False, osvol=True) if hotplug: self._session.call_xenapi("VBD.plug", vbd_ref) except Exception: # NOTE(sirp): Forgetting the SR will have the effect of cleaning up # the VDI and VBD records, so no need to handle that explicitly. volume_utils.forget_sr(self._session, sr_ref) raise def detach_volume(self, connection_info, instance_name, mountpoint): """Detach volume storage to VM instance.""" LOG.debug(_("Detach_volume: %(instance_name)s, %(mountpoint)s") % locals()) device_number = volume_utils.get_device_number(mountpoint) vm_ref = vm_utils.vm_ref_or_raise(self._session, instance_name) try: vbd_ref = vm_utils.find_vbd_by_number( self._session, vm_ref, device_number) except volume_utils.StorageError: # NOTE(sirp): If we don't find the VBD then it must have been
# Unplug VBD if we're NOT shutdown unplug = not vm_utils._is_vm_shutdown(self._session, vm_ref) self._detach_vbd(vbd_ref, unplug=unplug) LOG.info(_('Mountpoint %(mountpoint)s detached from instance' ' %(instance_name)s') % locals()) def _get_all_volume_vbd_refs(self, vm_ref): """Return VBD refs for all Nova/Cinder volumes.""" vbd_refs = self._session.call_xenapi("VM.get_VBDs", vm_ref) for vbd_ref in vbd_refs: other_config = self._session.call_xenapi( "VBD.get_other_config", vbd_ref) if other_config.get('osvol'): yield vbd_ref def _detach_vbd(self, vbd_ref, unplug=False): if unplug: vm_utils.unplug_vbd(self._session, vbd_ref) sr_ref = volume_utils.find_sr_from_vbd(self._session, vbd_ref) vm_utils.destroy_vbd(self._session, vbd_ref) # Forget SR only if not in use volume_utils.purge_sr(self._session, sr_ref) def detach_all(self, vm_ref): """Detach any external nova/cinder volumes and purge the SRs.""" # Generally speaking, detach_all will be called with VM already # shutdown; however if it's still running, we can still perform the # operation by unplugging the VBD first. unplug = not vm_utils._is_vm_shutdown(self._session, vm_ref) vbd_refs = self._get_all_volume_vbd_refs(vm_ref) for vbd_ref in vbd_refs: self._detach_vbd(vbd_ref, unplug=unplug) def find_bad_volumes(self, vm_ref): """Find any volumes with their connection severed. Certain VM operations (e.g. `VM.start`, `VM.reboot`, etc.) will not work when a VBD is present that points to a non-working volume. To work around this, we scan for non-working volumes and detach them before retrying a failed operation. """ bad_devices = [] vbd_refs = self._get_all_volume_vbd_refs(vm_ref) for vbd_ref in vbd_refs: sr_ref = volume_utils.find_sr_from_vbd(self._session, vbd_ref) try: # TODO(sirp): bug1152401 This relies on a 120 sec timeout # within XenServer, update this to fail-fast when this is fixed # upstream self._session.call_xenapi("SR.scan", sr_ref) except self._session.XenAPI.Failure, exc: if exc.details[0] == 'SR_BACKEND_FAILURE_40': vbd_rec = vbd_rec = self._session.call_xenapi( "VBD.get_record", vbd_ref) bad_devices.append('/dev/%s' % vbd_rec['device']) else: raise return bad_devices
# detached previously. LOG.warn(_('Skipping detach because VBD for %(instance_name)s was' ' not found') % locals()) return
random_line_split
volumeops.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2010 Citrix Systems, Inc. # Copyright (c) 2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Management class for Storage-related functions (attach, detach, etc). """ from nova import exception from nova.openstack.common import log as logging from nova.virt.xenapi import vm_utils from nova.virt.xenapi import volume_utils LOG = logging.getLogger(__name__) class VolumeOps(object): """ Management class for Volume-related tasks """ def __init__(self, session): self._session = session def attach_volume(self, connection_info, instance_name, mountpoint, hotplug=True): """Attach volume storage to VM instance.""" vm_ref = vm_utils.vm_ref_or_raise(self._session, instance_name) # NOTE: No Resource Pool concept so far LOG.debug(_("Attach_volume: %(connection_info)s, %(instance_name)s," " %(mountpoint)s") % locals()) driver_type = connection_info['driver_volume_type'] if driver_type not in ['iscsi', 'xensm']: raise exception.VolumeDriverNotFound(driver_type=driver_type) connection_data = connection_info['data'] dev_number = volume_utils.get_device_number(mountpoint) self._connect_volume(connection_data, dev_number, instance_name, vm_ref, hotplug=hotplug) LOG.info(_('Mountpoint %(mountpoint)s attached to' ' instance %(instance_name)s') % locals()) def _connect_volume(self, connection_data, dev_number, instance_name, vm_ref, hotplug=True):
def detach_volume(self, connection_info, instance_name, mountpoint): """Detach volume storage to VM instance.""" LOG.debug(_("Detach_volume: %(instance_name)s, %(mountpoint)s") % locals()) device_number = volume_utils.get_device_number(mountpoint) vm_ref = vm_utils.vm_ref_or_raise(self._session, instance_name) try: vbd_ref = vm_utils.find_vbd_by_number( self._session, vm_ref, device_number) except volume_utils.StorageError: # NOTE(sirp): If we don't find the VBD then it must have been # detached previously. LOG.warn(_('Skipping detach because VBD for %(instance_name)s was' ' not found') % locals()) return # Unplug VBD if we're NOT shutdown unplug = not vm_utils._is_vm_shutdown(self._session, vm_ref) self._detach_vbd(vbd_ref, unplug=unplug) LOG.info(_('Mountpoint %(mountpoint)s detached from instance' ' %(instance_name)s') % locals()) def _get_all_volume_vbd_refs(self, vm_ref): """Return VBD refs for all Nova/Cinder volumes.""" vbd_refs = self._session.call_xenapi("VM.get_VBDs", vm_ref) for vbd_ref in vbd_refs: other_config = self._session.call_xenapi( "VBD.get_other_config", vbd_ref) if other_config.get('osvol'): yield vbd_ref def _detach_vbd(self, vbd_ref, unplug=False): if unplug: vm_utils.unplug_vbd(self._session, vbd_ref) sr_ref = volume_utils.find_sr_from_vbd(self._session, vbd_ref) vm_utils.destroy_vbd(self._session, vbd_ref) # Forget SR only if not in use volume_utils.purge_sr(self._session, sr_ref) def detach_all(self, vm_ref): """Detach any external nova/cinder volumes and purge the SRs.""" # Generally speaking, detach_all will be called with VM already # shutdown; however if it's still running, we can still perform the # operation by unplugging the VBD first. unplug = not vm_utils._is_vm_shutdown(self._session, vm_ref) vbd_refs = self._get_all_volume_vbd_refs(vm_ref) for vbd_ref in vbd_refs: self._detach_vbd(vbd_ref, unplug=unplug) def find_bad_volumes(self, vm_ref): """Find any volumes with their connection severed. Certain VM operations (e.g. `VM.start`, `VM.reboot`, etc.) will not work when a VBD is present that points to a non-working volume. To work around this, we scan for non-working volumes and detach them before retrying a failed operation. """ bad_devices = [] vbd_refs = self._get_all_volume_vbd_refs(vm_ref) for vbd_ref in vbd_refs: sr_ref = volume_utils.find_sr_from_vbd(self._session, vbd_ref) try: # TODO(sirp): bug1152401 This relies on a 120 sec timeout # within XenServer, update this to fail-fast when this is fixed # upstream self._session.call_xenapi("SR.scan", sr_ref) except self._session.XenAPI.Failure, exc: if exc.details[0] == 'SR_BACKEND_FAILURE_40': vbd_rec = vbd_rec = self._session.call_xenapi( "VBD.get_record", vbd_ref) bad_devices.append('/dev/%s' % vbd_rec['device']) else: raise return bad_devices
sr_uuid, sr_label, sr_params = volume_utils.parse_sr_info( connection_data, 'Disk-for:%s' % instance_name) # Introduce SR if not already present sr_ref = volume_utils.find_sr_by_uuid(self._session, sr_uuid) if not sr_ref: sr_ref = volume_utils.introduce_sr( self._session, sr_uuid, sr_label, sr_params) try: # Introduce VDI if 'vdi_uuid' in connection_data: vdi_ref = volume_utils.introduce_vdi( self._session, sr_ref, vdi_uuid=connection_data['vdi_uuid']) elif 'target_lun' in connection_data: vdi_ref = volume_utils.introduce_vdi( self._session, sr_ref, target_lun=connection_data['target_lun']) else: # NOTE(sirp): This will introduce the first VDI in the SR vdi_ref = volume_utils.introduce_vdi(self._session, sr_ref) # Attach vbd_ref = vm_utils.create_vbd(self._session, vm_ref, vdi_ref, dev_number, bootable=False, osvol=True) if hotplug: self._session.call_xenapi("VBD.plug", vbd_ref) except Exception: # NOTE(sirp): Forgetting the SR will have the effect of cleaning up # the VDI and VBD records, so no need to handle that explicitly. volume_utils.forget_sr(self._session, sr_ref) raise
identifier_body
stockListGen.py
# (c) 2011, 2012 Georgia Tech Research Corporation # This source code is released under the New BSD license. Please see # http://wiki.quantsoftware.org/index.php?title=QSTK_License # for license details. # # Created on October <day>, 2011 # # @author: Vishal Shekhar # @contact: [email protected]
dataobj = da.DataAccess('Norgate') delistSymbols = set(dataobj.get_symbols_in_sublist('/US/Delisted Securities')) allSymbols = set(dataobj.get_all_symbols()) #by default Alive symbols only aliveSymbols = list(allSymbols - delistSymbols) # set difference is smart startday = dt.datetime(2008,1,1) endday = dt.datetime(2009,12,31) timeofday=dt.timedelta(hours=16) timestamps = du.getNYSEdays(startday,endday,timeofday) #Actual Close Prices of aliveSymbols and allSymbols aliveSymbsclose = dataobj.get_data(timestamps, aliveSymbols, 'actual_close') allSymbsclose = dataobj.get_data(timestamps, allSymbols, 'actual_close') file = open('aliveSymbols2','w') for symbol in aliveSymbols: belowdollar = len(aliveSymbsclose[symbol][aliveSymbsclose[symbol]<1.0]) if belowdollar and (len(aliveSymbsclose[symbol]) > belowdollar): file.write(str(symbol)+'\n') file.close() file = open('allSymbols2','w') for symbol in allSymbols: belowdollar = len(allSymbsclose[symbol][allSymbsclose[symbol]<1.0]) if belowdollar and (len(allSymbsclose[symbol]) > belowdollar): file.write(str(symbol)+'\n') file.close()
# @summary: Utiltiy script to create list of symbols for study. import qstkutil.DataAccess as da import qstkutil.qsdateutil as du import datetime as dt
random_line_split
stockListGen.py
# (c) 2011, 2012 Georgia Tech Research Corporation # This source code is released under the New BSD license. Please see # http://wiki.quantsoftware.org/index.php?title=QSTK_License # for license details. # # Created on October <day>, 2011 # # @author: Vishal Shekhar # @contact: [email protected] # @summary: Utiltiy script to create list of symbols for study. import qstkutil.DataAccess as da import qstkutil.qsdateutil as du import datetime as dt dataobj = da.DataAccess('Norgate') delistSymbols = set(dataobj.get_symbols_in_sublist('/US/Delisted Securities')) allSymbols = set(dataobj.get_all_symbols()) #by default Alive symbols only aliveSymbols = list(allSymbols - delistSymbols) # set difference is smart startday = dt.datetime(2008,1,1) endday = dt.datetime(2009,12,31) timeofday=dt.timedelta(hours=16) timestamps = du.getNYSEdays(startday,endday,timeofday) #Actual Close Prices of aliveSymbols and allSymbols aliveSymbsclose = dataobj.get_data(timestamps, aliveSymbols, 'actual_close') allSymbsclose = dataobj.get_data(timestamps, allSymbols, 'actual_close') file = open('aliveSymbols2','w') for symbol in aliveSymbols: belowdollar = len(aliveSymbsclose[symbol][aliveSymbsclose[symbol]<1.0]) if belowdollar and (len(aliveSymbsclose[symbol]) > belowdollar): file.write(str(symbol)+'\n') file.close() file = open('allSymbols2','w') for symbol in allSymbols: belowdollar = len(allSymbsclose[symbol][allSymbsclose[symbol]<1.0]) if belowdollar and (len(allSymbsclose[symbol]) > belowdollar):
file.close()
file.write(str(symbol)+'\n')
conditional_block
scripts.js
$(function(){ var binds = []; var edit_index = -1; var edit_key_id = null; function loadBindsFromJSON(file) { // Load Binds $.get("data/" + file, function(data) { binds = JSON.parse(data); binds.forEach(function(e, i, a) { var key = Object.keys(e)[0]; var bind = e[key]; // loop through the JSON and apply it to the HTML // Load New if (bind.title != "" || bind.color != "") { var $bind = $("#" + key); if (bind.action != "") { $bind.attr("title", bind.action); $bind.addClass("has_action"); } if (bind.color != "") { $bind.css("background-color", bind.color); } if (bind.title != "") { $("h2", $bind).html(bind.title); } } }); }); } // Stupid hack to clear them for now function clearBinds() { $("#bind_container h2").html(""); $("#bind_container div").css("background-color",""); $("#bind_container div").attr("title",""); $("#bind_container div").removeClass("has_action"); } // Initial load loadBindsFromJSON("ninja_binds.txt"); /* * Other */ $(".key").each(function() { $(this).prepend('<i class="fa fa-pencil"></i>'); }); $(".key i").click(function() { var $key_editor = $("#key_editor"); var key_id = $(this).parent("div").attr("id"); var key_name = $(this).siblings("div").html(); $key_editor.show(); $("h3 span", $key_editor).html(key_name); //console.log(binds); // Look for the bind in the JSON binds.forEach(function(e, i, a) { var key = Object.keys(e)[0]; if (key == key_id) { var bind = e[key]; console.log(e[key]); console.log(i); edit_index = i; edit_key_id = key_id; $("#edit_key_title").val(bind.title); $("#edit_key_action").val(bind.action); if (bind.color != "") { $('#picker').colpickSetColor(bind.color); } else { $('#picker').colpickSetColor("#ffffff"); } return false; } }); }); $("#key_save").click(function() { console.log(binds[edit_index]); console.log(binds[edit_index][edit_key_id]); var bind = binds[edit_index][edit_key_id]; var $bind = $("#" + edit_key_id); bind.title = $("#edit_key_title").val(); bind.action = $("#edit_key_action").val(); bind.color = "#" + $(".colpick_hex_field input").val(); console.log(bind); if (bind.action != "") { $bind.attr("title", bind.action); $bind.addClass("has_action"); } if (bind.color != "")
if (bind.title != "") { $("h2", $bind).html(bind.title); } }); $('#picker').colpick({ flat:true, layout:'hex', colorScheme:'dark', submit:0 }); $("#about").click(function() { $("#about-info").show(); }); $("#parse").click(function() { $("#parse-my-config").show(); }); $("#download").click(function() { var b = kbx_to_xon(binds); $("#d_my_config").val(b.join("\n")); $("#download-my-config").show(); }); $("#download2").click(function() { $("#d_my_kbx").val(JSON.stringify(binds)); $("#download-my-kbx").show(); }); $("#load").click(function() { $("#load-my-kbx").show(); }); $("#parse_it").click(function() { clearBinds(); var data = $("#my_config").val(); var cfg_array = data.split("\n"); var b = xon_to_kbx(cfg_array); b.forEach(function(e, i, a) { var key = Object.keys(e)[0]; var bind = e[key]; // loop through the JSON and apply it to the HTML // Load New if (bind.title != "" || bind.color != "") { var $bind = $("#" + key); if (bind.action != "") { $bind.attr("title", bind.action); $bind.addClass("has_action"); } if (bind.color != "") { $bind.css("background-color", bind.color); } if (bind.title != "") { $("h2", $bind).html(bind.title); } } }); }); $("#load_my_kbx").click(function() { clearBinds(); var data = $("#my_kbx").val(); var b = JSON.parse(data); b.forEach(function(e, i, a) { var key = Object.keys(e)[0]; var bind = e[key]; // loop through the JSON and apply it to the HTML // Load New if (bind.title != "" || bind.color != "") { var $bind = $("#" + key); if (bind.action != "") { $bind.attr("title", bind.action); $bind.addClass("has_action"); } if (bind.color != "") { $bind.css("background-color", bind.color); } if (bind.title != "") { $("h2", $bind).html(bind.title); } } }); }); $(".close").click(function() { var parent = $(this).parent().attr("id"); $("#" + parent).hide(); }); /* * Examples for debugging */ $("#kbx-to-xon").click(function(e) { kbx_to_xon(binds); }); $("#parse-vanilla").click(function(e) { // cfg to kbx JSON $.get("data/vanilla-config.cfg", function(data) { var cfg_array = data.split("\n"); xon_to_kbx(cfg_array); }); e.preventDefault(); }); $("#load-parsed-cfg").click(function(e) { clearBinds(); loadBindsFromJSON("vanilla_binds.txt"); }); $("#load-ninja-binds").click(function(e) { clearBinds(); loadBindsFromJSON("ninja_binds.txt"); }); /* * Parsing Functions */ // object to map kbx names to xonotic cfg var kbx_names = { "esc": "escape", "backtick": "backquote", "up": "uparrow", "right": "rightarrow", "down": "downarrow", "left": "leftarrow", "num_0": "kp_ins", "num_period": "kp_del", "num_3": "kp_pgdn", "num_6": "kp_rightarrow", "num_9": "kp_pgup", "num_8": "kp_uparrow", "num_7": "kp_home", "num_4": "kp_leftarrow", "num_1": "kp_end", "num_2": "kp_downarrow", "num_5": "kp_5", "num_enter": "kp_enter", "num_plus": "kp_plus", "num_minus": "kp_minus", "num_multiply": "kp_multiply", "num_slash": "kp_slash", "minus": "-", "plus": "=", "left_bracket": "[", "right_bracket": "]", "space_bar": "space", "mouse_wheel_up": "mwheelup", "mouse_wheel_down": "mwheeldown" }; // object to map xonotic cfg names to kbx var xon_names = { "escape": "esc", "backquote": "backtick", "-": "minus", "=": "plus", "[": "left_bracket", "]": "right_bracket", "space": "space_bar", "uparrow": "up", "leftarrow": "left", "downarrow": "down", "rightarrow": "right", "kp_slash": "num_slash", "kp_multiply": "num_multiply", "kp_minus": "num_minus", "kp_home": "num_7", "kp_uparrow": "num_8", "kp_pgup": "num_9", "kp_plus": "num_plus", "kp_leftarrow": "num_4", "kp_5": "num_5", "kp_rightarrow": "num_6", "kp_end": "num_1", "kp_downarrow": "num_2", "kp_pgdn": "num_3", "kp_enter": "num_enter", "kp_ins": "num_0", "kp_del": "num_period", "mwheelup": "mouse_wheel_up", "mwheeldown": "mouse_wheel_down" }; function kbx_to_xon(kbx_json) { var output = []; kbx_json.forEach(function(e, i, a) { var key = Object.keys(e)[0]; var bind = e[key]; var k = key.replace("key_",""); if (kbx_names[k] != undefined) { output.push('bind ' + kbx_names[k] + ' "' + bind.action + '" // ' + bind.title); } else { output.push('bind ' + k + ' "' + bind.action + '" // ' + bind.title); } }); console.log(output.join("\n")); return output; } function xon_to_kbx(cfg_array) { var output = []; cfg_array.forEach(function(e, i, a) { var re = /^bind (.+) "(.+)"( (.+))?/i; var raw = e.match(re); if (raw) { //console.log(raw); var bind = raw[1].toLowerCase(); var action = raw[2]; var key = xon_names[bind] || bind; key = "key_" + key; var o = {}; o[key] = { "title": action, "action": action, "color": "" }; output.push(o); } else { console.warn(e); } }); console.log(output); console.log(JSON.stringify(output)); return output; } });
{ $bind.css("background-color", bind.color); }
conditional_block
scripts.js
$(function(){ var binds = []; var edit_index = -1; var edit_key_id = null; function loadBindsFromJSON(file)
// Stupid hack to clear them for now function clearBinds() { $("#bind_container h2").html(""); $("#bind_container div").css("background-color",""); $("#bind_container div").attr("title",""); $("#bind_container div").removeClass("has_action"); } // Initial load loadBindsFromJSON("ninja_binds.txt"); /* * Other */ $(".key").each(function() { $(this).prepend('<i class="fa fa-pencil"></i>'); }); $(".key i").click(function() { var $key_editor = $("#key_editor"); var key_id = $(this).parent("div").attr("id"); var key_name = $(this).siblings("div").html(); $key_editor.show(); $("h3 span", $key_editor).html(key_name); //console.log(binds); // Look for the bind in the JSON binds.forEach(function(e, i, a) { var key = Object.keys(e)[0]; if (key == key_id) { var bind = e[key]; console.log(e[key]); console.log(i); edit_index = i; edit_key_id = key_id; $("#edit_key_title").val(bind.title); $("#edit_key_action").val(bind.action); if (bind.color != "") { $('#picker').colpickSetColor(bind.color); } else { $('#picker').colpickSetColor("#ffffff"); } return false; } }); }); $("#key_save").click(function() { console.log(binds[edit_index]); console.log(binds[edit_index][edit_key_id]); var bind = binds[edit_index][edit_key_id]; var $bind = $("#" + edit_key_id); bind.title = $("#edit_key_title").val(); bind.action = $("#edit_key_action").val(); bind.color = "#" + $(".colpick_hex_field input").val(); console.log(bind); if (bind.action != "") { $bind.attr("title", bind.action); $bind.addClass("has_action"); } if (bind.color != "") { $bind.css("background-color", bind.color); } if (bind.title != "") { $("h2", $bind).html(bind.title); } }); $('#picker').colpick({ flat:true, layout:'hex', colorScheme:'dark', submit:0 }); $("#about").click(function() { $("#about-info").show(); }); $("#parse").click(function() { $("#parse-my-config").show(); }); $("#download").click(function() { var b = kbx_to_xon(binds); $("#d_my_config").val(b.join("\n")); $("#download-my-config").show(); }); $("#download2").click(function() { $("#d_my_kbx").val(JSON.stringify(binds)); $("#download-my-kbx").show(); }); $("#load").click(function() { $("#load-my-kbx").show(); }); $("#parse_it").click(function() { clearBinds(); var data = $("#my_config").val(); var cfg_array = data.split("\n"); var b = xon_to_kbx(cfg_array); b.forEach(function(e, i, a) { var key = Object.keys(e)[0]; var bind = e[key]; // loop through the JSON and apply it to the HTML // Load New if (bind.title != "" || bind.color != "") { var $bind = $("#" + key); if (bind.action != "") { $bind.attr("title", bind.action); $bind.addClass("has_action"); } if (bind.color != "") { $bind.css("background-color", bind.color); } if (bind.title != "") { $("h2", $bind).html(bind.title); } } }); }); $("#load_my_kbx").click(function() { clearBinds(); var data = $("#my_kbx").val(); var b = JSON.parse(data); b.forEach(function(e, i, a) { var key = Object.keys(e)[0]; var bind = e[key]; // loop through the JSON and apply it to the HTML // Load New if (bind.title != "" || bind.color != "") { var $bind = $("#" + key); if (bind.action != "") { $bind.attr("title", bind.action); $bind.addClass("has_action"); } if (bind.color != "") { $bind.css("background-color", bind.color); } if (bind.title != "") { $("h2", $bind).html(bind.title); } } }); }); $(".close").click(function() { var parent = $(this).parent().attr("id"); $("#" + parent).hide(); }); /* * Examples for debugging */ $("#kbx-to-xon").click(function(e) { kbx_to_xon(binds); }); $("#parse-vanilla").click(function(e) { // cfg to kbx JSON $.get("data/vanilla-config.cfg", function(data) { var cfg_array = data.split("\n"); xon_to_kbx(cfg_array); }); e.preventDefault(); }); $("#load-parsed-cfg").click(function(e) { clearBinds(); loadBindsFromJSON("vanilla_binds.txt"); }); $("#load-ninja-binds").click(function(e) { clearBinds(); loadBindsFromJSON("ninja_binds.txt"); }); /* * Parsing Functions */ // object to map kbx names to xonotic cfg var kbx_names = { "esc": "escape", "backtick": "backquote", "up": "uparrow", "right": "rightarrow", "down": "downarrow", "left": "leftarrow", "num_0": "kp_ins", "num_period": "kp_del", "num_3": "kp_pgdn", "num_6": "kp_rightarrow", "num_9": "kp_pgup", "num_8": "kp_uparrow", "num_7": "kp_home", "num_4": "kp_leftarrow", "num_1": "kp_end", "num_2": "kp_downarrow", "num_5": "kp_5", "num_enter": "kp_enter", "num_plus": "kp_plus", "num_minus": "kp_minus", "num_multiply": "kp_multiply", "num_slash": "kp_slash", "minus": "-", "plus": "=", "left_bracket": "[", "right_bracket": "]", "space_bar": "space", "mouse_wheel_up": "mwheelup", "mouse_wheel_down": "mwheeldown" }; // object to map xonotic cfg names to kbx var xon_names = { "escape": "esc", "backquote": "backtick", "-": "minus", "=": "plus", "[": "left_bracket", "]": "right_bracket", "space": "space_bar", "uparrow": "up", "leftarrow": "left", "downarrow": "down", "rightarrow": "right", "kp_slash": "num_slash", "kp_multiply": "num_multiply", "kp_minus": "num_minus", "kp_home": "num_7", "kp_uparrow": "num_8", "kp_pgup": "num_9", "kp_plus": "num_plus", "kp_leftarrow": "num_4", "kp_5": "num_5", "kp_rightarrow": "num_6", "kp_end": "num_1", "kp_downarrow": "num_2", "kp_pgdn": "num_3", "kp_enter": "num_enter", "kp_ins": "num_0", "kp_del": "num_period", "mwheelup": "mouse_wheel_up", "mwheeldown": "mouse_wheel_down" }; function kbx_to_xon(kbx_json) { var output = []; kbx_json.forEach(function(e, i, a) { var key = Object.keys(e)[0]; var bind = e[key]; var k = key.replace("key_",""); if (kbx_names[k] != undefined) { output.push('bind ' + kbx_names[k] + ' "' + bind.action + '" // ' + bind.title); } else { output.push('bind ' + k + ' "' + bind.action + '" // ' + bind.title); } }); console.log(output.join("\n")); return output; } function xon_to_kbx(cfg_array) { var output = []; cfg_array.forEach(function(e, i, a) { var re = /^bind (.+) "(.+)"( (.+))?/i; var raw = e.match(re); if (raw) { //console.log(raw); var bind = raw[1].toLowerCase(); var action = raw[2]; var key = xon_names[bind] || bind; key = "key_" + key; var o = {}; o[key] = { "title": action, "action": action, "color": "" }; output.push(o); } else { console.warn(e); } }); console.log(output); console.log(JSON.stringify(output)); return output; } });
{ // Load Binds $.get("data/" + file, function(data) { binds = JSON.parse(data); binds.forEach(function(e, i, a) { var key = Object.keys(e)[0]; var bind = e[key]; // loop through the JSON and apply it to the HTML // Load New if (bind.title != "" || bind.color != "") { var $bind = $("#" + key); if (bind.action != "") { $bind.attr("title", bind.action); $bind.addClass("has_action"); } if (bind.color != "") { $bind.css("background-color", bind.color); } if (bind.title != "") { $("h2", $bind).html(bind.title); } } }); }); }
identifier_body
scripts.js
$(function(){ var binds = []; var edit_index = -1; var edit_key_id = null; function loadBindsFromJSON(file) { // Load Binds $.get("data/" + file, function(data) { binds = JSON.parse(data); binds.forEach(function(e, i, a) { var key = Object.keys(e)[0]; var bind = e[key]; // loop through the JSON and apply it to the HTML // Load New if (bind.title != "" || bind.color != "") { var $bind = $("#" + key); if (bind.action != "") { $bind.attr("title", bind.action); $bind.addClass("has_action"); } if (bind.color != "") { $bind.css("background-color", bind.color); } if (bind.title != "") { $("h2", $bind).html(bind.title); } } }); }); } // Stupid hack to clear them for now function clearBinds() { $("#bind_container h2").html(""); $("#bind_container div").css("background-color",""); $("#bind_container div").attr("title",""); $("#bind_container div").removeClass("has_action"); } // Initial load loadBindsFromJSON("ninja_binds.txt"); /* * Other */ $(".key").each(function() { $(this).prepend('<i class="fa fa-pencil"></i>'); }); $(".key i").click(function() { var $key_editor = $("#key_editor"); var key_id = $(this).parent("div").attr("id"); var key_name = $(this).siblings("div").html(); $key_editor.show(); $("h3 span", $key_editor).html(key_name); //console.log(binds); // Look for the bind in the JSON binds.forEach(function(e, i, a) { var key = Object.keys(e)[0]; if (key == key_id) { var bind = e[key]; console.log(e[key]); console.log(i); edit_index = i; edit_key_id = key_id; $("#edit_key_title").val(bind.title); $("#edit_key_action").val(bind.action); if (bind.color != "") { $('#picker').colpickSetColor(bind.color); } else { $('#picker').colpickSetColor("#ffffff"); } return false; } }); }); $("#key_save").click(function() { console.log(binds[edit_index]); console.log(binds[edit_index][edit_key_id]); var bind = binds[edit_index][edit_key_id]; var $bind = $("#" + edit_key_id); bind.title = $("#edit_key_title").val(); bind.action = $("#edit_key_action").val(); bind.color = "#" + $(".colpick_hex_field input").val(); console.log(bind); if (bind.action != "") { $bind.attr("title", bind.action); $bind.addClass("has_action"); } if (bind.color != "") { $bind.css("background-color", bind.color); } if (bind.title != "") { $("h2", $bind).html(bind.title); } }); $('#picker').colpick({ flat:true, layout:'hex', colorScheme:'dark', submit:0 }); $("#about").click(function() { $("#about-info").show(); }); $("#parse").click(function() { $("#parse-my-config").show(); }); $("#download").click(function() { var b = kbx_to_xon(binds); $("#d_my_config").val(b.join("\n")); $("#download-my-config").show(); }); $("#download2").click(function() { $("#d_my_kbx").val(JSON.stringify(binds)); $("#download-my-kbx").show(); }); $("#load").click(function() { $("#load-my-kbx").show(); }); $("#parse_it").click(function() { clearBinds(); var data = $("#my_config").val(); var cfg_array = data.split("\n"); var b = xon_to_kbx(cfg_array); b.forEach(function(e, i, a) { var key = Object.keys(e)[0]; var bind = e[key]; // loop through the JSON and apply it to the HTML // Load New if (bind.title != "" || bind.color != "") { var $bind = $("#" + key); if (bind.action != "") { $bind.attr("title", bind.action); $bind.addClass("has_action"); } if (bind.color != "") { $bind.css("background-color", bind.color); } if (bind.title != "") { $("h2", $bind).html(bind.title); } } }); }); $("#load_my_kbx").click(function() { clearBinds(); var data = $("#my_kbx").val(); var b = JSON.parse(data); b.forEach(function(e, i, a) { var key = Object.keys(e)[0]; var bind = e[key]; // loop through the JSON and apply it to the HTML // Load New if (bind.title != "" || bind.color != "") { var $bind = $("#" + key); if (bind.action != "") { $bind.attr("title", bind.action); $bind.addClass("has_action"); } if (bind.color != "") { $bind.css("background-color", bind.color); } if (bind.title != "") { $("h2", $bind).html(bind.title); } } }); }); $(".close").click(function() { var parent = $(this).parent().attr("id"); $("#" + parent).hide(); }); /* * Examples for debugging */ $("#kbx-to-xon").click(function(e) { kbx_to_xon(binds); }); $("#parse-vanilla").click(function(e) { // cfg to kbx JSON $.get("data/vanilla-config.cfg", function(data) { var cfg_array = data.split("\n"); xon_to_kbx(cfg_array); }); e.preventDefault(); }); $("#load-parsed-cfg").click(function(e) { clearBinds(); loadBindsFromJSON("vanilla_binds.txt"); }); $("#load-ninja-binds").click(function(e) { clearBinds(); loadBindsFromJSON("ninja_binds.txt"); }); /* * Parsing Functions */ // object to map kbx names to xonotic cfg var kbx_names = { "esc": "escape", "backtick": "backquote", "up": "uparrow", "right": "rightarrow", "down": "downarrow", "left": "leftarrow", "num_0": "kp_ins", "num_period": "kp_del", "num_3": "kp_pgdn", "num_6": "kp_rightarrow", "num_9": "kp_pgup", "num_8": "kp_uparrow", "num_7": "kp_home", "num_4": "kp_leftarrow", "num_1": "kp_end", "num_2": "kp_downarrow", "num_5": "kp_5", "num_enter": "kp_enter", "num_plus": "kp_plus", "num_minus": "kp_minus", "num_multiply": "kp_multiply", "num_slash": "kp_slash", "minus": "-", "plus": "=", "left_bracket": "[", "right_bracket": "]", "space_bar": "space", "mouse_wheel_up": "mwheelup", "mouse_wheel_down": "mwheeldown" }; // object to map xonotic cfg names to kbx var xon_names = { "escape": "esc", "backquote": "backtick", "-": "minus", "=": "plus", "[": "left_bracket", "]": "right_bracket", "space": "space_bar", "uparrow": "up", "leftarrow": "left", "downarrow": "down", "rightarrow": "right", "kp_slash": "num_slash", "kp_multiply": "num_multiply", "kp_minus": "num_minus", "kp_home": "num_7", "kp_uparrow": "num_8", "kp_pgup": "num_9", "kp_plus": "num_plus", "kp_leftarrow": "num_4", "kp_5": "num_5", "kp_rightarrow": "num_6", "kp_end": "num_1", "kp_downarrow": "num_2", "kp_pgdn": "num_3", "kp_enter": "num_enter", "kp_ins": "num_0", "kp_del": "num_period", "mwheelup": "mouse_wheel_up", "mwheeldown": "mouse_wheel_down" }; function kbx_to_xon(kbx_json) { var output = []; kbx_json.forEach(function(e, i, a) { var key = Object.keys(e)[0]; var bind = e[key]; var k = key.replace("key_",""); if (kbx_names[k] != undefined) { output.push('bind ' + kbx_names[k] + ' "' + bind.action + '" // ' + bind.title); } else { output.push('bind ' + k + ' "' + bind.action + '" // ' + bind.title); } }); console.log(output.join("\n")); return output; } function
(cfg_array) { var output = []; cfg_array.forEach(function(e, i, a) { var re = /^bind (.+) "(.+)"( (.+))?/i; var raw = e.match(re); if (raw) { //console.log(raw); var bind = raw[1].toLowerCase(); var action = raw[2]; var key = xon_names[bind] || bind; key = "key_" + key; var o = {}; o[key] = { "title": action, "action": action, "color": "" }; output.push(o); } else { console.warn(e); } }); console.log(output); console.log(JSON.stringify(output)); return output; } });
xon_to_kbx
identifier_name
scripts.js
$(function(){ var binds = []; var edit_index = -1; var edit_key_id = null; function loadBindsFromJSON(file) { // Load Binds $.get("data/" + file, function(data) { binds = JSON.parse(data); binds.forEach(function(e, i, a) { var key = Object.keys(e)[0]; var bind = e[key]; // loop through the JSON and apply it to the HTML // Load New if (bind.title != "" || bind.color != "") { var $bind = $("#" + key); if (bind.action != "") { $bind.attr("title", bind.action); $bind.addClass("has_action"); } if (bind.color != "") { $bind.css("background-color", bind.color); } if (bind.title != "") { $("h2", $bind).html(bind.title); } } }); }); } // Stupid hack to clear them for now function clearBinds() { $("#bind_container h2").html(""); $("#bind_container div").css("background-color",""); $("#bind_container div").attr("title",""); $("#bind_container div").removeClass("has_action"); } // Initial load loadBindsFromJSON("ninja_binds.txt"); /* * Other */ $(".key").each(function() { $(this).prepend('<i class="fa fa-pencil"></i>'); }); $(".key i").click(function() { var $key_editor = $("#key_editor"); var key_id = $(this).parent("div").attr("id"); var key_name = $(this).siblings("div").html(); $key_editor.show(); $("h3 span", $key_editor).html(key_name); //console.log(binds); // Look for the bind in the JSON binds.forEach(function(e, i, a) { var key = Object.keys(e)[0]; if (key == key_id) { var bind = e[key]; console.log(e[key]); console.log(i); edit_index = i; edit_key_id = key_id; $("#edit_key_title").val(bind.title);
if (bind.color != "") { $('#picker').colpickSetColor(bind.color); } else { $('#picker').colpickSetColor("#ffffff"); } return false; } }); }); $("#key_save").click(function() { console.log(binds[edit_index]); console.log(binds[edit_index][edit_key_id]); var bind = binds[edit_index][edit_key_id]; var $bind = $("#" + edit_key_id); bind.title = $("#edit_key_title").val(); bind.action = $("#edit_key_action").val(); bind.color = "#" + $(".colpick_hex_field input").val(); console.log(bind); if (bind.action != "") { $bind.attr("title", bind.action); $bind.addClass("has_action"); } if (bind.color != "") { $bind.css("background-color", bind.color); } if (bind.title != "") { $("h2", $bind).html(bind.title); } }); $('#picker').colpick({ flat:true, layout:'hex', colorScheme:'dark', submit:0 }); $("#about").click(function() { $("#about-info").show(); }); $("#parse").click(function() { $("#parse-my-config").show(); }); $("#download").click(function() { var b = kbx_to_xon(binds); $("#d_my_config").val(b.join("\n")); $("#download-my-config").show(); }); $("#download2").click(function() { $("#d_my_kbx").val(JSON.stringify(binds)); $("#download-my-kbx").show(); }); $("#load").click(function() { $("#load-my-kbx").show(); }); $("#parse_it").click(function() { clearBinds(); var data = $("#my_config").val(); var cfg_array = data.split("\n"); var b = xon_to_kbx(cfg_array); b.forEach(function(e, i, a) { var key = Object.keys(e)[0]; var bind = e[key]; // loop through the JSON and apply it to the HTML // Load New if (bind.title != "" || bind.color != "") { var $bind = $("#" + key); if (bind.action != "") { $bind.attr("title", bind.action); $bind.addClass("has_action"); } if (bind.color != "") { $bind.css("background-color", bind.color); } if (bind.title != "") { $("h2", $bind).html(bind.title); } } }); }); $("#load_my_kbx").click(function() { clearBinds(); var data = $("#my_kbx").val(); var b = JSON.parse(data); b.forEach(function(e, i, a) { var key = Object.keys(e)[0]; var bind = e[key]; // loop through the JSON and apply it to the HTML // Load New if (bind.title != "" || bind.color != "") { var $bind = $("#" + key); if (bind.action != "") { $bind.attr("title", bind.action); $bind.addClass("has_action"); } if (bind.color != "") { $bind.css("background-color", bind.color); } if (bind.title != "") { $("h2", $bind).html(bind.title); } } }); }); $(".close").click(function() { var parent = $(this).parent().attr("id"); $("#" + parent).hide(); }); /* * Examples for debugging */ $("#kbx-to-xon").click(function(e) { kbx_to_xon(binds); }); $("#parse-vanilla").click(function(e) { // cfg to kbx JSON $.get("data/vanilla-config.cfg", function(data) { var cfg_array = data.split("\n"); xon_to_kbx(cfg_array); }); e.preventDefault(); }); $("#load-parsed-cfg").click(function(e) { clearBinds(); loadBindsFromJSON("vanilla_binds.txt"); }); $("#load-ninja-binds").click(function(e) { clearBinds(); loadBindsFromJSON("ninja_binds.txt"); }); /* * Parsing Functions */ // object to map kbx names to xonotic cfg var kbx_names = { "esc": "escape", "backtick": "backquote", "up": "uparrow", "right": "rightarrow", "down": "downarrow", "left": "leftarrow", "num_0": "kp_ins", "num_period": "kp_del", "num_3": "kp_pgdn", "num_6": "kp_rightarrow", "num_9": "kp_pgup", "num_8": "kp_uparrow", "num_7": "kp_home", "num_4": "kp_leftarrow", "num_1": "kp_end", "num_2": "kp_downarrow", "num_5": "kp_5", "num_enter": "kp_enter", "num_plus": "kp_plus", "num_minus": "kp_minus", "num_multiply": "kp_multiply", "num_slash": "kp_slash", "minus": "-", "plus": "=", "left_bracket": "[", "right_bracket": "]", "space_bar": "space", "mouse_wheel_up": "mwheelup", "mouse_wheel_down": "mwheeldown" }; // object to map xonotic cfg names to kbx var xon_names = { "escape": "esc", "backquote": "backtick", "-": "minus", "=": "plus", "[": "left_bracket", "]": "right_bracket", "space": "space_bar", "uparrow": "up", "leftarrow": "left", "downarrow": "down", "rightarrow": "right", "kp_slash": "num_slash", "kp_multiply": "num_multiply", "kp_minus": "num_minus", "kp_home": "num_7", "kp_uparrow": "num_8", "kp_pgup": "num_9", "kp_plus": "num_plus", "kp_leftarrow": "num_4", "kp_5": "num_5", "kp_rightarrow": "num_6", "kp_end": "num_1", "kp_downarrow": "num_2", "kp_pgdn": "num_3", "kp_enter": "num_enter", "kp_ins": "num_0", "kp_del": "num_period", "mwheelup": "mouse_wheel_up", "mwheeldown": "mouse_wheel_down" }; function kbx_to_xon(kbx_json) { var output = []; kbx_json.forEach(function(e, i, a) { var key = Object.keys(e)[0]; var bind = e[key]; var k = key.replace("key_",""); if (kbx_names[k] != undefined) { output.push('bind ' + kbx_names[k] + ' "' + bind.action + '" // ' + bind.title); } else { output.push('bind ' + k + ' "' + bind.action + '" // ' + bind.title); } }); console.log(output.join("\n")); return output; } function xon_to_kbx(cfg_array) { var output = []; cfg_array.forEach(function(e, i, a) { var re = /^bind (.+) "(.+)"( (.+))?/i; var raw = e.match(re); if (raw) { //console.log(raw); var bind = raw[1].toLowerCase(); var action = raw[2]; var key = xon_names[bind] || bind; key = "key_" + key; var o = {}; o[key] = { "title": action, "action": action, "color": "" }; output.push(o); } else { console.warn(e); } }); console.log(output); console.log(JSON.stringify(output)); return output; } });
$("#edit_key_action").val(bind.action);
random_line_split
signals.py
""" This module contains signals related to enterprise. """ import logging import six from django.conf import settings from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from enterprise.models import EnterpriseCourseEnrollment, EnterpriseCustomer, EnterpriseCustomerUser from integrated_channels.integrated_channel.tasks import ( transmit_single_learner_data, transmit_single_subsection_learner_data ) from slumber.exceptions import HttpClientError from lms.djangoapps.email_marketing.tasks import update_user from openedx.core.djangoapps.commerce.utils import ecommerce_api_client from openedx.core.djangoapps.signals.signals import COURSE_GRADE_NOW_PASSED, COURSE_ASSESSMENT_GRADE_CHANGED from openedx.features.enterprise_support.api import enterprise_enabled from openedx.features.enterprise_support.tasks import clear_enterprise_customer_data_consent_share_cache from openedx.features.enterprise_support.utils import clear_data_consent_share_cache, is_enterprise_learner from common.djangoapps.student.signals import UNENROLL_DONE log = logging.getLogger(__name__) @receiver(post_save, sender=EnterpriseCustomerUser) def update_email_marketing_user_with_enterprise_vars(sender, instance, **kwargs): # pylint: disable=unused-argument, invalid-name """ Update the SailThru user with enterprise-related vars. """ user = User.objects.get(id=instance.user_id) # perform update asynchronously update_user.delay( sailthru_vars={ 'is_enterprise_learner': True, 'enterprise_name': instance.enterprise_customer.name, }, email=user.email ) @receiver(post_save, sender=EnterpriseCourseEnrollment) def update_dsc_cache_on_course_enrollment(sender, instance, **kwargs): # pylint: disable=unused-argument
@receiver(pre_save, sender=EnterpriseCustomer) def update_dsc_cache_on_enterprise_customer_update(sender, instance, **kwargs): """ clears data_sharing_consent_needed cache after enable_data_sharing_consent flag is changed. """ old_instance = sender.objects.filter(pk=instance.uuid).first() if old_instance: # instance already exists, so it's updating. new_value = instance.enable_data_sharing_consent old_value = old_instance.enable_data_sharing_consent if new_value != old_value: kwargs = {'enterprise_customer_uuid': six.text_type(instance.uuid)} result = clear_enterprise_customer_data_consent_share_cache.apply_async(kwargs=kwargs) log.info(u"DSC: Created {task_name}[{task_id}] with arguments {kwargs}".format( task_name=clear_enterprise_customer_data_consent_share_cache.name, task_id=result.task_id, kwargs=kwargs, )) @receiver(COURSE_GRADE_NOW_PASSED, dispatch_uid="new_passing_enterprise_learner") def handle_enterprise_learner_passing_grade(sender, user, course_id, **kwargs): # pylint: disable=unused-argument """ Listen for a learner passing a course, transmit data to relevant integrated channel """ if enterprise_enabled() and is_enterprise_learner(user): kwargs = { 'username': six.text_type(user.username), 'course_run_id': six.text_type(course_id) } transmit_single_learner_data.apply_async(kwargs=kwargs) @receiver(COURSE_ASSESSMENT_GRADE_CHANGED) def handle_enterprise_learner_subsection(sender, user, course_id, subsection_id, subsection_grade, **kwargs): # pylint: disable=unused-argument """ Listen for an enterprise learner completing a subsection, transmit data to relevant integrated channel. """ if enterprise_enabled() and is_enterprise_learner(user): kwargs = { 'username': str(user.username), 'course_run_id': str(course_id), 'subsection_id': str(subsection_id), 'grade': str(subsection_grade), } transmit_single_subsection_learner_data.apply_async(kwargs=kwargs) @receiver(UNENROLL_DONE) def refund_order_voucher(sender, course_enrollment, skip_refund=False, **kwargs): # pylint: disable=unused-argument """ Call the /api/v2/enterprise/coupons/create_refunded_voucher/ API to create new voucher and assign it to user. """ if skip_refund: return if not course_enrollment.refundable(): return if not EnterpriseCourseEnrollment.objects.filter( enterprise_customer_user__user_id=course_enrollment.user_id, course_id=str(course_enrollment.course.id) ).exists(): return service_user = User.objects.get(username=settings.ECOMMERCE_SERVICE_WORKER_USERNAME) client = ecommerce_api_client(service_user) order_number = course_enrollment.get_order_attribute_value('order_number') if order_number: error_message = u"Encountered {} from ecommerce while creating refund voucher. Order={}, enrollment={}, user={}" try: client.enterprise.coupons.create_refunded_voucher.post({"order": order_number}) except HttpClientError as ex: log.info( error_message.format(type(ex).__name__, order_number, course_enrollment, course_enrollment.user) ) except Exception as ex: # pylint: disable=broad-except log.exception( error_message.format(type(ex).__name__, order_number, course_enrollment, course_enrollment.user) )
""" clears data_sharing_consent_needed cache after Enterprise Course Enrollment """ clear_data_consent_share_cache( instance.enterprise_customer_user.user_id, instance.course_id )
identifier_body
signals.py
""" This module contains signals related to enterprise. """ import logging import six from django.conf import settings from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from enterprise.models import EnterpriseCourseEnrollment, EnterpriseCustomer, EnterpriseCustomerUser from integrated_channels.integrated_channel.tasks import ( transmit_single_learner_data, transmit_single_subsection_learner_data ) from slumber.exceptions import HttpClientError from lms.djangoapps.email_marketing.tasks import update_user from openedx.core.djangoapps.commerce.utils import ecommerce_api_client from openedx.core.djangoapps.signals.signals import COURSE_GRADE_NOW_PASSED, COURSE_ASSESSMENT_GRADE_CHANGED from openedx.features.enterprise_support.api import enterprise_enabled from openedx.features.enterprise_support.tasks import clear_enterprise_customer_data_consent_share_cache from openedx.features.enterprise_support.utils import clear_data_consent_share_cache, is_enterprise_learner from common.djangoapps.student.signals import UNENROLL_DONE log = logging.getLogger(__name__) @receiver(post_save, sender=EnterpriseCustomerUser) def update_email_marketing_user_with_enterprise_vars(sender, instance, **kwargs): # pylint: disable=unused-argument, invalid-name """ Update the SailThru user with enterprise-related vars. """ user = User.objects.get(id=instance.user_id) # perform update asynchronously update_user.delay( sailthru_vars={ 'is_enterprise_learner': True, 'enterprise_name': instance.enterprise_customer.name, }, email=user.email ) @receiver(post_save, sender=EnterpriseCourseEnrollment) def
(sender, instance, **kwargs): # pylint: disable=unused-argument """ clears data_sharing_consent_needed cache after Enterprise Course Enrollment """ clear_data_consent_share_cache( instance.enterprise_customer_user.user_id, instance.course_id ) @receiver(pre_save, sender=EnterpriseCustomer) def update_dsc_cache_on_enterprise_customer_update(sender, instance, **kwargs): """ clears data_sharing_consent_needed cache after enable_data_sharing_consent flag is changed. """ old_instance = sender.objects.filter(pk=instance.uuid).first() if old_instance: # instance already exists, so it's updating. new_value = instance.enable_data_sharing_consent old_value = old_instance.enable_data_sharing_consent if new_value != old_value: kwargs = {'enterprise_customer_uuid': six.text_type(instance.uuid)} result = clear_enterprise_customer_data_consent_share_cache.apply_async(kwargs=kwargs) log.info(u"DSC: Created {task_name}[{task_id}] with arguments {kwargs}".format( task_name=clear_enterprise_customer_data_consent_share_cache.name, task_id=result.task_id, kwargs=kwargs, )) @receiver(COURSE_GRADE_NOW_PASSED, dispatch_uid="new_passing_enterprise_learner") def handle_enterprise_learner_passing_grade(sender, user, course_id, **kwargs): # pylint: disable=unused-argument """ Listen for a learner passing a course, transmit data to relevant integrated channel """ if enterprise_enabled() and is_enterprise_learner(user): kwargs = { 'username': six.text_type(user.username), 'course_run_id': six.text_type(course_id) } transmit_single_learner_data.apply_async(kwargs=kwargs) @receiver(COURSE_ASSESSMENT_GRADE_CHANGED) def handle_enterprise_learner_subsection(sender, user, course_id, subsection_id, subsection_grade, **kwargs): # pylint: disable=unused-argument """ Listen for an enterprise learner completing a subsection, transmit data to relevant integrated channel. """ if enterprise_enabled() and is_enterprise_learner(user): kwargs = { 'username': str(user.username), 'course_run_id': str(course_id), 'subsection_id': str(subsection_id), 'grade': str(subsection_grade), } transmit_single_subsection_learner_data.apply_async(kwargs=kwargs) @receiver(UNENROLL_DONE) def refund_order_voucher(sender, course_enrollment, skip_refund=False, **kwargs): # pylint: disable=unused-argument """ Call the /api/v2/enterprise/coupons/create_refunded_voucher/ API to create new voucher and assign it to user. """ if skip_refund: return if not course_enrollment.refundable(): return if not EnterpriseCourseEnrollment.objects.filter( enterprise_customer_user__user_id=course_enrollment.user_id, course_id=str(course_enrollment.course.id) ).exists(): return service_user = User.objects.get(username=settings.ECOMMERCE_SERVICE_WORKER_USERNAME) client = ecommerce_api_client(service_user) order_number = course_enrollment.get_order_attribute_value('order_number') if order_number: error_message = u"Encountered {} from ecommerce while creating refund voucher. Order={}, enrollment={}, user={}" try: client.enterprise.coupons.create_refunded_voucher.post({"order": order_number}) except HttpClientError as ex: log.info( error_message.format(type(ex).__name__, order_number, course_enrollment, course_enrollment.user) ) except Exception as ex: # pylint: disable=broad-except log.exception( error_message.format(type(ex).__name__, order_number, course_enrollment, course_enrollment.user) )
update_dsc_cache_on_course_enrollment
identifier_name
signals.py
""" This module contains signals related to enterprise. """ import logging import six from django.conf import settings from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from enterprise.models import EnterpriseCourseEnrollment, EnterpriseCustomer, EnterpriseCustomerUser from integrated_channels.integrated_channel.tasks import ( transmit_single_learner_data, transmit_single_subsection_learner_data ) from slumber.exceptions import HttpClientError from lms.djangoapps.email_marketing.tasks import update_user from openedx.core.djangoapps.commerce.utils import ecommerce_api_client from openedx.core.djangoapps.signals.signals import COURSE_GRADE_NOW_PASSED, COURSE_ASSESSMENT_GRADE_CHANGED from openedx.features.enterprise_support.api import enterprise_enabled from openedx.features.enterprise_support.tasks import clear_enterprise_customer_data_consent_share_cache from openedx.features.enterprise_support.utils import clear_data_consent_share_cache, is_enterprise_learner from common.djangoapps.student.signals import UNENROLL_DONE log = logging.getLogger(__name__) @receiver(post_save, sender=EnterpriseCustomerUser) def update_email_marketing_user_with_enterprise_vars(sender, instance, **kwargs): # pylint: disable=unused-argument, invalid-name """ Update the SailThru user with enterprise-related vars. """ user = User.objects.get(id=instance.user_id) # perform update asynchronously update_user.delay( sailthru_vars={ 'is_enterprise_learner': True, 'enterprise_name': instance.enterprise_customer.name, }, email=user.email ) @receiver(post_save, sender=EnterpriseCourseEnrollment) def update_dsc_cache_on_course_enrollment(sender, instance, **kwargs): # pylint: disable=unused-argument """ clears data_sharing_consent_needed cache after Enterprise Course Enrollment """ clear_data_consent_share_cache( instance.enterprise_customer_user.user_id, instance.course_id ) @receiver(pre_save, sender=EnterpriseCustomer) def update_dsc_cache_on_enterprise_customer_update(sender, instance, **kwargs): """ clears data_sharing_consent_needed cache after enable_data_sharing_consent flag is changed. """ old_instance = sender.objects.filter(pk=instance.uuid).first() if old_instance: # instance already exists, so it's updating. new_value = instance.enable_data_sharing_consent old_value = old_instance.enable_data_sharing_consent if new_value != old_value: kwargs = {'enterprise_customer_uuid': six.text_type(instance.uuid)} result = clear_enterprise_customer_data_consent_share_cache.apply_async(kwargs=kwargs) log.info(u"DSC: Created {task_name}[{task_id}] with arguments {kwargs}".format( task_name=clear_enterprise_customer_data_consent_share_cache.name, task_id=result.task_id, kwargs=kwargs, )) @receiver(COURSE_GRADE_NOW_PASSED, dispatch_uid="new_passing_enterprise_learner") def handle_enterprise_learner_passing_grade(sender, user, course_id, **kwargs): # pylint: disable=unused-argument """ Listen for a learner passing a course, transmit data to relevant integrated channel """ if enterprise_enabled() and is_enterprise_learner(user): kwargs = { 'username': six.text_type(user.username), 'course_run_id': six.text_type(course_id) } transmit_single_learner_data.apply_async(kwargs=kwargs) @receiver(COURSE_ASSESSMENT_GRADE_CHANGED) def handle_enterprise_learner_subsection(sender, user, course_id, subsection_id, subsection_grade, **kwargs): # pylint: disable=unused-argument """ Listen for an enterprise learner completing a subsection, transmit data to relevant integrated channel. """ if enterprise_enabled() and is_enterprise_learner(user): kwargs = { 'username': str(user.username), 'course_run_id': str(course_id), 'subsection_id': str(subsection_id), 'grade': str(subsection_grade), } transmit_single_subsection_learner_data.apply_async(kwargs=kwargs) @receiver(UNENROLL_DONE) def refund_order_voucher(sender, course_enrollment, skip_refund=False, **kwargs): # pylint: disable=unused-argument """ Call the /api/v2/enterprise/coupons/create_refunded_voucher/ API to create new voucher and assign it to user. """ if skip_refund: return if not course_enrollment.refundable(): return if not EnterpriseCourseEnrollment.objects.filter( enterprise_customer_user__user_id=course_enrollment.user_id, course_id=str(course_enrollment.course.id) ).exists(): return service_user = User.objects.get(username=settings.ECOMMERCE_SERVICE_WORKER_USERNAME) client = ecommerce_api_client(service_user) order_number = course_enrollment.get_order_attribute_value('order_number') if order_number: error_message = u"Encountered {} from ecommerce while creating refund voucher. Order={}, enrollment={}, user={}" try: client.enterprise.coupons.create_refunded_voucher.post({"order": order_number}) except HttpClientError as ex: log.info( error_message.format(type(ex).__name__, order_number, course_enrollment, course_enrollment.user) ) except Exception as ex: # pylint: disable=broad-except
log.exception( error_message.format(type(ex).__name__, order_number, course_enrollment, course_enrollment.user) )
random_line_split
signals.py
""" This module contains signals related to enterprise. """ import logging import six from django.conf import settings from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from enterprise.models import EnterpriseCourseEnrollment, EnterpriseCustomer, EnterpriseCustomerUser from integrated_channels.integrated_channel.tasks import ( transmit_single_learner_data, transmit_single_subsection_learner_data ) from slumber.exceptions import HttpClientError from lms.djangoapps.email_marketing.tasks import update_user from openedx.core.djangoapps.commerce.utils import ecommerce_api_client from openedx.core.djangoapps.signals.signals import COURSE_GRADE_NOW_PASSED, COURSE_ASSESSMENT_GRADE_CHANGED from openedx.features.enterprise_support.api import enterprise_enabled from openedx.features.enterprise_support.tasks import clear_enterprise_customer_data_consent_share_cache from openedx.features.enterprise_support.utils import clear_data_consent_share_cache, is_enterprise_learner from common.djangoapps.student.signals import UNENROLL_DONE log = logging.getLogger(__name__) @receiver(post_save, sender=EnterpriseCustomerUser) def update_email_marketing_user_with_enterprise_vars(sender, instance, **kwargs): # pylint: disable=unused-argument, invalid-name """ Update the SailThru user with enterprise-related vars. """ user = User.objects.get(id=instance.user_id) # perform update asynchronously update_user.delay( sailthru_vars={ 'is_enterprise_learner': True, 'enterprise_name': instance.enterprise_customer.name, }, email=user.email ) @receiver(post_save, sender=EnterpriseCourseEnrollment) def update_dsc_cache_on_course_enrollment(sender, instance, **kwargs): # pylint: disable=unused-argument """ clears data_sharing_consent_needed cache after Enterprise Course Enrollment """ clear_data_consent_share_cache( instance.enterprise_customer_user.user_id, instance.course_id ) @receiver(pre_save, sender=EnterpriseCustomer) def update_dsc_cache_on_enterprise_customer_update(sender, instance, **kwargs): """ clears data_sharing_consent_needed cache after enable_data_sharing_consent flag is changed. """ old_instance = sender.objects.filter(pk=instance.uuid).first() if old_instance: # instance already exists, so it's updating. new_value = instance.enable_data_sharing_consent old_value = old_instance.enable_data_sharing_consent if new_value != old_value: kwargs = {'enterprise_customer_uuid': six.text_type(instance.uuid)} result = clear_enterprise_customer_data_consent_share_cache.apply_async(kwargs=kwargs) log.info(u"DSC: Created {task_name}[{task_id}] with arguments {kwargs}".format( task_name=clear_enterprise_customer_data_consent_share_cache.name, task_id=result.task_id, kwargs=kwargs, )) @receiver(COURSE_GRADE_NOW_PASSED, dispatch_uid="new_passing_enterprise_learner") def handle_enterprise_learner_passing_grade(sender, user, course_id, **kwargs): # pylint: disable=unused-argument """ Listen for a learner passing a course, transmit data to relevant integrated channel """ if enterprise_enabled() and is_enterprise_learner(user): kwargs = { 'username': six.text_type(user.username), 'course_run_id': six.text_type(course_id) } transmit_single_learner_data.apply_async(kwargs=kwargs) @receiver(COURSE_ASSESSMENT_GRADE_CHANGED) def handle_enterprise_learner_subsection(sender, user, course_id, subsection_id, subsection_grade, **kwargs): # pylint: disable=unused-argument """ Listen for an enterprise learner completing a subsection, transmit data to relevant integrated channel. """ if enterprise_enabled() and is_enterprise_learner(user): kwargs = { 'username': str(user.username), 'course_run_id': str(course_id), 'subsection_id': str(subsection_id), 'grade': str(subsection_grade), } transmit_single_subsection_learner_data.apply_async(kwargs=kwargs) @receiver(UNENROLL_DONE) def refund_order_voucher(sender, course_enrollment, skip_refund=False, **kwargs): # pylint: disable=unused-argument """ Call the /api/v2/enterprise/coupons/create_refunded_voucher/ API to create new voucher and assign it to user. """ if skip_refund: return if not course_enrollment.refundable():
if not EnterpriseCourseEnrollment.objects.filter( enterprise_customer_user__user_id=course_enrollment.user_id, course_id=str(course_enrollment.course.id) ).exists(): return service_user = User.objects.get(username=settings.ECOMMERCE_SERVICE_WORKER_USERNAME) client = ecommerce_api_client(service_user) order_number = course_enrollment.get_order_attribute_value('order_number') if order_number: error_message = u"Encountered {} from ecommerce while creating refund voucher. Order={}, enrollment={}, user={}" try: client.enterprise.coupons.create_refunded_voucher.post({"order": order_number}) except HttpClientError as ex: log.info( error_message.format(type(ex).__name__, order_number, course_enrollment, course_enrollment.user) ) except Exception as ex: # pylint: disable=broad-except log.exception( error_message.format(type(ex).__name__, order_number, course_enrollment, course_enrollment.user) )
return
conditional_block
statevector.js
//________________________________________________________________________________________________ // statevector.js //todo: update description // // cStateVector object - This is a generic container useful for ... // Every item added to the queue is time stamped for time series analyis, playback, etc. // There are optional functions onAdd[1,2,..]() that the user can define that will be //cp-not right!!!!! // called each time imageUpdate() is called. // // Note that the debug statements are commented outin some functions to reduce vpRefresh time. //cp-mention that this saves mouse & moves only > a fixed amount... // // history // 1106 cperz created // _______________________________________end_Rel 12.1 __________________________________________ // // 131119 cperz renamed imageUpdate to viewUpdate to avoid confusion with public interface // // todo // - could make queue trim on time instead of size (with size max still...) // - add methods for getlast direction, mouse position, etc.... // much more straightforward, no need to understand internal storage of this object! //________________________________________________________________________________________________ // state types: // image: set by viewUpdate() // mouse: set by mouseUpdate() // us.eStateTypes = { image: 0, mouse: 1 }; //________________________________________________________________________________________________ function cStateVector(vpObj) { var thisImg = vpObj; // the viewport object - the parent var self = this; // local var for closure var imageId_ = thisImg.getImageId(); var uScopeIdx_ = thisImg.getImageIdx(); var imageSizeMax; var mouseSizeMax; var idxPrevNext = -1; // index in image queue var idxPrevNextStart = -1; // index of starting position of prev/next sequence var d = new Date(); var dTime = 1. / 10.; // get the start time and scale it from millisecs to 1/100th sec var startTime = d.getTime() * dTime; var imageQueue = []; // the image state vector queue var mouseQueue = []; // the mouse state vector queue var cb_imageState = []; // array of image state function callbacks var cb_mouseState = []; // array of mouse state function callbacks var stateTypeView = us.eStateTypes.view; // for quick access var stateTypeMouse = us.eStateTypes.mouse; var minMoveMagnitude_ = 12; // the minimum magnitude in pixels of movement to record var slopeLimit = 4; var slopeLimtInv = 0.25; // 1. / slopeLimit var kSVQUEUE_VIEW_SIZE = 500; // number of view states to retain in state vector queue // this throttles the responsivity of the state vector! //............................................ _sinceStartTime local // This function is used for all time stamps in this object. // It converts absolute time from "new Date().getTime()" to a differntial in seconds // (to the 3rd decimal place - milliseconds) since the start time of this object. var _sinceStartTime = function (time) { return (time * dTime - startTime).toFixed(3); }; //............................................ _setSize local // This function sets the image and mouse queue maximum sizes. var _setSize = function (newSize) { var newMax = (newSize) ? newSize : 200; // maximum size for queue if (newMax < 1 || newMax > 2000) // sanity check on the queue size return; imageSizeMax = newMax; mouseSizeMax = 100; // parseInt(newMax / 2); // limit the mouse queue to half the size while (imageQueue.length > imageSizeMax) imageQueue.shift(); while (mouseQueue.length > mouseSizeMax) mouseQueue.shift(); }; //............................................ registerForEvent // This function adds a subscription to state change event. // The imageUpdate() and mouseUpdate() functions call these subscribers. // this.registerForEvent = function (functionString, stateType) { if (typeof functionString === "function") { if (isUnDefined(stateType)) stateType = us.eStateTypes.view; if (us.DBGSTATEVECTOR) thisImg.log("statevector: add callback: (" + functionString + ") Type: " + stateType); if (stateType === us.eStateTypes.view) cb_imageState.push(functionString); else cb_mouseState.push(functionString); } }; //............................................ unRegisterForEvent // This function removes a subscription to state change event. this.unRegisterForEvent = function (functionString) { // find a string match in the call back arrays and remove it. if (typeof functionString === "function") { functionString = functionString.toString(); // search image state queue for the event for (var c = 0, len = cb_imageState.length; c < len; c++) { var str = cb_imageState[c].toString(); if (str.indexOf(functionString) !== -1) { if (us.DBGSTATEVECTOR) thisImg.log("statevector: remove image callback: (" + functionString + ")"); cb_imageState.remove(c); return; } } // search mouse state queue for the event for (var c = 0, len = cb_mouseState.length; c < len; c++) { var str = cb_mouseState[c].toString(); if (str.indexOf(functionString) !== -1) { if (us.DBGSTATEVECTOR) thisImg.log("statevector: remove mouse callback: (" + functionString + ")"); cb_mouseState.remove(c); return; } } } }; //............................................ viewUpdate // This function adds an image state vector to its queue. // If the state description is a move, the city block distance between this position and the previous state on the queue // must be greater than a threshold. Otherwise the state is not added to the queue. // // An Image State Vector is a definition of the view state plus: // time stamp // + desc {"all", "move", "zoom", "focus", "dims", } // + viewport's vpView contents {left, top, width, height, zoom, focus, angleDeg} // + dir {"none", "wholeview", "north", "east", "west", "south", northwest, ...} //cp-fill in and define // + magpx { magnitude of move in pixels } // // parameters // state: is viewport's vpView contents // changeDesc: {"all", "move", "zoom", "focus", "dims", "rotate"} // // todo: // - I'd like to know if there are listenters, perhaps I don't do all this if not var lastViewState_ = new cPoint(0,0); this.viewUpdate = function (state, changeDesc) { var zoom = state.zoom; var x = state.left; var y = state.top; //debug-only thisImg.log("image state: X,Y,ZOOM: " + x + "," + y + "," + zoom); if (imageQueue.length == imageSizeMax) // maintain queue size imageQueue.shift(); // remove the top element of the array to make room at the bottom var magpx = 0; if (changeDesc == "move") { // throttle the responsivity to motion var magpx = Math.abs(state.left - lastViewState_.x) + Math.abs(state.top - lastViewState_.y); // city-street magnitude of move in pixels if (magpx < minMoveMagnitude_) { //dbg-only if (us.DBGSTATEVECTOREX) thisImg.log("cStateVector: viewUpdate: magnitude of move (" + magpx + ") < minimum (" + minMoveMagnitude_ + ")"); return; } //consoleWrite("cur state: " + state.left + "," + state.top + " last state: " + lastViewState_.toString() + " magpx: " + magpx); } var sv = []; // add info to new state vector sv.time = _sinceStartTime(new Date().getTime()); // add time stamp sv.desc = changeDesc; // add input change description sv.state = jQuery.extend(true, {}, state); // add input view state, must clone state first if (changeDesc == "move") // sv.magpx = magpx; // add magnitude of move (units are pixels) _computeDir(sv); // add computed direction 'dir' imageQueue.push(sv); // add state vector to the queue lastViewState_.set(state.left, state.top); // save last queue view position //if (us.DBGSTATEVECTOR) sv.magpx ? thisImg.log("cStateVector: viewUpdate: dir: " + sv.dir + " magpx: " + sv.magpx) // : thisImg.log("cStateVector: viewUpdate: desc: " + sv.desc); for (var c = 0, len = cb_imageState.length; c < len; c++) // execute the callbacks to signal a SV update event cb_imageState[c](); triggerUScopeEvent(us.evVIEWCHANGE, { // fire event that the view has changed imageId: imageId_, uScopeIdx: uScopeIdx_, desc: sv.desc, x: thisImg.getViewCenterX(), y: thisImg.getViewCenterY(), zoom: zoom, angleDeg: state.angleDeg }); }; //............................................ mouseUpdate // This function adds an mouse state vector to its queue. // If the state description is a mousemove, the city block distance between this position and the previous state on the queue // must be greater than a threshold. Otherwise the state is not added to the queue. // // A Mouse State Vector is a definition of the mouse state: // time stamp // + desc {"mousemove", "mousedown", ...} // + state cPoint {x,y} of mouse position in base image coordinates // // parameters // state: cPoint {x,y} of mouse position in base image coordinates // eventDesc: {"mousemove", "mousedown",} // bForce: boolean, if true the function does not exit when there are no listeners // so us.evMOUSECHANGE event is fired if mouse move is sufficient var lastMouseState_ = new cPoint(0, 0); this.mouseUpdate = function (state, eventDesc, bForce) { if (bForce == false && cb_mouseState.length == 0) // do not save state if no one is subscribed return; //dbg-only if (us.DBGSTATEVECTOREX) thisImg.log("cStateVector: mouseUpdate: " + state.toString() + " desc: " + eventDesc); if (mouseQueue.length == mouseSizeMax) // maintain queue size mouseQueue.shift(); // remove the top element of the array to make room at the bottom var magpx = 0; if (eventDesc == "mousemove") { if (lastMouseState_) { // throttle the responsivity to motion magpx = lastMouseState_.cityBlockDistance(state); //consoleWrite("cur state: " + state + " last state: " + lastMouseState_.toString() + " magpx: " + magpx); if (magpx < minMoveMagnitude_) { //dbg-only if (us.DBGSTATEVECTOREX) thisImg.log("cStateVector: mouseUpdate: magnitude of move (" + magpx + ") < minimum (" + minMoveMagnitude_ + ")"); return; } } } var sv = []; // add info to new state vector sv.time = _sinceStartTime(new Date().getTime()); // add time stamp sv.desc = eventDesc; // add input change description sv.state = jQuery.extend(true, {}, state); // add input view state, must clone state first mouseQueue.push(sv); // add state vector to the queue lastMouseState_.setPoint(sv.state); // save last queue mouse position //dbg-only if (us.DBGSTATEVECTOREX) thisImg.log("cStateVector: mouseUpdate: desc: " + sv.desc + sv.state.toString() + " magnitude: " + magpx); for (var c = 0, len = cb_mouseState.length; c < len; c++) // execute the callbacks to signal a SV update event cb_mouseState[c](); triggerUScopeEvent(us.evMOUSECHANGE, { imageId: imageId_, uScopeIdx: uScopeIdx_, uScopeIdx: thisImg.getImageIdx(), x: state.x, y: state.y }); }; //............................................ getLastMousePosition // This function returns the last recorded mouse position or undefined if none have been recorded. this.getLastMousePosition = function () { return (mouseQueue.length > 0) ? mouseQueue[mouseQueue.length - 1].state : undefined; }; //............................................ getMouseEventsSince // This function returns an array in ascending order of the mouse events since a specified time. // The time stamp in the list of events is in this object's format - delta time since the start of the object scaled by dTime; // Optionally a specific type of mouse event can be selected. // A maximum number of returned events is enforced but can be overridden. // // parameters: // sinceTime required, time to start collecting the event, sinceTime = new Date().getTime() // eventDesc optional, return this mouse event type {"mousemove", "mousedown", ...} default is all // maxRtnSize optional, maximum number of mousestates to return, default is 100 this.getMouseEventsSince = function (sinceTime, eventDesc, maxRtnSize) { var rtnQueue = []; if (isUnDefined(sinceTime)) return rtnQueue; sinceTime = _sinceStartTime(sinceTime); // convert to same time format as used here in if (mouseQueue.length > 0) { eventDesc = (eventDesc) ? eventDesc : "all"; // set event filter maxRtnSize = (maxRtnSize) ? maxRtnSize + 1 : 101; // set limit of number of items returned var cnt = 0; var startIdx = mouseQueue.length; while (--startIdx > 0 && ++cnt < maxRtnSize) { if (mouseQueue[startIdx].time < sinceTime) // am I now before my time? break; if (eventDesc == "all" || eventDesc == mouseQueue[startIdx].desc) rtnQueue.unshift(mouseQueue[startIdx]); // add to the begining of the array for ascending order } } return rtnQueue; }; //............................................ getPrevNext this.getPrevNext = function (incr) {//incr s/b +/-1 if (imageQueue.length < 1) return undefined; var rtnSV = undefined; if (idxPrevNext == -1) { idxPrevNext = imageQueue.length - 1 + incr; idxPrevNextStart = imageQueue.length - 1; } else { idxPrevNext = idxPrevNext + incr; if (idxPrevNext > idxPrevNextStart) idxPrevNext = idxPrevNextStart; // don't move past starting position } /////thisImg.log("getPrevNext: idxPrevNext: " + idxPrevNext); if (idxPrevNext > 0 && idxPrevNext < imageQueue.length) rtnSV = imageQueue[idxPrevNext]; if (idxPrevNext == idxPrevNextStart) idxPrevNext = -1; //reset return rtnSV; }; //............................................ getLastDirection // This function returns the last recorded image direction or undefined if none have been recorded. this.getLastDirection = function () { return (imageQueue.length > 0) ? imageQueue[imageQueue.length - 1].dir : undefined; }; //............................................ getLastDescription // This function returns the last recorded image description or undefined if none have been recorded. this.getLastDescription = function () { return (imageQueue.length > 0) ? imageQueue[imageQueue.length - 1].desc : undefined; }; //............................................ getLast // This function returns the last state vector for the specified state type. this.getLast = function (stateType) {//cp-todo rename to get LastState if (isUnDefined(stateType)) stateType = us.eStateTypes.view; if (stateType === us.eStateTypes.view) return (imageQueue.length > 0) ? imageQueue[imageQueue.length - 1] : undefined; else return (mouseQueue.length > 0) ? mouseQueue[mouseQueue.length - 1] : undefined; }; //............................................ reportLast // This function returns a string containing the last state vector report for the specified state type. this.reportLast = function (stateType) { var str = ""; var queue = (stateType === us.eStateTypes.view) ? imageQueue : mouseQueue; if (queue.length > 0) { str = (stateType === us.eStateTypes.view) ? "LastViewState: " : "LastMouseState: "; var state = queue[queue.length - 1]; str += this.report(state, stateType); } return str; }; //............................................ report // This function converts the passed state into a csv string. this.report = function (stateVector, stateType) { var str = ""; if (isUnDefined(stateVector)) return str; if (isUnDefined(stateType)) stateType = us.eStateTypes.view; if (stateType === us.eStateTypes.view) { var zoom = stateVector.state.zoom; var isFit = thisImg.isFitZoom(zoom); var mag = (isFit) ? "Fit" : thisImg.convertToMag(zoom); zoom = (isFit) ? "Fit" : zoom; // note that this format is copied into the performance test sequence in cPerformanceTest str = parseInt(stateVector.time) + ', \"' + stateVector.desc + '\", ' + stateVector.state.left + ", " + stateVector.state.top + ", " + zoom + ", " + mag; //note: stateVector.dir & stateVector.magpx not reported (yet?) } else { var sv = mouseQueue[mouseQueue.length - 1]; str = stateVector.desc; str += stateVector.state.toString(); if (stateVector.magpx) str += " magnitude_px:" + stateVector.magpx; } return str; }; this.reportTitle = function (stateType) { var str = ""; if (isUnDefined(stateType)) stateType = us.eStateTypes.view; str = "Filename: " + thisImg.getFileName() + " Width: " + thisImg.getImageWidth() + " Height:" + thisImg.getImageHeight() + "\n"; if (stateType === us.eStateTypes.view) { str += "time, desc, centerX, centerY, zoom, mag\n"; //note: stateVector.dir & stateVector.magpx not reported (yet?) } else
return str; }; //............................................ reportAll this.reportAll = function (stateType, normalize) { var str = this.reportTitle(stateType); if (isUnDefined(stateType)) stateType = us.eStateTypes.view; if (isUnDefined(normalize)) normalize = false; var queue = (stateType === us.eStateTypes.view) ? imageQueue : mouseQueue; if (queue.length > 0) { for (var s = 0, len = queue.length; s < len; s++) { var svRef = queue[s]; // get state vector at index s var sv = new cloneObject(svRef); // clone the state vector so I can modify it var x = sv.state.left; // state reports top left corner, convert to center position var y = sv.state.top; x = parseInt(x + thisImg.getViewWidth() / 2); y = parseInt(y + thisImg.getViewHeight() / 2); if (normalize == true) { // if normalize, x and y are proportion of the image dims x = (x / thisImg.getImageWidth()).toFixed(5); y = (y / thisImg.getImageHeight()).toFixed(5); } sv.state.left = x; sv.state.top = y; str += (this.report(sv, stateType) + "\n"); } } return str; }; //............................................ _computeDir // This function evaluates the most recent state change and concludes the view motion direction. // It then adds that direction to the passed array. var _computeDir = function (ioSV) { ioSV.dir = "none"; if (imageQueue.length == 0 || ioSV.desc == "all" || ioSV.desc != "move") return; var lastState = self.getLast(stateTypeView).state; var dx = ioSV.state.left - lastState.left; var dy = ioSV.state.top - lastState.top; if (Math.abs(dx) > lastState.width * 2 || Math.abs(dy) > lastState.height * 2 // if moved N views //cp-revisit factor of 2 || ioSV.desc == "dim") { // or resized view dimensions ioSV.dir = "wholeview"; // then indicate whole view change return; } var dr = slopeLimit + 1; // slope of motion if (dy != 0) dr = dx / dy; if (us.DBGSTATEVECTOREX) ioSV.magpx ? thisImg.log("cStateVector: computeDir: " + dr.toFixed(2) + " dx dy:" + dx + " " + dy + " magpx:" + ioSV.magpx) : thisImg.log("cStateVector: computeDir: " + dr.toFixed(2) + " dx dy:" + dx + " " + dy); var dir = "none"; // default direction of move if (Math.abs(dr) > slopeLimit) { // if horizontal motion if (dx < 0) // if moving left dir = "east"; else dir = "west"; } else if (Math.abs(dr) < slopeLimtInv) { // if vertical motion if (dy < 0) // if moving up dir = "south"; else dir = "north"; } else if (dx < 0) { // diagnal motion, moving left if (dy < 0) // if moving up, too dir = "southeast"; else dir = "northeast"; } else { // diagnal motion, moving right if (dy < 0) // if moving up, too dir = "southwest"; else dir = "northwest"; } ioSV.dir = dir; // add direction to return ioSV }; //............................................................................................ // construction _setSize(kSVQUEUE_VIEW_SIZE); // save the max queue size allowed }; //________________________________________________________________________________________________
{ // not implemented }
conditional_block
statevector.js
//________________________________________________________________________________________________ // statevector.js //todo: update description // // cStateVector object - This is a generic container useful for ... // Every item added to the queue is time stamped for time series analyis, playback, etc. // There are optional functions onAdd[1,2,..]() that the user can define that will be //cp-not right!!!!! // called each time imageUpdate() is called. // // Note that the debug statements are commented outin some functions to reduce vpRefresh time. //cp-mention that this saves mouse & moves only > a fixed amount... // // history // 1106 cperz created // _______________________________________end_Rel 12.1 __________________________________________ // // 131119 cperz renamed imageUpdate to viewUpdate to avoid confusion with public interface // // todo // - could make queue trim on time instead of size (with size max still...) // - add methods for getlast direction, mouse position, etc.... // much more straightforward, no need to understand internal storage of this object! //________________________________________________________________________________________________ // state types: // image: set by viewUpdate() // mouse: set by mouseUpdate() // us.eStateTypes = { image: 0, mouse: 1 }; //________________________________________________________________________________________________ function cStateVector(vpObj)
; //________________________________________________________________________________________________
{ var thisImg = vpObj; // the viewport object - the parent var self = this; // local var for closure var imageId_ = thisImg.getImageId(); var uScopeIdx_ = thisImg.getImageIdx(); var imageSizeMax; var mouseSizeMax; var idxPrevNext = -1; // index in image queue var idxPrevNextStart = -1; // index of starting position of prev/next sequence var d = new Date(); var dTime = 1. / 10.; // get the start time and scale it from millisecs to 1/100th sec var startTime = d.getTime() * dTime; var imageQueue = []; // the image state vector queue var mouseQueue = []; // the mouse state vector queue var cb_imageState = []; // array of image state function callbacks var cb_mouseState = []; // array of mouse state function callbacks var stateTypeView = us.eStateTypes.view; // for quick access var stateTypeMouse = us.eStateTypes.mouse; var minMoveMagnitude_ = 12; // the minimum magnitude in pixels of movement to record var slopeLimit = 4; var slopeLimtInv = 0.25; // 1. / slopeLimit var kSVQUEUE_VIEW_SIZE = 500; // number of view states to retain in state vector queue // this throttles the responsivity of the state vector! //............................................ _sinceStartTime local // This function is used for all time stamps in this object. // It converts absolute time from "new Date().getTime()" to a differntial in seconds // (to the 3rd decimal place - milliseconds) since the start time of this object. var _sinceStartTime = function (time) { return (time * dTime - startTime).toFixed(3); }; //............................................ _setSize local // This function sets the image and mouse queue maximum sizes. var _setSize = function (newSize) { var newMax = (newSize) ? newSize : 200; // maximum size for queue if (newMax < 1 || newMax > 2000) // sanity check on the queue size return; imageSizeMax = newMax; mouseSizeMax = 100; // parseInt(newMax / 2); // limit the mouse queue to half the size while (imageQueue.length > imageSizeMax) imageQueue.shift(); while (mouseQueue.length > mouseSizeMax) mouseQueue.shift(); }; //............................................ registerForEvent // This function adds a subscription to state change event. // The imageUpdate() and mouseUpdate() functions call these subscribers. // this.registerForEvent = function (functionString, stateType) { if (typeof functionString === "function") { if (isUnDefined(stateType)) stateType = us.eStateTypes.view; if (us.DBGSTATEVECTOR) thisImg.log("statevector: add callback: (" + functionString + ") Type: " + stateType); if (stateType === us.eStateTypes.view) cb_imageState.push(functionString); else cb_mouseState.push(functionString); } }; //............................................ unRegisterForEvent // This function removes a subscription to state change event. this.unRegisterForEvent = function (functionString) { // find a string match in the call back arrays and remove it. if (typeof functionString === "function") { functionString = functionString.toString(); // search image state queue for the event for (var c = 0, len = cb_imageState.length; c < len; c++) { var str = cb_imageState[c].toString(); if (str.indexOf(functionString) !== -1) { if (us.DBGSTATEVECTOR) thisImg.log("statevector: remove image callback: (" + functionString + ")"); cb_imageState.remove(c); return; } } // search mouse state queue for the event for (var c = 0, len = cb_mouseState.length; c < len; c++) { var str = cb_mouseState[c].toString(); if (str.indexOf(functionString) !== -1) { if (us.DBGSTATEVECTOR) thisImg.log("statevector: remove mouse callback: (" + functionString + ")"); cb_mouseState.remove(c); return; } } } }; //............................................ viewUpdate // This function adds an image state vector to its queue. // If the state description is a move, the city block distance between this position and the previous state on the queue // must be greater than a threshold. Otherwise the state is not added to the queue. // // An Image State Vector is a definition of the view state plus: // time stamp // + desc {"all", "move", "zoom", "focus", "dims", } // + viewport's vpView contents {left, top, width, height, zoom, focus, angleDeg} // + dir {"none", "wholeview", "north", "east", "west", "south", northwest, ...} //cp-fill in and define // + magpx { magnitude of move in pixels } // // parameters // state: is viewport's vpView contents // changeDesc: {"all", "move", "zoom", "focus", "dims", "rotate"} // // todo: // - I'd like to know if there are listenters, perhaps I don't do all this if not var lastViewState_ = new cPoint(0,0); this.viewUpdate = function (state, changeDesc) { var zoom = state.zoom; var x = state.left; var y = state.top; //debug-only thisImg.log("image state: X,Y,ZOOM: " + x + "," + y + "," + zoom); if (imageQueue.length == imageSizeMax) // maintain queue size imageQueue.shift(); // remove the top element of the array to make room at the bottom var magpx = 0; if (changeDesc == "move") { // throttle the responsivity to motion var magpx = Math.abs(state.left - lastViewState_.x) + Math.abs(state.top - lastViewState_.y); // city-street magnitude of move in pixels if (magpx < minMoveMagnitude_) { //dbg-only if (us.DBGSTATEVECTOREX) thisImg.log("cStateVector: viewUpdate: magnitude of move (" + magpx + ") < minimum (" + minMoveMagnitude_ + ")"); return; } //consoleWrite("cur state: " + state.left + "," + state.top + " last state: " + lastViewState_.toString() + " magpx: " + magpx); } var sv = []; // add info to new state vector sv.time = _sinceStartTime(new Date().getTime()); // add time stamp sv.desc = changeDesc; // add input change description sv.state = jQuery.extend(true, {}, state); // add input view state, must clone state first if (changeDesc == "move") // sv.magpx = magpx; // add magnitude of move (units are pixels) _computeDir(sv); // add computed direction 'dir' imageQueue.push(sv); // add state vector to the queue lastViewState_.set(state.left, state.top); // save last queue view position //if (us.DBGSTATEVECTOR) sv.magpx ? thisImg.log("cStateVector: viewUpdate: dir: " + sv.dir + " magpx: " + sv.magpx) // : thisImg.log("cStateVector: viewUpdate: desc: " + sv.desc); for (var c = 0, len = cb_imageState.length; c < len; c++) // execute the callbacks to signal a SV update event cb_imageState[c](); triggerUScopeEvent(us.evVIEWCHANGE, { // fire event that the view has changed imageId: imageId_, uScopeIdx: uScopeIdx_, desc: sv.desc, x: thisImg.getViewCenterX(), y: thisImg.getViewCenterY(), zoom: zoom, angleDeg: state.angleDeg }); }; //............................................ mouseUpdate // This function adds an mouse state vector to its queue. // If the state description is a mousemove, the city block distance between this position and the previous state on the queue // must be greater than a threshold. Otherwise the state is not added to the queue. // // A Mouse State Vector is a definition of the mouse state: // time stamp // + desc {"mousemove", "mousedown", ...} // + state cPoint {x,y} of mouse position in base image coordinates // // parameters // state: cPoint {x,y} of mouse position in base image coordinates // eventDesc: {"mousemove", "mousedown",} // bForce: boolean, if true the function does not exit when there are no listeners // so us.evMOUSECHANGE event is fired if mouse move is sufficient var lastMouseState_ = new cPoint(0, 0); this.mouseUpdate = function (state, eventDesc, bForce) { if (bForce == false && cb_mouseState.length == 0) // do not save state if no one is subscribed return; //dbg-only if (us.DBGSTATEVECTOREX) thisImg.log("cStateVector: mouseUpdate: " + state.toString() + " desc: " + eventDesc); if (mouseQueue.length == mouseSizeMax) // maintain queue size mouseQueue.shift(); // remove the top element of the array to make room at the bottom var magpx = 0; if (eventDesc == "mousemove") { if (lastMouseState_) { // throttle the responsivity to motion magpx = lastMouseState_.cityBlockDistance(state); //consoleWrite("cur state: " + state + " last state: " + lastMouseState_.toString() + " magpx: " + magpx); if (magpx < minMoveMagnitude_) { //dbg-only if (us.DBGSTATEVECTOREX) thisImg.log("cStateVector: mouseUpdate: magnitude of move (" + magpx + ") < minimum (" + minMoveMagnitude_ + ")"); return; } } } var sv = []; // add info to new state vector sv.time = _sinceStartTime(new Date().getTime()); // add time stamp sv.desc = eventDesc; // add input change description sv.state = jQuery.extend(true, {}, state); // add input view state, must clone state first mouseQueue.push(sv); // add state vector to the queue lastMouseState_.setPoint(sv.state); // save last queue mouse position //dbg-only if (us.DBGSTATEVECTOREX) thisImg.log("cStateVector: mouseUpdate: desc: " + sv.desc + sv.state.toString() + " magnitude: " + magpx); for (var c = 0, len = cb_mouseState.length; c < len; c++) // execute the callbacks to signal a SV update event cb_mouseState[c](); triggerUScopeEvent(us.evMOUSECHANGE, { imageId: imageId_, uScopeIdx: uScopeIdx_, uScopeIdx: thisImg.getImageIdx(), x: state.x, y: state.y }); }; //............................................ getLastMousePosition // This function returns the last recorded mouse position or undefined if none have been recorded. this.getLastMousePosition = function () { return (mouseQueue.length > 0) ? mouseQueue[mouseQueue.length - 1].state : undefined; }; //............................................ getMouseEventsSince // This function returns an array in ascending order of the mouse events since a specified time. // The time stamp in the list of events is in this object's format - delta time since the start of the object scaled by dTime; // Optionally a specific type of mouse event can be selected. // A maximum number of returned events is enforced but can be overridden. // // parameters: // sinceTime required, time to start collecting the event, sinceTime = new Date().getTime() // eventDesc optional, return this mouse event type {"mousemove", "mousedown", ...} default is all // maxRtnSize optional, maximum number of mousestates to return, default is 100 this.getMouseEventsSince = function (sinceTime, eventDesc, maxRtnSize) { var rtnQueue = []; if (isUnDefined(sinceTime)) return rtnQueue; sinceTime = _sinceStartTime(sinceTime); // convert to same time format as used here in if (mouseQueue.length > 0) { eventDesc = (eventDesc) ? eventDesc : "all"; // set event filter maxRtnSize = (maxRtnSize) ? maxRtnSize + 1 : 101; // set limit of number of items returned var cnt = 0; var startIdx = mouseQueue.length; while (--startIdx > 0 && ++cnt < maxRtnSize) { if (mouseQueue[startIdx].time < sinceTime) // am I now before my time? break; if (eventDesc == "all" || eventDesc == mouseQueue[startIdx].desc) rtnQueue.unshift(mouseQueue[startIdx]); // add to the begining of the array for ascending order } } return rtnQueue; }; //............................................ getPrevNext this.getPrevNext = function (incr) {//incr s/b +/-1 if (imageQueue.length < 1) return undefined; var rtnSV = undefined; if (idxPrevNext == -1) { idxPrevNext = imageQueue.length - 1 + incr; idxPrevNextStart = imageQueue.length - 1; } else { idxPrevNext = idxPrevNext + incr; if (idxPrevNext > idxPrevNextStart) idxPrevNext = idxPrevNextStart; // don't move past starting position } /////thisImg.log("getPrevNext: idxPrevNext: " + idxPrevNext); if (idxPrevNext > 0 && idxPrevNext < imageQueue.length) rtnSV = imageQueue[idxPrevNext]; if (idxPrevNext == idxPrevNextStart) idxPrevNext = -1; //reset return rtnSV; }; //............................................ getLastDirection // This function returns the last recorded image direction or undefined if none have been recorded. this.getLastDirection = function () { return (imageQueue.length > 0) ? imageQueue[imageQueue.length - 1].dir : undefined; }; //............................................ getLastDescription // This function returns the last recorded image description or undefined if none have been recorded. this.getLastDescription = function () { return (imageQueue.length > 0) ? imageQueue[imageQueue.length - 1].desc : undefined; }; //............................................ getLast // This function returns the last state vector for the specified state type. this.getLast = function (stateType) {//cp-todo rename to get LastState if (isUnDefined(stateType)) stateType = us.eStateTypes.view; if (stateType === us.eStateTypes.view) return (imageQueue.length > 0) ? imageQueue[imageQueue.length - 1] : undefined; else return (mouseQueue.length > 0) ? mouseQueue[mouseQueue.length - 1] : undefined; }; //............................................ reportLast // This function returns a string containing the last state vector report for the specified state type. this.reportLast = function (stateType) { var str = ""; var queue = (stateType === us.eStateTypes.view) ? imageQueue : mouseQueue; if (queue.length > 0) { str = (stateType === us.eStateTypes.view) ? "LastViewState: " : "LastMouseState: "; var state = queue[queue.length - 1]; str += this.report(state, stateType); } return str; }; //............................................ report // This function converts the passed state into a csv string. this.report = function (stateVector, stateType) { var str = ""; if (isUnDefined(stateVector)) return str; if (isUnDefined(stateType)) stateType = us.eStateTypes.view; if (stateType === us.eStateTypes.view) { var zoom = stateVector.state.zoom; var isFit = thisImg.isFitZoom(zoom); var mag = (isFit) ? "Fit" : thisImg.convertToMag(zoom); zoom = (isFit) ? "Fit" : zoom; // note that this format is copied into the performance test sequence in cPerformanceTest str = parseInt(stateVector.time) + ', \"' + stateVector.desc + '\", ' + stateVector.state.left + ", " + stateVector.state.top + ", " + zoom + ", " + mag; //note: stateVector.dir & stateVector.magpx not reported (yet?) } else { var sv = mouseQueue[mouseQueue.length - 1]; str = stateVector.desc; str += stateVector.state.toString(); if (stateVector.magpx) str += " magnitude_px:" + stateVector.magpx; } return str; }; this.reportTitle = function (stateType) { var str = ""; if (isUnDefined(stateType)) stateType = us.eStateTypes.view; str = "Filename: " + thisImg.getFileName() + " Width: " + thisImg.getImageWidth() + " Height:" + thisImg.getImageHeight() + "\n"; if (stateType === us.eStateTypes.view) { str += "time, desc, centerX, centerY, zoom, mag\n"; //note: stateVector.dir & stateVector.magpx not reported (yet?) } else { // not implemented } return str; }; //............................................ reportAll this.reportAll = function (stateType, normalize) { var str = this.reportTitle(stateType); if (isUnDefined(stateType)) stateType = us.eStateTypes.view; if (isUnDefined(normalize)) normalize = false; var queue = (stateType === us.eStateTypes.view) ? imageQueue : mouseQueue; if (queue.length > 0) { for (var s = 0, len = queue.length; s < len; s++) { var svRef = queue[s]; // get state vector at index s var sv = new cloneObject(svRef); // clone the state vector so I can modify it var x = sv.state.left; // state reports top left corner, convert to center position var y = sv.state.top; x = parseInt(x + thisImg.getViewWidth() / 2); y = parseInt(y + thisImg.getViewHeight() / 2); if (normalize == true) { // if normalize, x and y are proportion of the image dims x = (x / thisImg.getImageWidth()).toFixed(5); y = (y / thisImg.getImageHeight()).toFixed(5); } sv.state.left = x; sv.state.top = y; str += (this.report(sv, stateType) + "\n"); } } return str; }; //............................................ _computeDir // This function evaluates the most recent state change and concludes the view motion direction. // It then adds that direction to the passed array. var _computeDir = function (ioSV) { ioSV.dir = "none"; if (imageQueue.length == 0 || ioSV.desc == "all" || ioSV.desc != "move") return; var lastState = self.getLast(stateTypeView).state; var dx = ioSV.state.left - lastState.left; var dy = ioSV.state.top - lastState.top; if (Math.abs(dx) > lastState.width * 2 || Math.abs(dy) > lastState.height * 2 // if moved N views //cp-revisit factor of 2 || ioSV.desc == "dim") { // or resized view dimensions ioSV.dir = "wholeview"; // then indicate whole view change return; } var dr = slopeLimit + 1; // slope of motion if (dy != 0) dr = dx / dy; if (us.DBGSTATEVECTOREX) ioSV.magpx ? thisImg.log("cStateVector: computeDir: " + dr.toFixed(2) + " dx dy:" + dx + " " + dy + " magpx:" + ioSV.magpx) : thisImg.log("cStateVector: computeDir: " + dr.toFixed(2) + " dx dy:" + dx + " " + dy); var dir = "none"; // default direction of move if (Math.abs(dr) > slopeLimit) { // if horizontal motion if (dx < 0) // if moving left dir = "east"; else dir = "west"; } else if (Math.abs(dr) < slopeLimtInv) { // if vertical motion if (dy < 0) // if moving up dir = "south"; else dir = "north"; } else if (dx < 0) { // diagnal motion, moving left if (dy < 0) // if moving up, too dir = "southeast"; else dir = "northeast"; } else { // diagnal motion, moving right if (dy < 0) // if moving up, too dir = "southwest"; else dir = "northwest"; } ioSV.dir = dir; // add direction to return ioSV }; //............................................................................................ // construction _setSize(kSVQUEUE_VIEW_SIZE); // save the max queue size allowed }
identifier_body
statevector.js
//________________________________________________________________________________________________ // statevector.js //todo: update description // // cStateVector object - This is a generic container useful for ... // Every item added to the queue is time stamped for time series analyis, playback, etc. // There are optional functions onAdd[1,2,..]() that the user can define that will be //cp-not right!!!!! // called each time imageUpdate() is called. // // Note that the debug statements are commented outin some functions to reduce vpRefresh time. //cp-mention that this saves mouse & moves only > a fixed amount... // // history // 1106 cperz created // _______________________________________end_Rel 12.1 __________________________________________ // // 131119 cperz renamed imageUpdate to viewUpdate to avoid confusion with public interface // // todo // - could make queue trim on time instead of size (with size max still...) // - add methods for getlast direction, mouse position, etc.... // much more straightforward, no need to understand internal storage of this object! //________________________________________________________________________________________________ // state types: // image: set by viewUpdate() // mouse: set by mouseUpdate() // us.eStateTypes = { image: 0, mouse: 1 }; //________________________________________________________________________________________________ function cStateVector(vpObj) { var thisImg = vpObj; // the viewport object - the parent var self = this; // local var for closure var imageId_ = thisImg.getImageId(); var uScopeIdx_ = thisImg.getImageIdx(); var imageSizeMax; var mouseSizeMax; var idxPrevNext = -1; // index in image queue var idxPrevNextStart = -1; // index of starting position of prev/next sequence var d = new Date(); var dTime = 1. / 10.; // get the start time and scale it from millisecs to 1/100th sec var startTime = d.getTime() * dTime; var imageQueue = []; // the image state vector queue var mouseQueue = []; // the mouse state vector queue var cb_imageState = []; // array of image state function callbacks var cb_mouseState = []; // array of mouse state function callbacks var stateTypeView = us.eStateTypes.view; // for quick access var stateTypeMouse = us.eStateTypes.mouse; var minMoveMagnitude_ = 12; // the minimum magnitude in pixels of movement to record var slopeLimit = 4; var slopeLimtInv = 0.25; // 1. / slopeLimit var kSVQUEUE_VIEW_SIZE = 500; // number of view states to retain in state vector queue // this throttles the responsivity of the state vector! //............................................ _sinceStartTime local // This function is used for all time stamps in this object. // It converts absolute time from "new Date().getTime()" to a differntial in seconds // (to the 3rd decimal place - milliseconds) since the start time of this object. var _sinceStartTime = function (time) { return (time * dTime - startTime).toFixed(3); }; //............................................ _setSize local // This function sets the image and mouse queue maximum sizes. var _setSize = function (newSize) { var newMax = (newSize) ? newSize : 200; // maximum size for queue if (newMax < 1 || newMax > 2000) // sanity check on the queue size return; imageSizeMax = newMax; mouseSizeMax = 100; // parseInt(newMax / 2); // limit the mouse queue to half the size while (imageQueue.length > imageSizeMax) imageQueue.shift(); while (mouseQueue.length > mouseSizeMax) mouseQueue.shift(); }; //............................................ registerForEvent // This function adds a subscription to state change event. // The imageUpdate() and mouseUpdate() functions call these subscribers. // this.registerForEvent = function (functionString, stateType) { if (typeof functionString === "function") { if (isUnDefined(stateType)) stateType = us.eStateTypes.view; if (us.DBGSTATEVECTOR) thisImg.log("statevector: add callback: (" + functionString + ") Type: " + stateType); if (stateType === us.eStateTypes.view) cb_imageState.push(functionString); else cb_mouseState.push(functionString); } }; //............................................ unRegisterForEvent // This function removes a subscription to state change event. this.unRegisterForEvent = function (functionString) { // find a string match in the call back arrays and remove it. if (typeof functionString === "function") { functionString = functionString.toString(); // search image state queue for the event for (var c = 0, len = cb_imageState.length; c < len; c++) { var str = cb_imageState[c].toString(); if (str.indexOf(functionString) !== -1) { if (us.DBGSTATEVECTOR) thisImg.log("statevector: remove image callback: (" + functionString + ")"); cb_imageState.remove(c); return; } } // search mouse state queue for the event for (var c = 0, len = cb_mouseState.length; c < len; c++) { var str = cb_mouseState[c].toString(); if (str.indexOf(functionString) !== -1) { if (us.DBGSTATEVECTOR) thisImg.log("statevector: remove mouse callback: (" + functionString + ")"); cb_mouseState.remove(c); return; } } } }; //............................................ viewUpdate // This function adds an image state vector to its queue. // If the state description is a move, the city block distance between this position and the previous state on the queue // must be greater than a threshold. Otherwise the state is not added to the queue. // // An Image State Vector is a definition of the view state plus: // time stamp // + desc {"all", "move", "zoom", "focus", "dims", } // + viewport's vpView contents {left, top, width, height, zoom, focus, angleDeg} // + dir {"none", "wholeview", "north", "east", "west", "south", northwest, ...} //cp-fill in and define // + magpx { magnitude of move in pixels } // // parameters // state: is viewport's vpView contents // changeDesc: {"all", "move", "zoom", "focus", "dims", "rotate"} // // todo: // - I'd like to know if there are listenters, perhaps I don't do all this if not var lastViewState_ = new cPoint(0,0); this.viewUpdate = function (state, changeDesc) { var zoom = state.zoom; var x = state.left; var y = state.top; //debug-only thisImg.log("image state: X,Y,ZOOM: " + x + "," + y + "," + zoom); if (imageQueue.length == imageSizeMax) // maintain queue size imageQueue.shift(); // remove the top element of the array to make room at the bottom var magpx = 0; if (changeDesc == "move") { // throttle the responsivity to motion var magpx = Math.abs(state.left - lastViewState_.x) + Math.abs(state.top - lastViewState_.y); // city-street magnitude of move in pixels if (magpx < minMoveMagnitude_) { //dbg-only if (us.DBGSTATEVECTOREX) thisImg.log("cStateVector: viewUpdate: magnitude of move (" + magpx + ") < minimum (" + minMoveMagnitude_ + ")"); return; } //consoleWrite("cur state: " + state.left + "," + state.top + " last state: " + lastViewState_.toString() + " magpx: " + magpx); } var sv = []; // add info to new state vector sv.time = _sinceStartTime(new Date().getTime()); // add time stamp sv.desc = changeDesc; // add input change description sv.state = jQuery.extend(true, {}, state); // add input view state, must clone state first if (changeDesc == "move") // sv.magpx = magpx; // add magnitude of move (units are pixels) _computeDir(sv); // add computed direction 'dir' imageQueue.push(sv); // add state vector to the queue
//if (us.DBGSTATEVECTOR) sv.magpx ? thisImg.log("cStateVector: viewUpdate: dir: " + sv.dir + " magpx: " + sv.magpx) // : thisImg.log("cStateVector: viewUpdate: desc: " + sv.desc); for (var c = 0, len = cb_imageState.length; c < len; c++) // execute the callbacks to signal a SV update event cb_imageState[c](); triggerUScopeEvent(us.evVIEWCHANGE, { // fire event that the view has changed imageId: imageId_, uScopeIdx: uScopeIdx_, desc: sv.desc, x: thisImg.getViewCenterX(), y: thisImg.getViewCenterY(), zoom: zoom, angleDeg: state.angleDeg }); }; //............................................ mouseUpdate // This function adds an mouse state vector to its queue. // If the state description is a mousemove, the city block distance between this position and the previous state on the queue // must be greater than a threshold. Otherwise the state is not added to the queue. // // A Mouse State Vector is a definition of the mouse state: // time stamp // + desc {"mousemove", "mousedown", ...} // + state cPoint {x,y} of mouse position in base image coordinates // // parameters // state: cPoint {x,y} of mouse position in base image coordinates // eventDesc: {"mousemove", "mousedown",} // bForce: boolean, if true the function does not exit when there are no listeners // so us.evMOUSECHANGE event is fired if mouse move is sufficient var lastMouseState_ = new cPoint(0, 0); this.mouseUpdate = function (state, eventDesc, bForce) { if (bForce == false && cb_mouseState.length == 0) // do not save state if no one is subscribed return; //dbg-only if (us.DBGSTATEVECTOREX) thisImg.log("cStateVector: mouseUpdate: " + state.toString() + " desc: " + eventDesc); if (mouseQueue.length == mouseSizeMax) // maintain queue size mouseQueue.shift(); // remove the top element of the array to make room at the bottom var magpx = 0; if (eventDesc == "mousemove") { if (lastMouseState_) { // throttle the responsivity to motion magpx = lastMouseState_.cityBlockDistance(state); //consoleWrite("cur state: " + state + " last state: " + lastMouseState_.toString() + " magpx: " + magpx); if (magpx < minMoveMagnitude_) { //dbg-only if (us.DBGSTATEVECTOREX) thisImg.log("cStateVector: mouseUpdate: magnitude of move (" + magpx + ") < minimum (" + minMoveMagnitude_ + ")"); return; } } } var sv = []; // add info to new state vector sv.time = _sinceStartTime(new Date().getTime()); // add time stamp sv.desc = eventDesc; // add input change description sv.state = jQuery.extend(true, {}, state); // add input view state, must clone state first mouseQueue.push(sv); // add state vector to the queue lastMouseState_.setPoint(sv.state); // save last queue mouse position //dbg-only if (us.DBGSTATEVECTOREX) thisImg.log("cStateVector: mouseUpdate: desc: " + sv.desc + sv.state.toString() + " magnitude: " + magpx); for (var c = 0, len = cb_mouseState.length; c < len; c++) // execute the callbacks to signal a SV update event cb_mouseState[c](); triggerUScopeEvent(us.evMOUSECHANGE, { imageId: imageId_, uScopeIdx: uScopeIdx_, uScopeIdx: thisImg.getImageIdx(), x: state.x, y: state.y }); }; //............................................ getLastMousePosition // This function returns the last recorded mouse position or undefined if none have been recorded. this.getLastMousePosition = function () { return (mouseQueue.length > 0) ? mouseQueue[mouseQueue.length - 1].state : undefined; }; //............................................ getMouseEventsSince // This function returns an array in ascending order of the mouse events since a specified time. // The time stamp in the list of events is in this object's format - delta time since the start of the object scaled by dTime; // Optionally a specific type of mouse event can be selected. // A maximum number of returned events is enforced but can be overridden. // // parameters: // sinceTime required, time to start collecting the event, sinceTime = new Date().getTime() // eventDesc optional, return this mouse event type {"mousemove", "mousedown", ...} default is all // maxRtnSize optional, maximum number of mousestates to return, default is 100 this.getMouseEventsSince = function (sinceTime, eventDesc, maxRtnSize) { var rtnQueue = []; if (isUnDefined(sinceTime)) return rtnQueue; sinceTime = _sinceStartTime(sinceTime); // convert to same time format as used here in if (mouseQueue.length > 0) { eventDesc = (eventDesc) ? eventDesc : "all"; // set event filter maxRtnSize = (maxRtnSize) ? maxRtnSize + 1 : 101; // set limit of number of items returned var cnt = 0; var startIdx = mouseQueue.length; while (--startIdx > 0 && ++cnt < maxRtnSize) { if (mouseQueue[startIdx].time < sinceTime) // am I now before my time? break; if (eventDesc == "all" || eventDesc == mouseQueue[startIdx].desc) rtnQueue.unshift(mouseQueue[startIdx]); // add to the begining of the array for ascending order } } return rtnQueue; }; //............................................ getPrevNext this.getPrevNext = function (incr) {//incr s/b +/-1 if (imageQueue.length < 1) return undefined; var rtnSV = undefined; if (idxPrevNext == -1) { idxPrevNext = imageQueue.length - 1 + incr; idxPrevNextStart = imageQueue.length - 1; } else { idxPrevNext = idxPrevNext + incr; if (idxPrevNext > idxPrevNextStart) idxPrevNext = idxPrevNextStart; // don't move past starting position } /////thisImg.log("getPrevNext: idxPrevNext: " + idxPrevNext); if (idxPrevNext > 0 && idxPrevNext < imageQueue.length) rtnSV = imageQueue[idxPrevNext]; if (idxPrevNext == idxPrevNextStart) idxPrevNext = -1; //reset return rtnSV; }; //............................................ getLastDirection // This function returns the last recorded image direction or undefined if none have been recorded. this.getLastDirection = function () { return (imageQueue.length > 0) ? imageQueue[imageQueue.length - 1].dir : undefined; }; //............................................ getLastDescription // This function returns the last recorded image description or undefined if none have been recorded. this.getLastDescription = function () { return (imageQueue.length > 0) ? imageQueue[imageQueue.length - 1].desc : undefined; }; //............................................ getLast // This function returns the last state vector for the specified state type. this.getLast = function (stateType) {//cp-todo rename to get LastState if (isUnDefined(stateType)) stateType = us.eStateTypes.view; if (stateType === us.eStateTypes.view) return (imageQueue.length > 0) ? imageQueue[imageQueue.length - 1] : undefined; else return (mouseQueue.length > 0) ? mouseQueue[mouseQueue.length - 1] : undefined; }; //............................................ reportLast // This function returns a string containing the last state vector report for the specified state type. this.reportLast = function (stateType) { var str = ""; var queue = (stateType === us.eStateTypes.view) ? imageQueue : mouseQueue; if (queue.length > 0) { str = (stateType === us.eStateTypes.view) ? "LastViewState: " : "LastMouseState: "; var state = queue[queue.length - 1]; str += this.report(state, stateType); } return str; }; //............................................ report // This function converts the passed state into a csv string. this.report = function (stateVector, stateType) { var str = ""; if (isUnDefined(stateVector)) return str; if (isUnDefined(stateType)) stateType = us.eStateTypes.view; if (stateType === us.eStateTypes.view) { var zoom = stateVector.state.zoom; var isFit = thisImg.isFitZoom(zoom); var mag = (isFit) ? "Fit" : thisImg.convertToMag(zoom); zoom = (isFit) ? "Fit" : zoom; // note that this format is copied into the performance test sequence in cPerformanceTest str = parseInt(stateVector.time) + ', \"' + stateVector.desc + '\", ' + stateVector.state.left + ", " + stateVector.state.top + ", " + zoom + ", " + mag; //note: stateVector.dir & stateVector.magpx not reported (yet?) } else { var sv = mouseQueue[mouseQueue.length - 1]; str = stateVector.desc; str += stateVector.state.toString(); if (stateVector.magpx) str += " magnitude_px:" + stateVector.magpx; } return str; }; this.reportTitle = function (stateType) { var str = ""; if (isUnDefined(stateType)) stateType = us.eStateTypes.view; str = "Filename: " + thisImg.getFileName() + " Width: " + thisImg.getImageWidth() + " Height:" + thisImg.getImageHeight() + "\n"; if (stateType === us.eStateTypes.view) { str += "time, desc, centerX, centerY, zoom, mag\n"; //note: stateVector.dir & stateVector.magpx not reported (yet?) } else { // not implemented } return str; }; //............................................ reportAll this.reportAll = function (stateType, normalize) { var str = this.reportTitle(stateType); if (isUnDefined(stateType)) stateType = us.eStateTypes.view; if (isUnDefined(normalize)) normalize = false; var queue = (stateType === us.eStateTypes.view) ? imageQueue : mouseQueue; if (queue.length > 0) { for (var s = 0, len = queue.length; s < len; s++) { var svRef = queue[s]; // get state vector at index s var sv = new cloneObject(svRef); // clone the state vector so I can modify it var x = sv.state.left; // state reports top left corner, convert to center position var y = sv.state.top; x = parseInt(x + thisImg.getViewWidth() / 2); y = parseInt(y + thisImg.getViewHeight() / 2); if (normalize == true) { // if normalize, x and y are proportion of the image dims x = (x / thisImg.getImageWidth()).toFixed(5); y = (y / thisImg.getImageHeight()).toFixed(5); } sv.state.left = x; sv.state.top = y; str += (this.report(sv, stateType) + "\n"); } } return str; }; //............................................ _computeDir // This function evaluates the most recent state change and concludes the view motion direction. // It then adds that direction to the passed array. var _computeDir = function (ioSV) { ioSV.dir = "none"; if (imageQueue.length == 0 || ioSV.desc == "all" || ioSV.desc != "move") return; var lastState = self.getLast(stateTypeView).state; var dx = ioSV.state.left - lastState.left; var dy = ioSV.state.top - lastState.top; if (Math.abs(dx) > lastState.width * 2 || Math.abs(dy) > lastState.height * 2 // if moved N views //cp-revisit factor of 2 || ioSV.desc == "dim") { // or resized view dimensions ioSV.dir = "wholeview"; // then indicate whole view change return; } var dr = slopeLimit + 1; // slope of motion if (dy != 0) dr = dx / dy; if (us.DBGSTATEVECTOREX) ioSV.magpx ? thisImg.log("cStateVector: computeDir: " + dr.toFixed(2) + " dx dy:" + dx + " " + dy + " magpx:" + ioSV.magpx) : thisImg.log("cStateVector: computeDir: " + dr.toFixed(2) + " dx dy:" + dx + " " + dy); var dir = "none"; // default direction of move if (Math.abs(dr) > slopeLimit) { // if horizontal motion if (dx < 0) // if moving left dir = "east"; else dir = "west"; } else if (Math.abs(dr) < slopeLimtInv) { // if vertical motion if (dy < 0) // if moving up dir = "south"; else dir = "north"; } else if (dx < 0) { // diagnal motion, moving left if (dy < 0) // if moving up, too dir = "southeast"; else dir = "northeast"; } else { // diagnal motion, moving right if (dy < 0) // if moving up, too dir = "southwest"; else dir = "northwest"; } ioSV.dir = dir; // add direction to return ioSV }; //............................................................................................ // construction _setSize(kSVQUEUE_VIEW_SIZE); // save the max queue size allowed }; //________________________________________________________________________________________________
lastViewState_.set(state.left, state.top); // save last queue view position
random_line_split
statevector.js
//________________________________________________________________________________________________ // statevector.js //todo: update description // // cStateVector object - This is a generic container useful for ... // Every item added to the queue is time stamped for time series analyis, playback, etc. // There are optional functions onAdd[1,2,..]() that the user can define that will be //cp-not right!!!!! // called each time imageUpdate() is called. // // Note that the debug statements are commented outin some functions to reduce vpRefresh time. //cp-mention that this saves mouse & moves only > a fixed amount... // // history // 1106 cperz created // _______________________________________end_Rel 12.1 __________________________________________ // // 131119 cperz renamed imageUpdate to viewUpdate to avoid confusion with public interface // // todo // - could make queue trim on time instead of size (with size max still...) // - add methods for getlast direction, mouse position, etc.... // much more straightforward, no need to understand internal storage of this object! //________________________________________________________________________________________________ // state types: // image: set by viewUpdate() // mouse: set by mouseUpdate() // us.eStateTypes = { image: 0, mouse: 1 }; //________________________________________________________________________________________________ function
(vpObj) { var thisImg = vpObj; // the viewport object - the parent var self = this; // local var for closure var imageId_ = thisImg.getImageId(); var uScopeIdx_ = thisImg.getImageIdx(); var imageSizeMax; var mouseSizeMax; var idxPrevNext = -1; // index in image queue var idxPrevNextStart = -1; // index of starting position of prev/next sequence var d = new Date(); var dTime = 1. / 10.; // get the start time and scale it from millisecs to 1/100th sec var startTime = d.getTime() * dTime; var imageQueue = []; // the image state vector queue var mouseQueue = []; // the mouse state vector queue var cb_imageState = []; // array of image state function callbacks var cb_mouseState = []; // array of mouse state function callbacks var stateTypeView = us.eStateTypes.view; // for quick access var stateTypeMouse = us.eStateTypes.mouse; var minMoveMagnitude_ = 12; // the minimum magnitude in pixels of movement to record var slopeLimit = 4; var slopeLimtInv = 0.25; // 1. / slopeLimit var kSVQUEUE_VIEW_SIZE = 500; // number of view states to retain in state vector queue // this throttles the responsivity of the state vector! //............................................ _sinceStartTime local // This function is used for all time stamps in this object. // It converts absolute time from "new Date().getTime()" to a differntial in seconds // (to the 3rd decimal place - milliseconds) since the start time of this object. var _sinceStartTime = function (time) { return (time * dTime - startTime).toFixed(3); }; //............................................ _setSize local // This function sets the image and mouse queue maximum sizes. var _setSize = function (newSize) { var newMax = (newSize) ? newSize : 200; // maximum size for queue if (newMax < 1 || newMax > 2000) // sanity check on the queue size return; imageSizeMax = newMax; mouseSizeMax = 100; // parseInt(newMax / 2); // limit the mouse queue to half the size while (imageQueue.length > imageSizeMax) imageQueue.shift(); while (mouseQueue.length > mouseSizeMax) mouseQueue.shift(); }; //............................................ registerForEvent // This function adds a subscription to state change event. // The imageUpdate() and mouseUpdate() functions call these subscribers. // this.registerForEvent = function (functionString, stateType) { if (typeof functionString === "function") { if (isUnDefined(stateType)) stateType = us.eStateTypes.view; if (us.DBGSTATEVECTOR) thisImg.log("statevector: add callback: (" + functionString + ") Type: " + stateType); if (stateType === us.eStateTypes.view) cb_imageState.push(functionString); else cb_mouseState.push(functionString); } }; //............................................ unRegisterForEvent // This function removes a subscription to state change event. this.unRegisterForEvent = function (functionString) { // find a string match in the call back arrays and remove it. if (typeof functionString === "function") { functionString = functionString.toString(); // search image state queue for the event for (var c = 0, len = cb_imageState.length; c < len; c++) { var str = cb_imageState[c].toString(); if (str.indexOf(functionString) !== -1) { if (us.DBGSTATEVECTOR) thisImg.log("statevector: remove image callback: (" + functionString + ")"); cb_imageState.remove(c); return; } } // search mouse state queue for the event for (var c = 0, len = cb_mouseState.length; c < len; c++) { var str = cb_mouseState[c].toString(); if (str.indexOf(functionString) !== -1) { if (us.DBGSTATEVECTOR) thisImg.log("statevector: remove mouse callback: (" + functionString + ")"); cb_mouseState.remove(c); return; } } } }; //............................................ viewUpdate // This function adds an image state vector to its queue. // If the state description is a move, the city block distance between this position and the previous state on the queue // must be greater than a threshold. Otherwise the state is not added to the queue. // // An Image State Vector is a definition of the view state plus: // time stamp // + desc {"all", "move", "zoom", "focus", "dims", } // + viewport's vpView contents {left, top, width, height, zoom, focus, angleDeg} // + dir {"none", "wholeview", "north", "east", "west", "south", northwest, ...} //cp-fill in and define // + magpx { magnitude of move in pixels } // // parameters // state: is viewport's vpView contents // changeDesc: {"all", "move", "zoom", "focus", "dims", "rotate"} // // todo: // - I'd like to know if there are listenters, perhaps I don't do all this if not var lastViewState_ = new cPoint(0,0); this.viewUpdate = function (state, changeDesc) { var zoom = state.zoom; var x = state.left; var y = state.top; //debug-only thisImg.log("image state: X,Y,ZOOM: " + x + "," + y + "," + zoom); if (imageQueue.length == imageSizeMax) // maintain queue size imageQueue.shift(); // remove the top element of the array to make room at the bottom var magpx = 0; if (changeDesc == "move") { // throttle the responsivity to motion var magpx = Math.abs(state.left - lastViewState_.x) + Math.abs(state.top - lastViewState_.y); // city-street magnitude of move in pixels if (magpx < minMoveMagnitude_) { //dbg-only if (us.DBGSTATEVECTOREX) thisImg.log("cStateVector: viewUpdate: magnitude of move (" + magpx + ") < minimum (" + minMoveMagnitude_ + ")"); return; } //consoleWrite("cur state: " + state.left + "," + state.top + " last state: " + lastViewState_.toString() + " magpx: " + magpx); } var sv = []; // add info to new state vector sv.time = _sinceStartTime(new Date().getTime()); // add time stamp sv.desc = changeDesc; // add input change description sv.state = jQuery.extend(true, {}, state); // add input view state, must clone state first if (changeDesc == "move") // sv.magpx = magpx; // add magnitude of move (units are pixels) _computeDir(sv); // add computed direction 'dir' imageQueue.push(sv); // add state vector to the queue lastViewState_.set(state.left, state.top); // save last queue view position //if (us.DBGSTATEVECTOR) sv.magpx ? thisImg.log("cStateVector: viewUpdate: dir: " + sv.dir + " magpx: " + sv.magpx) // : thisImg.log("cStateVector: viewUpdate: desc: " + sv.desc); for (var c = 0, len = cb_imageState.length; c < len; c++) // execute the callbacks to signal a SV update event cb_imageState[c](); triggerUScopeEvent(us.evVIEWCHANGE, { // fire event that the view has changed imageId: imageId_, uScopeIdx: uScopeIdx_, desc: sv.desc, x: thisImg.getViewCenterX(), y: thisImg.getViewCenterY(), zoom: zoom, angleDeg: state.angleDeg }); }; //............................................ mouseUpdate // This function adds an mouse state vector to its queue. // If the state description is a mousemove, the city block distance between this position and the previous state on the queue // must be greater than a threshold. Otherwise the state is not added to the queue. // // A Mouse State Vector is a definition of the mouse state: // time stamp // + desc {"mousemove", "mousedown", ...} // + state cPoint {x,y} of mouse position in base image coordinates // // parameters // state: cPoint {x,y} of mouse position in base image coordinates // eventDesc: {"mousemove", "mousedown",} // bForce: boolean, if true the function does not exit when there are no listeners // so us.evMOUSECHANGE event is fired if mouse move is sufficient var lastMouseState_ = new cPoint(0, 0); this.mouseUpdate = function (state, eventDesc, bForce) { if (bForce == false && cb_mouseState.length == 0) // do not save state if no one is subscribed return; //dbg-only if (us.DBGSTATEVECTOREX) thisImg.log("cStateVector: mouseUpdate: " + state.toString() + " desc: " + eventDesc); if (mouseQueue.length == mouseSizeMax) // maintain queue size mouseQueue.shift(); // remove the top element of the array to make room at the bottom var magpx = 0; if (eventDesc == "mousemove") { if (lastMouseState_) { // throttle the responsivity to motion magpx = lastMouseState_.cityBlockDistance(state); //consoleWrite("cur state: " + state + " last state: " + lastMouseState_.toString() + " magpx: " + magpx); if (magpx < minMoveMagnitude_) { //dbg-only if (us.DBGSTATEVECTOREX) thisImg.log("cStateVector: mouseUpdate: magnitude of move (" + magpx + ") < minimum (" + minMoveMagnitude_ + ")"); return; } } } var sv = []; // add info to new state vector sv.time = _sinceStartTime(new Date().getTime()); // add time stamp sv.desc = eventDesc; // add input change description sv.state = jQuery.extend(true, {}, state); // add input view state, must clone state first mouseQueue.push(sv); // add state vector to the queue lastMouseState_.setPoint(sv.state); // save last queue mouse position //dbg-only if (us.DBGSTATEVECTOREX) thisImg.log("cStateVector: mouseUpdate: desc: " + sv.desc + sv.state.toString() + " magnitude: " + magpx); for (var c = 0, len = cb_mouseState.length; c < len; c++) // execute the callbacks to signal a SV update event cb_mouseState[c](); triggerUScopeEvent(us.evMOUSECHANGE, { imageId: imageId_, uScopeIdx: uScopeIdx_, uScopeIdx: thisImg.getImageIdx(), x: state.x, y: state.y }); }; //............................................ getLastMousePosition // This function returns the last recorded mouse position or undefined if none have been recorded. this.getLastMousePosition = function () { return (mouseQueue.length > 0) ? mouseQueue[mouseQueue.length - 1].state : undefined; }; //............................................ getMouseEventsSince // This function returns an array in ascending order of the mouse events since a specified time. // The time stamp in the list of events is in this object's format - delta time since the start of the object scaled by dTime; // Optionally a specific type of mouse event can be selected. // A maximum number of returned events is enforced but can be overridden. // // parameters: // sinceTime required, time to start collecting the event, sinceTime = new Date().getTime() // eventDesc optional, return this mouse event type {"mousemove", "mousedown", ...} default is all // maxRtnSize optional, maximum number of mousestates to return, default is 100 this.getMouseEventsSince = function (sinceTime, eventDesc, maxRtnSize) { var rtnQueue = []; if (isUnDefined(sinceTime)) return rtnQueue; sinceTime = _sinceStartTime(sinceTime); // convert to same time format as used here in if (mouseQueue.length > 0) { eventDesc = (eventDesc) ? eventDesc : "all"; // set event filter maxRtnSize = (maxRtnSize) ? maxRtnSize + 1 : 101; // set limit of number of items returned var cnt = 0; var startIdx = mouseQueue.length; while (--startIdx > 0 && ++cnt < maxRtnSize) { if (mouseQueue[startIdx].time < sinceTime) // am I now before my time? break; if (eventDesc == "all" || eventDesc == mouseQueue[startIdx].desc) rtnQueue.unshift(mouseQueue[startIdx]); // add to the begining of the array for ascending order } } return rtnQueue; }; //............................................ getPrevNext this.getPrevNext = function (incr) {//incr s/b +/-1 if (imageQueue.length < 1) return undefined; var rtnSV = undefined; if (idxPrevNext == -1) { idxPrevNext = imageQueue.length - 1 + incr; idxPrevNextStart = imageQueue.length - 1; } else { idxPrevNext = idxPrevNext + incr; if (idxPrevNext > idxPrevNextStart) idxPrevNext = idxPrevNextStart; // don't move past starting position } /////thisImg.log("getPrevNext: idxPrevNext: " + idxPrevNext); if (idxPrevNext > 0 && idxPrevNext < imageQueue.length) rtnSV = imageQueue[idxPrevNext]; if (idxPrevNext == idxPrevNextStart) idxPrevNext = -1; //reset return rtnSV; }; //............................................ getLastDirection // This function returns the last recorded image direction or undefined if none have been recorded. this.getLastDirection = function () { return (imageQueue.length > 0) ? imageQueue[imageQueue.length - 1].dir : undefined; }; //............................................ getLastDescription // This function returns the last recorded image description or undefined if none have been recorded. this.getLastDescription = function () { return (imageQueue.length > 0) ? imageQueue[imageQueue.length - 1].desc : undefined; }; //............................................ getLast // This function returns the last state vector for the specified state type. this.getLast = function (stateType) {//cp-todo rename to get LastState if (isUnDefined(stateType)) stateType = us.eStateTypes.view; if (stateType === us.eStateTypes.view) return (imageQueue.length > 0) ? imageQueue[imageQueue.length - 1] : undefined; else return (mouseQueue.length > 0) ? mouseQueue[mouseQueue.length - 1] : undefined; }; //............................................ reportLast // This function returns a string containing the last state vector report for the specified state type. this.reportLast = function (stateType) { var str = ""; var queue = (stateType === us.eStateTypes.view) ? imageQueue : mouseQueue; if (queue.length > 0) { str = (stateType === us.eStateTypes.view) ? "LastViewState: " : "LastMouseState: "; var state = queue[queue.length - 1]; str += this.report(state, stateType); } return str; }; //............................................ report // This function converts the passed state into a csv string. this.report = function (stateVector, stateType) { var str = ""; if (isUnDefined(stateVector)) return str; if (isUnDefined(stateType)) stateType = us.eStateTypes.view; if (stateType === us.eStateTypes.view) { var zoom = stateVector.state.zoom; var isFit = thisImg.isFitZoom(zoom); var mag = (isFit) ? "Fit" : thisImg.convertToMag(zoom); zoom = (isFit) ? "Fit" : zoom; // note that this format is copied into the performance test sequence in cPerformanceTest str = parseInt(stateVector.time) + ', \"' + stateVector.desc + '\", ' + stateVector.state.left + ", " + stateVector.state.top + ", " + zoom + ", " + mag; //note: stateVector.dir & stateVector.magpx not reported (yet?) } else { var sv = mouseQueue[mouseQueue.length - 1]; str = stateVector.desc; str += stateVector.state.toString(); if (stateVector.magpx) str += " magnitude_px:" + stateVector.magpx; } return str; }; this.reportTitle = function (stateType) { var str = ""; if (isUnDefined(stateType)) stateType = us.eStateTypes.view; str = "Filename: " + thisImg.getFileName() + " Width: " + thisImg.getImageWidth() + " Height:" + thisImg.getImageHeight() + "\n"; if (stateType === us.eStateTypes.view) { str += "time, desc, centerX, centerY, zoom, mag\n"; //note: stateVector.dir & stateVector.magpx not reported (yet?) } else { // not implemented } return str; }; //............................................ reportAll this.reportAll = function (stateType, normalize) { var str = this.reportTitle(stateType); if (isUnDefined(stateType)) stateType = us.eStateTypes.view; if (isUnDefined(normalize)) normalize = false; var queue = (stateType === us.eStateTypes.view) ? imageQueue : mouseQueue; if (queue.length > 0) { for (var s = 0, len = queue.length; s < len; s++) { var svRef = queue[s]; // get state vector at index s var sv = new cloneObject(svRef); // clone the state vector so I can modify it var x = sv.state.left; // state reports top left corner, convert to center position var y = sv.state.top; x = parseInt(x + thisImg.getViewWidth() / 2); y = parseInt(y + thisImg.getViewHeight() / 2); if (normalize == true) { // if normalize, x and y are proportion of the image dims x = (x / thisImg.getImageWidth()).toFixed(5); y = (y / thisImg.getImageHeight()).toFixed(5); } sv.state.left = x; sv.state.top = y; str += (this.report(sv, stateType) + "\n"); } } return str; }; //............................................ _computeDir // This function evaluates the most recent state change and concludes the view motion direction. // It then adds that direction to the passed array. var _computeDir = function (ioSV) { ioSV.dir = "none"; if (imageQueue.length == 0 || ioSV.desc == "all" || ioSV.desc != "move") return; var lastState = self.getLast(stateTypeView).state; var dx = ioSV.state.left - lastState.left; var dy = ioSV.state.top - lastState.top; if (Math.abs(dx) > lastState.width * 2 || Math.abs(dy) > lastState.height * 2 // if moved N views //cp-revisit factor of 2 || ioSV.desc == "dim") { // or resized view dimensions ioSV.dir = "wholeview"; // then indicate whole view change return; } var dr = slopeLimit + 1; // slope of motion if (dy != 0) dr = dx / dy; if (us.DBGSTATEVECTOREX) ioSV.magpx ? thisImg.log("cStateVector: computeDir: " + dr.toFixed(2) + " dx dy:" + dx + " " + dy + " magpx:" + ioSV.magpx) : thisImg.log("cStateVector: computeDir: " + dr.toFixed(2) + " dx dy:" + dx + " " + dy); var dir = "none"; // default direction of move if (Math.abs(dr) > slopeLimit) { // if horizontal motion if (dx < 0) // if moving left dir = "east"; else dir = "west"; } else if (Math.abs(dr) < slopeLimtInv) { // if vertical motion if (dy < 0) // if moving up dir = "south"; else dir = "north"; } else if (dx < 0) { // diagnal motion, moving left if (dy < 0) // if moving up, too dir = "southeast"; else dir = "northeast"; } else { // diagnal motion, moving right if (dy < 0) // if moving up, too dir = "southwest"; else dir = "northwest"; } ioSV.dir = dir; // add direction to return ioSV }; //............................................................................................ // construction _setSize(kSVQUEUE_VIEW_SIZE); // save the max queue size allowed }; //________________________________________________________________________________________________
cStateVector
identifier_name
socket.js
'use strict'; var phonetic = require('phonetic'); var socketio = require('socket.io'); var _ = require('underscore'); var load = function(http) { var io = socketio(http); var ioNamespace = '/'; var getEmptyRoomId = function() { var roomId = null; do { roomId = phonetic.generate().toLowerCase() } while (io.nsps[ioNamespace].adapter.rooms[roomId]); return roomId; }; var sendRoomInfo = function(socket, info) { if (!info.roomId) { return; } var clients = io.nsps[ioNamespace].adapter.rooms[info.roomId]; io.sockets.in(info.roomId).emit('room.info', { id: info.roomId, count: clients ? Object.keys(clients).length : 0 }); }; var onJoin = function(socket, info, data) { if (info.roomId)
info.roomId = data && data.roomId ? data.roomId : null; if (!info.roomId || !io.nsps[ioNamespace].adapter.rooms[data.roomId]) { info.roomId = getEmptyRoomId(socket); console.log('[Socket] Assigning room id ' + info.roomId + ' to ip ' + socket.handshake.address); } else { console.log('[Socket] Assigning room id ' + info.roomId + ' to ip ' + socket.handshake.address + ' (from client)'); } socket.join(info.roomId); socket.emit('join', { roomId: info.roomId }); sendRoomInfo(socket, info); }; var onEvent = function(socket, info, event, data) { if (!info.roomId) { return; } socket.broadcast.to(info.roomId).emit(event, data); }; var onChunk = function(socket, info, data) { socket.emit('file.ack', { guid: data.guid }); onEvent(socket, info, 'file.chunk', data); }; var onConnection = function(socket) { console.log('[Socket] New connection from ip ' + socket.handshake.address); var info = { roomId: null }; socket.on('disconnect', function() { console.log('[Socket] Connection from ip ' + socket.handshake.address + ' disconnected'); sendRoomInfo(socket, info); }); socket.on('join', _.partial(onJoin, socket, info)); socket.on('file.start', _.partial(onEvent, socket, info, 'file.start')); socket.on('file.chunk', _.partial(onChunk, socket, info)); } io.on('connection', onConnection); }; module.exports = { load: load };
{ return; }
conditional_block
socket.js
'use strict'; var phonetic = require('phonetic'); var socketio = require('socket.io'); var _ = require('underscore'); var load = function(http) { var io = socketio(http); var ioNamespace = '/'; var getEmptyRoomId = function() { var roomId = null; do { roomId = phonetic.generate().toLowerCase() } while (io.nsps[ioNamespace].adapter.rooms[roomId]); return roomId; }; var sendRoomInfo = function(socket, info) { if (!info.roomId) { return; } var clients = io.nsps[ioNamespace].adapter.rooms[info.roomId]; io.sockets.in(info.roomId).emit('room.info', { id: info.roomId, count: clients ? Object.keys(clients).length : 0 }); }; var onJoin = function(socket, info, data) { if (info.roomId) { return; } info.roomId = data && data.roomId ? data.roomId : null; if (!info.roomId || !io.nsps[ioNamespace].adapter.rooms[data.roomId]) { info.roomId = getEmptyRoomId(socket); console.log('[Socket] Assigning room id ' + info.roomId + ' to ip ' + socket.handshake.address); } else { console.log('[Socket] Assigning room id ' + info.roomId + ' to ip ' + socket.handshake.address + ' (from client)'); } socket.join(info.roomId); socket.emit('join', { roomId: info.roomId }); sendRoomInfo(socket, info); }; var onEvent = function(socket, info, event, data) { if (!info.roomId) { return; } socket.broadcast.to(info.roomId).emit(event, data); }; var onChunk = function(socket, info, data) { socket.emit('file.ack', { guid: data.guid }); onEvent(socket, info, 'file.chunk', data); }; var onConnection = function(socket) { console.log('[Socket] New connection from ip ' + socket.handshake.address); var info = { roomId: null }; socket.on('disconnect', function() { console.log('[Socket] Connection from ip ' + socket.handshake.address + ' disconnected'); sendRoomInfo(socket, info); }); socket.on('join', _.partial(onJoin, socket, info)); socket.on('file.start', _.partial(onEvent, socket, info, 'file.start')); socket.on('file.chunk', _.partial(onChunk, socket, info)); }
module.exports = { load: load };
io.on('connection', onConnection); };
random_line_split
vga.rs
use core::prelude::*; use io; const BACKSPACE: u8 = 0x08; const TAB: u8 = 0x09; const NEWLINE: u8 = 0x0A; const CR: u8 = 0x0D; const WHITESPACE: u8 = 0x20; const VGA_ADDRESS: int = 0xB8000; const VGA_HEIGHT: u16 = 25; const VGA_WIDTH: u16 = 80; enum Color { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Pink = 5, Brown = 6, LightGray = 7, DarkGray = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, LightPink = 13, Yellow = 14, White = 15, } static mut VGA: VGA = VGA { height: VGA_HEIGHT, width: VGA_WIDTH, x: 0, y: 0 }; struct VGA { height: u16, width: u16, x: u16, y: u16, } impl VGA { fn new() -> VGA { VGA {height: VGA_HEIGHT, width: VGA_WIDTH, x: 0, y: 0} } fn back(&mut self) { if self.x > 0 { self.x -= 1; let offset = self.offset(); self.put(offset, Black as u16, White as u16, WHITESPACE); } } fn forward(&mut self) { self.x += 1; if self.x >= self.width { self.newline(); } } fn cr(&mut self) { self.x = 0; } fn newline(&mut self) { self.x = 0; self.y += 1; } fn offset(&self) -> u16 { self.y * self.width + self.x } fn reset(&mut self) { self.x = 0; self.y = 0; self.mov(); } // handle a tab by increasing the cursor's X, but only to a point // where it is divisible by 8 fn tab(&mut self) { self.x = (self.x + 8) & !(8 - 1); } fn mov(&mut self) { let offset = self.offset() as u8; io::port::write(0x3D4, 14); // tell the VGA board we are setting the high cursor byte io::port::write(0x3D5, offset >> 8); // send the high cursor byte io::port::write(0x3D4, 15); // tell the VGA board we are setting the low cursor byte io::port::write(0x3D5, offset); } fn clear (&mut self) { let mut x: u16 = 0; loop { if x > 80 * 200 { break; } self.put(x, Black as u16, White as u16, WHITESPACE); x += 1; } } fn put(&mut self, offset: u16, background: u16, foreground: u16, character: u8) { let pixel: u16 = (background << 12) | (foreground << 8) | character as u16; unsafe { *((VGA_ADDRESS + offset as int * 2) as *mut u16) = pixel; } } fn putc(&mut self, character: u8) { if character == BACKSPACE { self.back(); } else if character == TAB { self.tab(); } else if character == NEWLINE { self.newline(); } else if character == CR { self.cr(); } else if character >= WHITESPACE { let offset = self.offset(); self.put(offset, Black as u16, White as u16, character); self.forward(); } self.mov(); } fn puti(&mut self, integer: uint) { if integer == 0 { self.puts("0"); } else { let mut integer = integer; let mut reversed = 0; while integer > 0 { reversed *= 10; reversed += integer % 10; integer /= 10; } while reversed > 0 { let character = (reversed % 10) as u8 + '0' as u8; self.putc(character); reversed /= 10; } } } fn puth(&mut self, integer: uint) { self.puts("0x"); let mut nibbles = 1; while (integer >> nibbles * 4) > 0 { nibbles += 1 } for i in range(0, nibbles) { let nibble = ((integer >> (nibbles - i - 1) * 4) & 0xF) as u8; let character = if nibble < 10 { '0' as u8 + nibble } else { 'a' as u8 + nibble - 10 }; self.putc(character); } } fn puts(&mut self, string: &str) { for character in string.bytes() { self.putc(character); } } } pub fn clear() { unsafe { VGA.clear(); } } pub fn puth(integer: uint) { unsafe { VGA.puth(integer); } } pub fn puti(integer: uint) { unsafe { VGA.puti(integer); } }
VGA.putc(character); } } pub fn puts(string: &str) { unsafe { VGA.puts(string); } }
pub fn putc(character: u8) { unsafe {
random_line_split
vga.rs
use core::prelude::*; use io; const BACKSPACE: u8 = 0x08; const TAB: u8 = 0x09; const NEWLINE: u8 = 0x0A; const CR: u8 = 0x0D; const WHITESPACE: u8 = 0x20; const VGA_ADDRESS: int = 0xB8000; const VGA_HEIGHT: u16 = 25; const VGA_WIDTH: u16 = 80; enum Color { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Pink = 5, Brown = 6, LightGray = 7, DarkGray = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, LightPink = 13, Yellow = 14, White = 15, } static mut VGA: VGA = VGA { height: VGA_HEIGHT, width: VGA_WIDTH, x: 0, y: 0 }; struct VGA { height: u16, width: u16, x: u16, y: u16, } impl VGA { fn new() -> VGA { VGA {height: VGA_HEIGHT, width: VGA_WIDTH, x: 0, y: 0} } fn back(&mut self) { if self.x > 0 { self.x -= 1; let offset = self.offset(); self.put(offset, Black as u16, White as u16, WHITESPACE); } } fn forward(&mut self) { self.x += 1; if self.x >= self.width { self.newline(); } } fn cr(&mut self) { self.x = 0; } fn newline(&mut self) { self.x = 0; self.y += 1; } fn offset(&self) -> u16 { self.y * self.width + self.x } fn reset(&mut self) { self.x = 0; self.y = 0; self.mov(); } // handle a tab by increasing the cursor's X, but only to a point // where it is divisible by 8 fn tab(&mut self) { self.x = (self.x + 8) & !(8 - 1); } fn mov(&mut self) { let offset = self.offset() as u8; io::port::write(0x3D4, 14); // tell the VGA board we are setting the high cursor byte io::port::write(0x3D5, offset >> 8); // send the high cursor byte io::port::write(0x3D4, 15); // tell the VGA board we are setting the low cursor byte io::port::write(0x3D5, offset); } fn clear (&mut self) { let mut x: u16 = 0; loop { if x > 80 * 200 { break; } self.put(x, Black as u16, White as u16, WHITESPACE); x += 1; } } fn put(&mut self, offset: u16, background: u16, foreground: u16, character: u8) { let pixel: u16 = (background << 12) | (foreground << 8) | character as u16; unsafe { *((VGA_ADDRESS + offset as int * 2) as *mut u16) = pixel; } } fn putc(&mut self, character: u8)
fn puti(&mut self, integer: uint) { if integer == 0 { self.puts("0"); } else { let mut integer = integer; let mut reversed = 0; while integer > 0 { reversed *= 10; reversed += integer % 10; integer /= 10; } while reversed > 0 { let character = (reversed % 10) as u8 + '0' as u8; self.putc(character); reversed /= 10; } } } fn puth(&mut self, integer: uint) { self.puts("0x"); let mut nibbles = 1; while (integer >> nibbles * 4) > 0 { nibbles += 1 } for i in range(0, nibbles) { let nibble = ((integer >> (nibbles - i - 1) * 4) & 0xF) as u8; let character = if nibble < 10 { '0' as u8 + nibble } else { 'a' as u8 + nibble - 10 }; self.putc(character); } } fn puts(&mut self, string: &str) { for character in string.bytes() { self.putc(character); } } } pub fn clear() { unsafe { VGA.clear(); } } pub fn puth(integer: uint) { unsafe { VGA.puth(integer); } } pub fn puti(integer: uint) { unsafe { VGA.puti(integer); } } pub fn putc(character: u8) { unsafe { VGA.putc(character); } } pub fn puts(string: &str) { unsafe { VGA.puts(string); } }
{ if character == BACKSPACE { self.back(); } else if character == TAB { self.tab(); } else if character == NEWLINE { self.newline(); } else if character == CR { self.cr(); } else if character >= WHITESPACE { let offset = self.offset(); self.put(offset, Black as u16, White as u16, character); self.forward(); } self.mov(); }
identifier_body
vga.rs
use core::prelude::*; use io; const BACKSPACE: u8 = 0x08; const TAB: u8 = 0x09; const NEWLINE: u8 = 0x0A; const CR: u8 = 0x0D; const WHITESPACE: u8 = 0x20; const VGA_ADDRESS: int = 0xB8000; const VGA_HEIGHT: u16 = 25; const VGA_WIDTH: u16 = 80; enum Color { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Pink = 5, Brown = 6, LightGray = 7, DarkGray = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, LightPink = 13, Yellow = 14, White = 15, } static mut VGA: VGA = VGA { height: VGA_HEIGHT, width: VGA_WIDTH, x: 0, y: 0 }; struct VGA { height: u16, width: u16, x: u16, y: u16, } impl VGA { fn new() -> VGA { VGA {height: VGA_HEIGHT, width: VGA_WIDTH, x: 0, y: 0} } fn back(&mut self) { if self.x > 0 { self.x -= 1; let offset = self.offset(); self.put(offset, Black as u16, White as u16, WHITESPACE); } } fn forward(&mut self) { self.x += 1; if self.x >= self.width { self.newline(); } } fn cr(&mut self) { self.x = 0; } fn newline(&mut self) { self.x = 0; self.y += 1; } fn offset(&self) -> u16 { self.y * self.width + self.x } fn reset(&mut self) { self.x = 0; self.y = 0; self.mov(); } // handle a tab by increasing the cursor's X, but only to a point // where it is divisible by 8 fn tab(&mut self) { self.x = (self.x + 8) & !(8 - 1); } fn mov(&mut self) { let offset = self.offset() as u8; io::port::write(0x3D4, 14); // tell the VGA board we are setting the high cursor byte io::port::write(0x3D5, offset >> 8); // send the high cursor byte io::port::write(0x3D4, 15); // tell the VGA board we are setting the low cursor byte io::port::write(0x3D5, offset); } fn clear (&mut self) { let mut x: u16 = 0; loop { if x > 80 * 200 { break; } self.put(x, Black as u16, White as u16, WHITESPACE); x += 1; } } fn put(&mut self, offset: u16, background: u16, foreground: u16, character: u8) { let pixel: u16 = (background << 12) | (foreground << 8) | character as u16; unsafe { *((VGA_ADDRESS + offset as int * 2) as *mut u16) = pixel; } } fn putc(&mut self, character: u8) { if character == BACKSPACE { self.back(); } else if character == TAB { self.tab(); } else if character == NEWLINE { self.newline(); } else if character == CR { self.cr(); } else if character >= WHITESPACE { let offset = self.offset(); self.put(offset, Black as u16, White as u16, character); self.forward(); } self.mov(); } fn puti(&mut self, integer: uint) { if integer == 0 { self.puts("0"); } else { let mut integer = integer; let mut reversed = 0; while integer > 0 { reversed *= 10; reversed += integer % 10; integer /= 10; } while reversed > 0 { let character = (reversed % 10) as u8 + '0' as u8; self.putc(character); reversed /= 10; } } } fn
(&mut self, integer: uint) { self.puts("0x"); let mut nibbles = 1; while (integer >> nibbles * 4) > 0 { nibbles += 1 } for i in range(0, nibbles) { let nibble = ((integer >> (nibbles - i - 1) * 4) & 0xF) as u8; let character = if nibble < 10 { '0' as u8 + nibble } else { 'a' as u8 + nibble - 10 }; self.putc(character); } } fn puts(&mut self, string: &str) { for character in string.bytes() { self.putc(character); } } } pub fn clear() { unsafe { VGA.clear(); } } pub fn puth(integer: uint) { unsafe { VGA.puth(integer); } } pub fn puti(integer: uint) { unsafe { VGA.puti(integer); } } pub fn putc(character: u8) { unsafe { VGA.putc(character); } } pub fn puts(string: &str) { unsafe { VGA.puts(string); } }
puth
identifier_name
vga.rs
use core::prelude::*; use io; const BACKSPACE: u8 = 0x08; const TAB: u8 = 0x09; const NEWLINE: u8 = 0x0A; const CR: u8 = 0x0D; const WHITESPACE: u8 = 0x20; const VGA_ADDRESS: int = 0xB8000; const VGA_HEIGHT: u16 = 25; const VGA_WIDTH: u16 = 80; enum Color { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Pink = 5, Brown = 6, LightGray = 7, DarkGray = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, LightPink = 13, Yellow = 14, White = 15, } static mut VGA: VGA = VGA { height: VGA_HEIGHT, width: VGA_WIDTH, x: 0, y: 0 }; struct VGA { height: u16, width: u16, x: u16, y: u16, } impl VGA { fn new() -> VGA { VGA {height: VGA_HEIGHT, width: VGA_WIDTH, x: 0, y: 0} } fn back(&mut self) { if self.x > 0 { self.x -= 1; let offset = self.offset(); self.put(offset, Black as u16, White as u16, WHITESPACE); } } fn forward(&mut self) { self.x += 1; if self.x >= self.width { self.newline(); } } fn cr(&mut self) { self.x = 0; } fn newline(&mut self) { self.x = 0; self.y += 1; } fn offset(&self) -> u16 { self.y * self.width + self.x } fn reset(&mut self) { self.x = 0; self.y = 0; self.mov(); } // handle a tab by increasing the cursor's X, but only to a point // where it is divisible by 8 fn tab(&mut self) { self.x = (self.x + 8) & !(8 - 1); } fn mov(&mut self) { let offset = self.offset() as u8; io::port::write(0x3D4, 14); // tell the VGA board we are setting the high cursor byte io::port::write(0x3D5, offset >> 8); // send the high cursor byte io::port::write(0x3D4, 15); // tell the VGA board we are setting the low cursor byte io::port::write(0x3D5, offset); } fn clear (&mut self) { let mut x: u16 = 0; loop { if x > 80 * 200 { break; } self.put(x, Black as u16, White as u16, WHITESPACE); x += 1; } } fn put(&mut self, offset: u16, background: u16, foreground: u16, character: u8) { let pixel: u16 = (background << 12) | (foreground << 8) | character as u16; unsafe { *((VGA_ADDRESS + offset as int * 2) as *mut u16) = pixel; } } fn putc(&mut self, character: u8) { if character == BACKSPACE { self.back(); } else if character == TAB { self.tab(); } else if character == NEWLINE { self.newline(); } else if character == CR
else if character >= WHITESPACE { let offset = self.offset(); self.put(offset, Black as u16, White as u16, character); self.forward(); } self.mov(); } fn puti(&mut self, integer: uint) { if integer == 0 { self.puts("0"); } else { let mut integer = integer; let mut reversed = 0; while integer > 0 { reversed *= 10; reversed += integer % 10; integer /= 10; } while reversed > 0 { let character = (reversed % 10) as u8 + '0' as u8; self.putc(character); reversed /= 10; } } } fn puth(&mut self, integer: uint) { self.puts("0x"); let mut nibbles = 1; while (integer >> nibbles * 4) > 0 { nibbles += 1 } for i in range(0, nibbles) { let nibble = ((integer >> (nibbles - i - 1) * 4) & 0xF) as u8; let character = if nibble < 10 { '0' as u8 + nibble } else { 'a' as u8 + nibble - 10 }; self.putc(character); } } fn puts(&mut self, string: &str) { for character in string.bytes() { self.putc(character); } } } pub fn clear() { unsafe { VGA.clear(); } } pub fn puth(integer: uint) { unsafe { VGA.puth(integer); } } pub fn puti(integer: uint) { unsafe { VGA.puti(integer); } } pub fn putc(character: u8) { unsafe { VGA.putc(character); } } pub fn puts(string: &str) { unsafe { VGA.puts(string); } }
{ self.cr(); }
conditional_block
LossOfControl.ts
import { OvaleDebug } from "./Debug"; import { OvaleProfiler } from "./Profiler"; import { Ovale } from "./Ovale"; import { OvaleState } from "./State"; import { RegisterRequirement, UnregisterRequirement, Tokens } from "./Requirement"; import aceEvent from "@wowts/ace_event-3.0"; import { C_LossOfControl, GetTime } from "@wowts/wow-mock"; import { LuaArray, pairs } from "@wowts/lua"; import { insert } from "@wowts/table"; import { sub, upper } from "@wowts/string"; interface LossOfControlEventInfo{ locType: string; spellID: number; startTime: number, duration: number, } export let OvaleLossOfControl:OvaleLossOfControlClass; const OvaleLossOfControlBase = OvaleProfiler.RegisterProfiling(OvaleDebug.RegisterDebugging(Ovale.NewModule("OvaleLossOfControl", aceEvent))) class OvaleLossOfControlClass extends OvaleLossOfControlBase { lossOfControlHistory: LuaArray<LossOfControlEventInfo>; OnInitialize()
OnDisable() { this.Debug("Disabled LossOfControl module"); this.lossOfControlHistory = {}; this.UnregisterEvent("LOSS_OF_CONTROL_ADDED"); UnregisterRequirement("lossofcontrol"); } LOSS_OF_CONTROL_ADDED(event: string, eventIndex: number){ this.Debug("GetEventInfo:", eventIndex, C_LossOfControl.GetEventInfo(eventIndex)); let [locType, spellID, , , startTime, , duration] = C_LossOfControl.GetEventInfo(eventIndex); let data: LossOfControlEventInfo = { locType: upper(locType), spellID: spellID, startTime: startTime || GetTime(), duration: duration || 10, } insert(this.lossOfControlHistory, data); } RequireLossOfControlHandler = (spellId: number, atTime: number, requirement:string, tokens: Tokens, index: number, targetGUID: string):[boolean, string, number] => { let verified: boolean = false; let locType = <string>tokens[index]; index = index + 1; if (locType) { let required = true; if (sub(locType, 1, 1) === "!") { required = false; locType = sub(locType, 2); } let hasLoss = this.HasLossOfControl(locType, atTime); verified = (required && hasLoss) || (!required && !hasLoss); } else { Ovale.OneTimeMessage("Warning: requirement '%s' is missing a locType argument.", requirement); } return [verified, requirement, index]; } HasLossOfControl = function(locType: string, atTime: number) { let lowestStartTime: number|undefined = undefined; let highestEndTime: number|undefined = undefined; for (const [, data] of pairs<LossOfControlEventInfo>(this.lossOfControlHistory)) { if (upper(locType) == data.locType && (data.startTime <= atTime && atTime <= data.startTime+data.duration)) { if (lowestStartTime == undefined || lowestStartTime > data.startTime) { lowestStartTime = data.startTime; } if (highestEndTime == undefined || highestEndTime < data.startTime + data.duration) { highestEndTime = data.startTime+data.duration; } } } return lowestStartTime != undefined && highestEndTime != undefined; } CleanState(): void { } InitializeState(): void { } ResetState(): void { } } OvaleLossOfControl = new OvaleLossOfControlClass(); OvaleState.RegisterState(OvaleLossOfControl);
{ this.Debug("Enabled LossOfControl module"); this.lossOfControlHistory = {}; this.RegisterEvent("LOSS_OF_CONTROL_ADDED"); RegisterRequirement("lossofcontrol", this.RequireLossOfControlHandler); }
identifier_body
LossOfControl.ts
import { OvaleDebug } from "./Debug"; import { OvaleProfiler } from "./Profiler"; import { Ovale } from "./Ovale"; import { OvaleState } from "./State"; import { RegisterRequirement, UnregisterRequirement, Tokens } from "./Requirement"; import aceEvent from "@wowts/ace_event-3.0"; import { C_LossOfControl, GetTime } from "@wowts/wow-mock"; import { LuaArray, pairs } from "@wowts/lua"; import { insert } from "@wowts/table"; import { sub, upper } from "@wowts/string"; interface LossOfControlEventInfo{ locType: string; spellID: number; startTime: number, duration: number, } export let OvaleLossOfControl:OvaleLossOfControlClass; const OvaleLossOfControlBase = OvaleProfiler.RegisterProfiling(OvaleDebug.RegisterDebugging(Ovale.NewModule("OvaleLossOfControl", aceEvent))) class OvaleLossOfControlClass extends OvaleLossOfControlBase { lossOfControlHistory: LuaArray<LossOfControlEventInfo>; OnInitialize() { this.Debug("Enabled LossOfControl module"); this.lossOfControlHistory = {}; this.RegisterEvent("LOSS_OF_CONTROL_ADDED"); RegisterRequirement("lossofcontrol", this.RequireLossOfControlHandler); } OnDisable() { this.Debug("Disabled LossOfControl module"); this.lossOfControlHistory = {}; this.UnregisterEvent("LOSS_OF_CONTROL_ADDED"); UnregisterRequirement("lossofcontrol"); } LOSS_OF_CONTROL_ADDED(event: string, eventIndex: number){
this.Debug("GetEventInfo:", eventIndex, C_LossOfControl.GetEventInfo(eventIndex)); let [locType, spellID, , , startTime, , duration] = C_LossOfControl.GetEventInfo(eventIndex); let data: LossOfControlEventInfo = { locType: upper(locType), spellID: spellID, startTime: startTime || GetTime(), duration: duration || 10, } insert(this.lossOfControlHistory, data); } RequireLossOfControlHandler = (spellId: number, atTime: number, requirement:string, tokens: Tokens, index: number, targetGUID: string):[boolean, string, number] => { let verified: boolean = false; let locType = <string>tokens[index]; index = index + 1; if (locType) { let required = true; if (sub(locType, 1, 1) === "!") { required = false; locType = sub(locType, 2); } let hasLoss = this.HasLossOfControl(locType, atTime); verified = (required && hasLoss) || (!required && !hasLoss); } else { Ovale.OneTimeMessage("Warning: requirement '%s' is missing a locType argument.", requirement); } return [verified, requirement, index]; } HasLossOfControl = function(locType: string, atTime: number) { let lowestStartTime: number|undefined = undefined; let highestEndTime: number|undefined = undefined; for (const [, data] of pairs<LossOfControlEventInfo>(this.lossOfControlHistory)) { if (upper(locType) == data.locType && (data.startTime <= atTime && atTime <= data.startTime+data.duration)) { if (lowestStartTime == undefined || lowestStartTime > data.startTime) { lowestStartTime = data.startTime; } if (highestEndTime == undefined || highestEndTime < data.startTime + data.duration) { highestEndTime = data.startTime+data.duration; } } } return lowestStartTime != undefined && highestEndTime != undefined; } CleanState(): void { } InitializeState(): void { } ResetState(): void { } } OvaleLossOfControl = new OvaleLossOfControlClass(); OvaleState.RegisterState(OvaleLossOfControl);
random_line_split
LossOfControl.ts
import { OvaleDebug } from "./Debug"; import { OvaleProfiler } from "./Profiler"; import { Ovale } from "./Ovale"; import { OvaleState } from "./State"; import { RegisterRequirement, UnregisterRequirement, Tokens } from "./Requirement"; import aceEvent from "@wowts/ace_event-3.0"; import { C_LossOfControl, GetTime } from "@wowts/wow-mock"; import { LuaArray, pairs } from "@wowts/lua"; import { insert } from "@wowts/table"; import { sub, upper } from "@wowts/string"; interface LossOfControlEventInfo{ locType: string; spellID: number; startTime: number, duration: number, } export let OvaleLossOfControl:OvaleLossOfControlClass; const OvaleLossOfControlBase = OvaleProfiler.RegisterProfiling(OvaleDebug.RegisterDebugging(Ovale.NewModule("OvaleLossOfControl", aceEvent))) class OvaleLossOfControlClass extends OvaleLossOfControlBase { lossOfControlHistory: LuaArray<LossOfControlEventInfo>; OnInitialize() { this.Debug("Enabled LossOfControl module"); this.lossOfControlHistory = {}; this.RegisterEvent("LOSS_OF_CONTROL_ADDED"); RegisterRequirement("lossofcontrol", this.RequireLossOfControlHandler); } OnDisable() { this.Debug("Disabled LossOfControl module"); this.lossOfControlHistory = {}; this.UnregisterEvent("LOSS_OF_CONTROL_ADDED"); UnregisterRequirement("lossofcontrol"); } LOSS_OF_CONTROL_ADDED(event: string, eventIndex: number){ this.Debug("GetEventInfo:", eventIndex, C_LossOfControl.GetEventInfo(eventIndex)); let [locType, spellID, , , startTime, , duration] = C_LossOfControl.GetEventInfo(eventIndex); let data: LossOfControlEventInfo = { locType: upper(locType), spellID: spellID, startTime: startTime || GetTime(), duration: duration || 10, } insert(this.lossOfControlHistory, data); } RequireLossOfControlHandler = (spellId: number, atTime: number, requirement:string, tokens: Tokens, index: number, targetGUID: string):[boolean, string, number] => { let verified: boolean = false; let locType = <string>tokens[index]; index = index + 1; if (locType) { let required = true; if (sub(locType, 1, 1) === "!") { required = false; locType = sub(locType, 2); } let hasLoss = this.HasLossOfControl(locType, atTime); verified = (required && hasLoss) || (!required && !hasLoss); } else { Ovale.OneTimeMessage("Warning: requirement '%s' is missing a locType argument.", requirement); } return [verified, requirement, index]; } HasLossOfControl = function(locType: string, atTime: number) { let lowestStartTime: number|undefined = undefined; let highestEndTime: number|undefined = undefined; for (const [, data] of pairs<LossOfControlEventInfo>(this.lossOfControlHistory)) { if (upper(locType) == data.locType && (data.startTime <= atTime && atTime <= data.startTime+data.duration)) { if (lowestStartTime == undefined || lowestStartTime > data.startTime) { lowestStartTime = data.startTime; } if (highestEndTime == undefined || highestEndTime < data.startTime + data.duration) { highestEndTime = data.startTime+data.duration; } } } return lowestStartTime != undefined && highestEndTime != undefined; } CleanState(): void { } InitializeState(): void { }
(): void { } } OvaleLossOfControl = new OvaleLossOfControlClass(); OvaleState.RegisterState(OvaleLossOfControl);
ResetState
identifier_name
LossOfControl.ts
import { OvaleDebug } from "./Debug"; import { OvaleProfiler } from "./Profiler"; import { Ovale } from "./Ovale"; import { OvaleState } from "./State"; import { RegisterRequirement, UnregisterRequirement, Tokens } from "./Requirement"; import aceEvent from "@wowts/ace_event-3.0"; import { C_LossOfControl, GetTime } from "@wowts/wow-mock"; import { LuaArray, pairs } from "@wowts/lua"; import { insert } from "@wowts/table"; import { sub, upper } from "@wowts/string"; interface LossOfControlEventInfo{ locType: string; spellID: number; startTime: number, duration: number, } export let OvaleLossOfControl:OvaleLossOfControlClass; const OvaleLossOfControlBase = OvaleProfiler.RegisterProfiling(OvaleDebug.RegisterDebugging(Ovale.NewModule("OvaleLossOfControl", aceEvent))) class OvaleLossOfControlClass extends OvaleLossOfControlBase { lossOfControlHistory: LuaArray<LossOfControlEventInfo>; OnInitialize() { this.Debug("Enabled LossOfControl module"); this.lossOfControlHistory = {}; this.RegisterEvent("LOSS_OF_CONTROL_ADDED"); RegisterRequirement("lossofcontrol", this.RequireLossOfControlHandler); } OnDisable() { this.Debug("Disabled LossOfControl module"); this.lossOfControlHistory = {}; this.UnregisterEvent("LOSS_OF_CONTROL_ADDED"); UnregisterRequirement("lossofcontrol"); } LOSS_OF_CONTROL_ADDED(event: string, eventIndex: number){ this.Debug("GetEventInfo:", eventIndex, C_LossOfControl.GetEventInfo(eventIndex)); let [locType, spellID, , , startTime, , duration] = C_LossOfControl.GetEventInfo(eventIndex); let data: LossOfControlEventInfo = { locType: upper(locType), spellID: spellID, startTime: startTime || GetTime(), duration: duration || 10, } insert(this.lossOfControlHistory, data); } RequireLossOfControlHandler = (spellId: number, atTime: number, requirement:string, tokens: Tokens, index: number, targetGUID: string):[boolean, string, number] => { let verified: boolean = false; let locType = <string>tokens[index]; index = index + 1; if (locType)
else { Ovale.OneTimeMessage("Warning: requirement '%s' is missing a locType argument.", requirement); } return [verified, requirement, index]; } HasLossOfControl = function(locType: string, atTime: number) { let lowestStartTime: number|undefined = undefined; let highestEndTime: number|undefined = undefined; for (const [, data] of pairs<LossOfControlEventInfo>(this.lossOfControlHistory)) { if (upper(locType) == data.locType && (data.startTime <= atTime && atTime <= data.startTime+data.duration)) { if (lowestStartTime == undefined || lowestStartTime > data.startTime) { lowestStartTime = data.startTime; } if (highestEndTime == undefined || highestEndTime < data.startTime + data.duration) { highestEndTime = data.startTime+data.duration; } } } return lowestStartTime != undefined && highestEndTime != undefined; } CleanState(): void { } InitializeState(): void { } ResetState(): void { } } OvaleLossOfControl = new OvaleLossOfControlClass(); OvaleState.RegisterState(OvaleLossOfControl);
{ let required = true; if (sub(locType, 1, 1) === "!") { required = false; locType = sub(locType, 2); } let hasLoss = this.HasLossOfControl(locType, atTime); verified = (required && hasLoss) || (!required && !hasLoss); }
conditional_block
gid_filter.rs
use filter; use filter::Filter; use walkdir::DirEntry; use std::os::unix::fs::MetadataExt; use std::process; pub struct GidFilter { gid: u32, comp_op: filter::CompOp, } impl GidFilter { pub fn new(comp_op: filter::CompOp, gid: u32) -> GidFilter { GidFilter{comp_op: comp_op, gid: gid} } } impl Filter for GidFilter { fn test(&self, dir_entry: &DirEntry) -> bool { match self.comp_op { filter::CompOp::Equal => self.gid == dir_entry.metadata().unwrap().gid(), filter::CompOp::Unequal => self.gid != dir_entry.metadata().unwrap().gid(), _ =>
, } } }
{ eprintln!("Operator {:?} not covered for attribute gid!", self.comp_op); process::exit(1); }
conditional_block
gid_filter.rs
use filter; use filter::Filter; use walkdir::DirEntry; use std::os::unix::fs::MetadataExt; use std::process; pub struct GidFilter { gid: u32, comp_op: filter::CompOp, } impl GidFilter { pub fn new(comp_op: filter::CompOp, gid: u32) -> GidFilter { GidFilter{comp_op: comp_op, gid: gid} } } impl Filter for GidFilter { fn test(&self, dir_entry: &DirEntry) -> bool
}
{ match self.comp_op { filter::CompOp::Equal => self.gid == dir_entry.metadata().unwrap().gid(), filter::CompOp::Unequal => self.gid != dir_entry.metadata().unwrap().gid(), _ => { eprintln!("Operator {:?} not covered for attribute gid!", self.comp_op); process::exit(1); }, } }
identifier_body
gid_filter.rs
use filter; use filter::Filter; use walkdir::DirEntry; use std::os::unix::fs::MetadataExt; use std::process; pub struct
{ gid: u32, comp_op: filter::CompOp, } impl GidFilter { pub fn new(comp_op: filter::CompOp, gid: u32) -> GidFilter { GidFilter{comp_op: comp_op, gid: gid} } } impl Filter for GidFilter { fn test(&self, dir_entry: &DirEntry) -> bool { match self.comp_op { filter::CompOp::Equal => self.gid == dir_entry.metadata().unwrap().gid(), filter::CompOp::Unequal => self.gid != dir_entry.metadata().unwrap().gid(), _ => { eprintln!("Operator {:?} not covered for attribute gid!", self.comp_op); process::exit(1); }, } } }
GidFilter
identifier_name
gid_filter.rs
use filter; use filter::Filter; use walkdir::DirEntry; use std::os::unix::fs::MetadataExt; use std::process; pub struct GidFilter { gid: u32, comp_op: filter::CompOp, } impl GidFilter { pub fn new(comp_op: filter::CompOp, gid: u32) -> GidFilter { GidFilter{comp_op: comp_op, gid: gid} } } impl Filter for GidFilter {
eprintln!("Operator {:?} not covered for attribute gid!", self.comp_op); process::exit(1); }, } } }
fn test(&self, dir_entry: &DirEntry) -> bool { match self.comp_op { filter::CompOp::Equal => self.gid == dir_entry.metadata().unwrap().gid(), filter::CompOp::Unequal => self.gid != dir_entry.metadata().unwrap().gid(), _ => {
random_line_split
config.rs
#![allow(dead_code)] use log::LevelFilter; use once_cell::sync::Lazy; use std::str::FromStr; static CONF: Lazy<Config> = Lazy::new(|| { let log_level = std::env::var("SIMAG_LOG_LEVEL") .or_else::<std::env::VarError, _>(|_| Ok("info".to_owned())) .ok() .map(|l| LevelFilter::from_str(&l).unwrap_or_else(|_| LevelFilter::Debug)) .unwrap_or_else(|| LevelFilter::Debug); Config { log_level } }); pub(super) struct Config { pub log_level: log::LevelFilter, } #[cfg(any(test, debug_assertions))] pub(super) mod tracing { use super::*; #[derive(Clone, Copy)] pub struct
; impl Logger { pub fn get_logger() -> &'static Logger { Lazy::force(&LOGGER) } } #[allow(unused_must_use)] static LOGGER: Lazy<Logger> = Lazy::new(|| { env_logger::builder() .format_module_path(true) .format_timestamp_nanos() .target(env_logger::Target::Stdout) .filter(None, CONF.log_level) .try_init(); Logger }); }
Logger
identifier_name
config.rs
#![allow(dead_code)] use log::LevelFilter; use once_cell::sync::Lazy; use std::str::FromStr; static CONF: Lazy<Config> = Lazy::new(|| { let log_level = std::env::var("SIMAG_LOG_LEVEL") .or_else::<std::env::VarError, _>(|_| Ok("info".to_owned())) .ok() .map(|l| LevelFilter::from_str(&l).unwrap_or_else(|_| LevelFilter::Debug)) .unwrap_or_else(|| LevelFilter::Debug); Config { log_level } }); pub(super) struct Config { pub log_level: log::LevelFilter, }
pub struct Logger; impl Logger { pub fn get_logger() -> &'static Logger { Lazy::force(&LOGGER) } } #[allow(unused_must_use)] static LOGGER: Lazy<Logger> = Lazy::new(|| { env_logger::builder() .format_module_path(true) .format_timestamp_nanos() .target(env_logger::Target::Stdout) .filter(None, CONF.log_level) .try_init(); Logger }); }
#[cfg(any(test, debug_assertions))] pub(super) mod tracing { use super::*; #[derive(Clone, Copy)]
random_line_split
gamerules.ts
import { CCSGameRulesProxy } from "../sendtabletypes"; import { Networkable } from "./networkable"; /** * Represents the game rules. */ export class GameRules extends Networkable<CCSGameRulesProxy> { /** * @returns Is the game currently in 'warmup' mode? */ get isWarmup(): boolean { return this.getProp("DT_CSGameRules", "m_bWarmupPeriod"); } /** * @deprecated Use `GameRules#roundsPlayed` instead. */ get roundNumber(): number { return this.roundsPlayed; } /** * This value is incremented when the scores are updated at round end. * If you need to keep track of the current round number, store this value * at each `round_start`. * * @returns Total number of rounds played. */ get
(): number { return this.getProp("DT_CSGameRules", "m_totalRoundsPlayed"); } /** * @returns 'first', 'second', 'halftime' or 'postgame' */ get phase(): string { const gamePhases: { [phase: number]: string } = { 2: "first", 3: "second", 4: "halftime", 5: "postgame" }; const phase = this.getProp("DT_CSGameRules", "m_gamePhase"); return gamePhases[phase]!; } }
roundsPlayed
identifier_name
gamerules.ts
import { CCSGameRulesProxy } from "../sendtabletypes";
/** * Represents the game rules. */ export class GameRules extends Networkable<CCSGameRulesProxy> { /** * @returns Is the game currently in 'warmup' mode? */ get isWarmup(): boolean { return this.getProp("DT_CSGameRules", "m_bWarmupPeriod"); } /** * @deprecated Use `GameRules#roundsPlayed` instead. */ get roundNumber(): number { return this.roundsPlayed; } /** * This value is incremented when the scores are updated at round end. * If you need to keep track of the current round number, store this value * at each `round_start`. * * @returns Total number of rounds played. */ get roundsPlayed(): number { return this.getProp("DT_CSGameRules", "m_totalRoundsPlayed"); } /** * @returns 'first', 'second', 'halftime' or 'postgame' */ get phase(): string { const gamePhases: { [phase: number]: string } = { 2: "first", 3: "second", 4: "halftime", 5: "postgame" }; const phase = this.getProp("DT_CSGameRules", "m_gamePhase"); return gamePhases[phase]!; } }
import { Networkable } from "./networkable";
random_line_split
gamerules.ts
import { CCSGameRulesProxy } from "../sendtabletypes"; import { Networkable } from "./networkable"; /** * Represents the game rules. */ export class GameRules extends Networkable<CCSGameRulesProxy> { /** * @returns Is the game currently in 'warmup' mode? */ get isWarmup(): boolean { return this.getProp("DT_CSGameRules", "m_bWarmupPeriod"); } /** * @deprecated Use `GameRules#roundsPlayed` instead. */ get roundNumber(): number { return this.roundsPlayed; } /** * This value is incremented when the scores are updated at round end. * If you need to keep track of the current round number, store this value * at each `round_start`. * * @returns Total number of rounds played. */ get roundsPlayed(): number { return this.getProp("DT_CSGameRules", "m_totalRoundsPlayed"); } /** * @returns 'first', 'second', 'halftime' or 'postgame' */ get phase(): string
}
{ const gamePhases: { [phase: number]: string } = { 2: "first", 3: "second", 4: "halftime", 5: "postgame" }; const phase = this.getProp("DT_CSGameRules", "m_gamePhase"); return gamePhases[phase]!; }
identifier_body
builder.rs
use crate::enums::{CapStyle, DashStyle, LineJoin}; use crate::factory::IFactory; use crate::stroke_style::StrokeStyle; use com_wrapper::ComWrapper; use dcommon::Error; use winapi::shared::winerror::SUCCEEDED; use winapi::um::d2d1::D2D1_STROKE_STYLE_PROPERTIES; pub struct StrokeStyleBuilder<'a> { factory: &'a dyn IFactory, start_cap: CapStyle, end_cap: CapStyle, dash_cap: CapStyle, line_join: LineJoin, miter_limit: f32, dash_style: DashStyle, dash_offset: f32, dashes: Option<&'a [f32]>, } impl<'a> StrokeStyleBuilder<'a> { pub fn new(factory: &'a dyn IFactory) -> Self { // default values taken from D2D1::StrokeStyleProperties in d2d1helper.h StrokeStyleBuilder { factory, start_cap: CapStyle::Flat, end_cap: CapStyle::Flat, dash_cap: CapStyle::Flat, line_join: LineJoin::Miter, miter_limit: 10.0, dash_style: DashStyle::Solid, dash_offset: 0.0, dashes: None, } } pub fn build(self) -> Result<StrokeStyle, Error> { unsafe { let properties = self.to_d2d1(); let (dashes, dash_count) = self .dashes .map(|d| (d.as_ptr(), d.len() as u32)) .unwrap_or((std::ptr::null(), 0)); let mut ptr = std::ptr::null_mut(); let hr = self.factory .raw_f() .CreateStrokeStyle(&properties, dashes, dash_count, &mut ptr); if SUCCEEDED(hr)
else { Err(hr.into()) } } } pub fn with_start_cap(mut self, start_cap: CapStyle) -> Self { self.start_cap = start_cap; self } pub fn with_end_cap(mut self, end_cap: CapStyle) -> Self { self.end_cap = end_cap; self } pub fn with_dash_cap(mut self, dash_cap: CapStyle) -> Self { self.dash_cap = dash_cap; self } pub fn with_line_join(mut self, line_join: LineJoin) -> Self { self.line_join = line_join; self } pub fn with_miter_limit(mut self, miter_limit: f32) -> Self { self.miter_limit = miter_limit; self } pub fn with_dash_style(mut self, dash_style: DashStyle) -> Self { self.dash_style = dash_style; self } pub fn with_dash_offset(mut self, dash_offset: f32) -> Self { self.dash_offset = dash_offset; self } pub fn with_dashes(mut self, dashes: &'a [f32]) -> Self { self.dash_style = DashStyle::Custom; self.dashes = Some(dashes); self } fn to_d2d1(&self) -> D2D1_STROKE_STYLE_PROPERTIES { D2D1_STROKE_STYLE_PROPERTIES { startCap: self.start_cap as u32, endCap: self.end_cap as u32, dashCap: self.dash_cap as u32, lineJoin: self.line_join as u32, miterLimit: self.miter_limit, dashStyle: self.dash_style as u32, dashOffset: self.dash_offset, } } }
{ Ok(StrokeStyle::from_raw(ptr)) }
conditional_block
builder.rs
use crate::enums::{CapStyle, DashStyle, LineJoin}; use crate::factory::IFactory; use crate::stroke_style::StrokeStyle; use com_wrapper::ComWrapper; use dcommon::Error; use winapi::shared::winerror::SUCCEEDED; use winapi::um::d2d1::D2D1_STROKE_STYLE_PROPERTIES; pub struct StrokeStyleBuilder<'a> { factory: &'a dyn IFactory, start_cap: CapStyle, end_cap: CapStyle, dash_cap: CapStyle, line_join: LineJoin, miter_limit: f32, dash_style: DashStyle, dash_offset: f32, dashes: Option<&'a [f32]>, } impl<'a> StrokeStyleBuilder<'a> { pub fn new(factory: &'a dyn IFactory) -> Self { // default values taken from D2D1::StrokeStyleProperties in d2d1helper.h StrokeStyleBuilder { factory, start_cap: CapStyle::Flat, end_cap: CapStyle::Flat, dash_cap: CapStyle::Flat, line_join: LineJoin::Miter, miter_limit: 10.0, dash_style: DashStyle::Solid, dash_offset: 0.0, dashes: None, } } pub fn build(self) -> Result<StrokeStyle, Error> { unsafe { let properties = self.to_d2d1(); let (dashes, dash_count) = self .dashes .map(|d| (d.as_ptr(), d.len() as u32)) .unwrap_or((std::ptr::null(), 0)); let mut ptr = std::ptr::null_mut(); let hr = self.factory .raw_f() .CreateStrokeStyle(&properties, dashes, dash_count, &mut ptr); if SUCCEEDED(hr) { Ok(StrokeStyle::from_raw(ptr)) } else { Err(hr.into()) } } } pub fn with_start_cap(mut self, start_cap: CapStyle) -> Self { self.start_cap = start_cap; self }
} pub fn with_dash_cap(mut self, dash_cap: CapStyle) -> Self { self.dash_cap = dash_cap; self } pub fn with_line_join(mut self, line_join: LineJoin) -> Self { self.line_join = line_join; self } pub fn with_miter_limit(mut self, miter_limit: f32) -> Self { self.miter_limit = miter_limit; self } pub fn with_dash_style(mut self, dash_style: DashStyle) -> Self { self.dash_style = dash_style; self } pub fn with_dash_offset(mut self, dash_offset: f32) -> Self { self.dash_offset = dash_offset; self } pub fn with_dashes(mut self, dashes: &'a [f32]) -> Self { self.dash_style = DashStyle::Custom; self.dashes = Some(dashes); self } fn to_d2d1(&self) -> D2D1_STROKE_STYLE_PROPERTIES { D2D1_STROKE_STYLE_PROPERTIES { startCap: self.start_cap as u32, endCap: self.end_cap as u32, dashCap: self.dash_cap as u32, lineJoin: self.line_join as u32, miterLimit: self.miter_limit, dashStyle: self.dash_style as u32, dashOffset: self.dash_offset, } } }
pub fn with_end_cap(mut self, end_cap: CapStyle) -> Self { self.end_cap = end_cap; self
random_line_split
builder.rs
use crate::enums::{CapStyle, DashStyle, LineJoin}; use crate::factory::IFactory; use crate::stroke_style::StrokeStyle; use com_wrapper::ComWrapper; use dcommon::Error; use winapi::shared::winerror::SUCCEEDED; use winapi::um::d2d1::D2D1_STROKE_STYLE_PROPERTIES; pub struct StrokeStyleBuilder<'a> { factory: &'a dyn IFactory, start_cap: CapStyle, end_cap: CapStyle, dash_cap: CapStyle, line_join: LineJoin, miter_limit: f32, dash_style: DashStyle, dash_offset: f32, dashes: Option<&'a [f32]>, } impl<'a> StrokeStyleBuilder<'a> { pub fn new(factory: &'a dyn IFactory) -> Self { // default values taken from D2D1::StrokeStyleProperties in d2d1helper.h StrokeStyleBuilder { factory, start_cap: CapStyle::Flat, end_cap: CapStyle::Flat, dash_cap: CapStyle::Flat, line_join: LineJoin::Miter, miter_limit: 10.0, dash_style: DashStyle::Solid, dash_offset: 0.0, dashes: None, } } pub fn build(self) -> Result<StrokeStyle, Error> { unsafe { let properties = self.to_d2d1(); let (dashes, dash_count) = self .dashes .map(|d| (d.as_ptr(), d.len() as u32)) .unwrap_or((std::ptr::null(), 0)); let mut ptr = std::ptr::null_mut(); let hr = self.factory .raw_f() .CreateStrokeStyle(&properties, dashes, dash_count, &mut ptr); if SUCCEEDED(hr) { Ok(StrokeStyle::from_raw(ptr)) } else { Err(hr.into()) } } } pub fn with_start_cap(mut self, start_cap: CapStyle) -> Self
pub fn with_end_cap(mut self, end_cap: CapStyle) -> Self { self.end_cap = end_cap; self } pub fn with_dash_cap(mut self, dash_cap: CapStyle) -> Self { self.dash_cap = dash_cap; self } pub fn with_line_join(mut self, line_join: LineJoin) -> Self { self.line_join = line_join; self } pub fn with_miter_limit(mut self, miter_limit: f32) -> Self { self.miter_limit = miter_limit; self } pub fn with_dash_style(mut self, dash_style: DashStyle) -> Self { self.dash_style = dash_style; self } pub fn with_dash_offset(mut self, dash_offset: f32) -> Self { self.dash_offset = dash_offset; self } pub fn with_dashes(mut self, dashes: &'a [f32]) -> Self { self.dash_style = DashStyle::Custom; self.dashes = Some(dashes); self } fn to_d2d1(&self) -> D2D1_STROKE_STYLE_PROPERTIES { D2D1_STROKE_STYLE_PROPERTIES { startCap: self.start_cap as u32, endCap: self.end_cap as u32, dashCap: self.dash_cap as u32, lineJoin: self.line_join as u32, miterLimit: self.miter_limit, dashStyle: self.dash_style as u32, dashOffset: self.dash_offset, } } }
{ self.start_cap = start_cap; self }
identifier_body
builder.rs
use crate::enums::{CapStyle, DashStyle, LineJoin}; use crate::factory::IFactory; use crate::stroke_style::StrokeStyle; use com_wrapper::ComWrapper; use dcommon::Error; use winapi::shared::winerror::SUCCEEDED; use winapi::um::d2d1::D2D1_STROKE_STYLE_PROPERTIES; pub struct StrokeStyleBuilder<'a> { factory: &'a dyn IFactory, start_cap: CapStyle, end_cap: CapStyle, dash_cap: CapStyle, line_join: LineJoin, miter_limit: f32, dash_style: DashStyle, dash_offset: f32, dashes: Option<&'a [f32]>, } impl<'a> StrokeStyleBuilder<'a> { pub fn new(factory: &'a dyn IFactory) -> Self { // default values taken from D2D1::StrokeStyleProperties in d2d1helper.h StrokeStyleBuilder { factory, start_cap: CapStyle::Flat, end_cap: CapStyle::Flat, dash_cap: CapStyle::Flat, line_join: LineJoin::Miter, miter_limit: 10.0, dash_style: DashStyle::Solid, dash_offset: 0.0, dashes: None, } } pub fn build(self) -> Result<StrokeStyle, Error> { unsafe { let properties = self.to_d2d1(); let (dashes, dash_count) = self .dashes .map(|d| (d.as_ptr(), d.len() as u32)) .unwrap_or((std::ptr::null(), 0)); let mut ptr = std::ptr::null_mut(); let hr = self.factory .raw_f() .CreateStrokeStyle(&properties, dashes, dash_count, &mut ptr); if SUCCEEDED(hr) { Ok(StrokeStyle::from_raw(ptr)) } else { Err(hr.into()) } } } pub fn with_start_cap(mut self, start_cap: CapStyle) -> Self { self.start_cap = start_cap; self } pub fn with_end_cap(mut self, end_cap: CapStyle) -> Self { self.end_cap = end_cap; self } pub fn with_dash_cap(mut self, dash_cap: CapStyle) -> Self { self.dash_cap = dash_cap; self } pub fn with_line_join(mut self, line_join: LineJoin) -> Self { self.line_join = line_join; self } pub fn with_miter_limit(mut self, miter_limit: f32) -> Self { self.miter_limit = miter_limit; self } pub fn with_dash_style(mut self, dash_style: DashStyle) -> Self { self.dash_style = dash_style; self } pub fn with_dash_offset(mut self, dash_offset: f32) -> Self { self.dash_offset = dash_offset; self } pub fn
(mut self, dashes: &'a [f32]) -> Self { self.dash_style = DashStyle::Custom; self.dashes = Some(dashes); self } fn to_d2d1(&self) -> D2D1_STROKE_STYLE_PROPERTIES { D2D1_STROKE_STYLE_PROPERTIES { startCap: self.start_cap as u32, endCap: self.end_cap as u32, dashCap: self.dash_cap as u32, lineJoin: self.line_join as u32, miterLimit: self.miter_limit, dashStyle: self.dash_style as u32, dashOffset: self.dash_offset, } } }
with_dashes
identifier_name
edp_engine.py
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from sahara.service.edp import base_engine from sahara.utils import edp class FakeJobEngine(base_engine.JobEngine): def cancel_job(self, job_execution): pass def get_job_status(self, job_execution): pass def run_job(self, job_execution): return 'engine_job_id', edp.JOB_STATUS_SUCCEEDED, None def run_scheduled_job(self, job_execution): pass def
(self, cluster, job, data): pass @staticmethod def get_possible_job_config(job_type): return None @staticmethod def get_supported_job_types(): return edp.JOB_TYPES_ALL
validate_job_execution
identifier_name
edp_engine.py
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from sahara.service.edp import base_engine from sahara.utils import edp class FakeJobEngine(base_engine.JobEngine): def cancel_job(self, job_execution): pass def get_job_status(self, job_execution): pass def run_job(self, job_execution): return 'engine_job_id', edp.JOB_STATUS_SUCCEEDED, None def run_scheduled_job(self, job_execution): pass def validate_job_execution(self, cluster, job, data): pass @staticmethod def get_possible_job_config(job_type): return None @staticmethod def get_supported_job_types():
return edp.JOB_TYPES_ALL
identifier_body
edp_engine.py
# Copyright (c) 2014 Mirantis Inc.
# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from sahara.service.edp import base_engine from sahara.utils import edp class FakeJobEngine(base_engine.JobEngine): def cancel_job(self, job_execution): pass def get_job_status(self, job_execution): pass def run_job(self, job_execution): return 'engine_job_id', edp.JOB_STATUS_SUCCEEDED, None def run_scheduled_job(self, job_execution): pass def validate_job_execution(self, cluster, job, data): pass @staticmethod def get_possible_job_config(job_type): return None @staticmethod def get_supported_job_types(): return edp.JOB_TYPES_ALL
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License.
random_line_split
utils.js
var utils = module.exports = require('../shared/utils'); var fs = require('fs'); var http = require('http'); var path = require('path'); var tty = require('tty'); var bones = require('..'); var colors = { 'default': 1, black: 30, red: 31, green: 32, yellow: 33, blue: 34, purple: 35, cyan: 36, white: 37 }; var styles = { regular: 0, bold: 1, underline: 4 }; if (tty.isatty(process.stdout.fd) && tty.isatty(process.stderr.fd)) { utils.colorize = function(text, color, style) { color = color || 'red'; style = style || 'regular'; return "\033[" + styles[style] + ";" + colors[color] + "m" + text + "\033[0m"; }; } else { utils.colorize = function(text) { return text; }; } // Load client-side wrappers var wrappers = {}; var wrapperDir = path.join(__dirname, '../client'); fs.readdirSync(wrapperDir).forEach(function(name) { var match = name.match(/^(.+)\.(prefix|suffix)\.js$/); if (match) { wrappers[match[1]] = wrappers[match[1]] || {}; wrappers[match[1]][match[2]] = fs.readFileSync(path.join(wrapperDir, name), 'utf8'); } }); // Remove common prefix between the working directory and filename so that we don't // leak information about the directory structure. utils.removePrefix = function(str) { var prefix = process.cwd().split('/'); str = str.split('/'); while (prefix.length && str[0] === prefix[0]) { str.shift(); prefix.shift(); } return str.join('/'); }; utils.wrapClientFile = function(content, filename) { var kind = utils.singularize(path.basename(path.dirname(filename))); var name = path.basename(filename).replace(/\..+$/, ''); var file = utils.removePrefix(filename); wrappers[kind] = wrappers[kind] || {}; wrappers[kind].prefix = wrappers[kind].prefix || ''; wrappers[kind].suffix = wrappers[kind].suffix || ''; return wrappers[kind].prefix.replace(/__NAME__/g, name).replace(/__FILE__/g, file) + "\n" + content + "\n" + wrappers[kind].suffix.replace(/__NAME__/g, name).replace(/__FILE__/g, file); }; utils.sortByLoadOrder = function(assets) { var reference = bones.plugin.order; assets.sort(function loadOrderSort(a, b) { a = reference.indexOf(a); b = reference.indexOf(b); return (a < 0 || b < 0) ? b - a : a - b; }); }; Error.HTTP = function(message, status) { if (typeof message === 'number') { status = message; message = null; } if (!message)
Error.call(this, message); Error.captureStackTrace(this, arguments.callee); this.message = message; this.status = status; }; Error.HTTP.prototype.__proto__ = Error.prototype;
{ message = http.STATUS_CODES[status] || 'Unknown'; }
conditional_block
utils.js
var utils = module.exports = require('../shared/utils'); var fs = require('fs'); var http = require('http'); var path = require('path'); var tty = require('tty'); var bones = require('..'); var colors = { 'default': 1, black: 30, red: 31, green: 32, yellow: 33, blue: 34, purple: 35, cyan: 36, white: 37
regular: 0, bold: 1, underline: 4 }; if (tty.isatty(process.stdout.fd) && tty.isatty(process.stderr.fd)) { utils.colorize = function(text, color, style) { color = color || 'red'; style = style || 'regular'; return "\033[" + styles[style] + ";" + colors[color] + "m" + text + "\033[0m"; }; } else { utils.colorize = function(text) { return text; }; } // Load client-side wrappers var wrappers = {}; var wrapperDir = path.join(__dirname, '../client'); fs.readdirSync(wrapperDir).forEach(function(name) { var match = name.match(/^(.+)\.(prefix|suffix)\.js$/); if (match) { wrappers[match[1]] = wrappers[match[1]] || {}; wrappers[match[1]][match[2]] = fs.readFileSync(path.join(wrapperDir, name), 'utf8'); } }); // Remove common prefix between the working directory and filename so that we don't // leak information about the directory structure. utils.removePrefix = function(str) { var prefix = process.cwd().split('/'); str = str.split('/'); while (prefix.length && str[0] === prefix[0]) { str.shift(); prefix.shift(); } return str.join('/'); }; utils.wrapClientFile = function(content, filename) { var kind = utils.singularize(path.basename(path.dirname(filename))); var name = path.basename(filename).replace(/\..+$/, ''); var file = utils.removePrefix(filename); wrappers[kind] = wrappers[kind] || {}; wrappers[kind].prefix = wrappers[kind].prefix || ''; wrappers[kind].suffix = wrappers[kind].suffix || ''; return wrappers[kind].prefix.replace(/__NAME__/g, name).replace(/__FILE__/g, file) + "\n" + content + "\n" + wrappers[kind].suffix.replace(/__NAME__/g, name).replace(/__FILE__/g, file); }; utils.sortByLoadOrder = function(assets) { var reference = bones.plugin.order; assets.sort(function loadOrderSort(a, b) { a = reference.indexOf(a); b = reference.indexOf(b); return (a < 0 || b < 0) ? b - a : a - b; }); }; Error.HTTP = function(message, status) { if (typeof message === 'number') { status = message; message = null; } if (!message) { message = http.STATUS_CODES[status] || 'Unknown'; } Error.call(this, message); Error.captureStackTrace(this, arguments.callee); this.message = message; this.status = status; }; Error.HTTP.prototype.__proto__ = Error.prototype;
}; var styles = {
random_line_split
bc_gen_feature_rep_xls.py
#!/usr/bin/env python # # Generate report in Excel format (from xml input) # import sys,os,shelve import re,dfxml,fiwalk from bc_utils import filename_from_path from openpyxl.workbook import Workbook from openpyxl.writer.excel import ExcelWriter from openpyxl.cell import get_column_letter def bc_generate_feature_xlsx(PdfReport, data, feature_file):
wb = Workbook() dest_filename = PdfReport.featuredir +'/'+ (filename_from_path(feature_file))[10:-3] + "xlsx" row_idx = [2] ws = wb.worksheets[0] ws.title = "File Feature Information" ws.cell('%s%s'%('A', '1')).value = '%s' % "Filename" ws.cell('%s%s'%('B', '1')).value = '%s' % "Position" ws.cell('%s%s'%('C', '1')).value = '%s' % "Feature" linenum=0 for row in data: # Skip the lines with known text lines to be eliminated if (re.match("Total features",str(row))): continue filename = "Unknown" feature = "Unknown" position = "Unknown" # Some lines in the annotated_xxx.txt have less than three # columns where filename or feature may be missing. if len(row) > 3: filename = row[3] else: filename = "Unknown" if len(row) > 1: feature = row[1] else: feature = "Unknown" position = row[0] # If it is a special file, check if the user wants it to # be repoted. If not, exclude this from the table. if (PdfReport.bc_config_report_special_files == False) and \ (is_special_file(filename)): ## print("D: File %s is special. So skipping" %(filename)) continue ws.cell('%s%s'%('A', row_idx[0])).value = '%s' % filename ws.cell('%s%s'%('B', row_idx[0])).value = '%s' % feature ws.cell('%s%s'%('C', row_idx[0])).value = '%s' % position row_idx[0] += 1 wb.save(filename=dest_filename)
identifier_body
bc_gen_feature_rep_xls.py
#!/usr/bin/env python # # Generate report in Excel format (from xml input) # import sys,os,shelve import re,dfxml,fiwalk from bc_utils import filename_from_path from openpyxl.workbook import Workbook from openpyxl.writer.excel import ExcelWriter from openpyxl.cell import get_column_letter def
(PdfReport, data, feature_file): wb = Workbook() dest_filename = PdfReport.featuredir +'/'+ (filename_from_path(feature_file))[10:-3] + "xlsx" row_idx = [2] ws = wb.worksheets[0] ws.title = "File Feature Information" ws.cell('%s%s'%('A', '1')).value = '%s' % "Filename" ws.cell('%s%s'%('B', '1')).value = '%s' % "Position" ws.cell('%s%s'%('C', '1')).value = '%s' % "Feature" linenum=0 for row in data: # Skip the lines with known text lines to be eliminated if (re.match("Total features",str(row))): continue filename = "Unknown" feature = "Unknown" position = "Unknown" # Some lines in the annotated_xxx.txt have less than three # columns where filename or feature may be missing. if len(row) > 3: filename = row[3] else: filename = "Unknown" if len(row) > 1: feature = row[1] else: feature = "Unknown" position = row[0] # If it is a special file, check if the user wants it to # be repoted. If not, exclude this from the table. if (PdfReport.bc_config_report_special_files == False) and \ (is_special_file(filename)): ## print("D: File %s is special. So skipping" %(filename)) continue ws.cell('%s%s'%('A', row_idx[0])).value = '%s' % filename ws.cell('%s%s'%('B', row_idx[0])).value = '%s' % feature ws.cell('%s%s'%('C', row_idx[0])).value = '%s' % position row_idx[0] += 1 wb.save(filename=dest_filename)
bc_generate_feature_xlsx
identifier_name
bc_gen_feature_rep_xls.py
#!/usr/bin/env python # # Generate report in Excel format (from xml input) # import sys,os,shelve import re,dfxml,fiwalk from bc_utils import filename_from_path from openpyxl.workbook import Workbook from openpyxl.writer.excel import ExcelWriter from openpyxl.cell import get_column_letter def bc_generate_feature_xlsx(PdfReport, data, feature_file): wb = Workbook() dest_filename = PdfReport.featuredir +'/'+ (filename_from_path(feature_file))[10:-3] + "xlsx" row_idx = [2] ws = wb.worksheets[0] ws.title = "File Feature Information" ws.cell('%s%s'%('A', '1')).value = '%s' % "Filename" ws.cell('%s%s'%('B', '1')).value = '%s' % "Position" ws.cell('%s%s'%('C', '1')).value = '%s' % "Feature" linenum=0 for row in data: # Skip the lines with known text lines to be eliminated if (re.match("Total features",str(row))): continue filename = "Unknown" feature = "Unknown" position = "Unknown" # Some lines in the annotated_xxx.txt have less than three # columns where filename or feature may be missing. if len(row) > 3: filename = row[3] else:
if len(row) > 1: feature = row[1] else: feature = "Unknown" position = row[0] # If it is a special file, check if the user wants it to # be repoted. If not, exclude this from the table. if (PdfReport.bc_config_report_special_files == False) and \ (is_special_file(filename)): ## print("D: File %s is special. So skipping" %(filename)) continue ws.cell('%s%s'%('A', row_idx[0])).value = '%s' % filename ws.cell('%s%s'%('B', row_idx[0])).value = '%s' % feature ws.cell('%s%s'%('C', row_idx[0])).value = '%s' % position row_idx[0] += 1 wb.save(filename=dest_filename)
filename = "Unknown"
random_line_split
bc_gen_feature_rep_xls.py
#!/usr/bin/env python # # Generate report in Excel format (from xml input) # import sys,os,shelve import re,dfxml,fiwalk from bc_utils import filename_from_path from openpyxl.workbook import Workbook from openpyxl.writer.excel import ExcelWriter from openpyxl.cell import get_column_letter def bc_generate_feature_xlsx(PdfReport, data, feature_file): wb = Workbook() dest_filename = PdfReport.featuredir +'/'+ (filename_from_path(feature_file))[10:-3] + "xlsx" row_idx = [2] ws = wb.worksheets[0] ws.title = "File Feature Information" ws.cell('%s%s'%('A', '1')).value = '%s' % "Filename" ws.cell('%s%s'%('B', '1')).value = '%s' % "Position" ws.cell('%s%s'%('C', '1')).value = '%s' % "Feature" linenum=0 for row in data: # Skip the lines with known text lines to be eliminated if (re.match("Total features",str(row))): continue filename = "Unknown" feature = "Unknown" position = "Unknown" # Some lines in the annotated_xxx.txt have less than three # columns where filename or feature may be missing. if len(row) > 3:
else: filename = "Unknown" if len(row) > 1: feature = row[1] else: feature = "Unknown" position = row[0] # If it is a special file, check if the user wants it to # be repoted. If not, exclude this from the table. if (PdfReport.bc_config_report_special_files == False) and \ (is_special_file(filename)): ## print("D: File %s is special. So skipping" %(filename)) continue ws.cell('%s%s'%('A', row_idx[0])).value = '%s' % filename ws.cell('%s%s'%('B', row_idx[0])).value = '%s' % feature ws.cell('%s%s'%('C', row_idx[0])).value = '%s' % position row_idx[0] += 1 wb.save(filename=dest_filename)
filename = row[3]
conditional_block
第四集.py
#第四集(包含部分文件3.py和部分第二集) # courses=['History','Math','Physics','Compsci']#此行代码在Mutable之前都要打开 # print(courses) # courses.append('Art')#在最后添加一个元素 # courses.insert(0,'English')#在0的位置添加一个元素 # courses_2=['Chinese','Education'] # courses.insert(1,courses_2)#看看这条代码与下面两条代码有什么不同 # courses.append(courses_2) # courses.extend(courses_2) # #用pop删除和用remove删除可以详见3.py # # courses.remove('Math')#删除一个元素 # popped=courses.pop()#删除一个元素并将该元素赋值给popped (括号内无数字则默认最后一个) # print(popped)#输出被删除的元素 # courses.reverse()#将元素倒叙 # courses.sort()#排序 按开头字母的顺序 数字排在字母前 # print(courses) # courses.sort(reverse=True)#按顺序倒叙(若=False则无效) # print(courses) # sorted_courses=sorted(courses) # print(sorted_courses) # alphabet=['DA1','SA2','AD3','3AD'] # alphabet.sort() # print(alphabet)
# print(min(nums))#输出最小数 # print(max(nums))#输出最大数 # print(sum(nums))#输出总和 # #中文不知道是什么规则 # Chinese=['啊了','吧即','啦'] # Chinese.sort() # print(Chinese) # print(courses.index('Math'))#查找某元素在列表中的位置 # print('Art' in courses)#True则表示该元素存在于列表,False则是不存在 #for和in语言 # for item in courses: #将courses中的元素一个一个输出 # print(item) # #输出元素位置和元素 # for course in enumerate(courses): # print(course) # for index,course in enumerate(courses): # print(index,course) # for index,course in enumerate(courses,start=1): # print(index,course) # courses_str=' - '.join(courses)#将' - '插入courses中输出 # new_list=courses_str.split(' - ')#将' - '从courses_str中删除 # print(courses_str) # print(new_list) # #Mutable (可变的) # list_1=['History','Math','Physics','Compsci'] # list_2=list_1 # print(list_1) # print(list_2) # list_1[0]='Art' # print(list_1) # print(list_2) # #Immutable (不可变的)(这里很神奇,视频上不可以但是我可以) # tuple_1=['History','Math','Physics','Compsci'] # tuple_2=tuple_1 # print(tuple_1) # print(tuple_2) # tuple_1[0]='Art' # print(tuple_1) # print(tuple_2) # #Sets # cs_courses={'History', 'Math', 'Physics', 'Compsci','Math'}#用大括号则会将两个相同的元素只输出前一个 # art_courses={'History', 'Math', 'Art', 'Design'} # print(cs_courses) # print(cs_courses.intersection(art_courses))#输出两个列表中相同的元素 # print(cs_courses.difference(art_courses))#输出两个列表中不相同的元素 # print(cs_courses.union(art_courses))#将两个列表合并(每次运行顺序都不同) #Empty Lists empty_list=[] empty_list=list() #Empty Tuples empty_tuple=() empty_tuple=tuple() #Empty Sets empty_set={} #错误的 empty_set=set()
# nums=[3,5,1,4,2] # nums.sort() # print(nums)
random_line_split
defs.rs
/* * Copyright (C) 2017 AltOS-Rust Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or
* GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ pub const GROUPA_ADDR: *const u32 = 0x4800_0000 as *const _; pub const GROUPB_ADDR: *const u32 = 0x4800_0400 as *const _; pub const GROUPC_ADDR: *const u32 = 0x4800_0800 as *const _; pub const GROUPF_ADDR: *const u32 = 0x4800_1400 as *const _; pub const OTYPER_OFFSET: u32 = 0x04; pub const TYPE_PUSHPULL: u32 = 0b0; pub const TYPE_OPENDRAIN: u32 = 0b1; pub const OSPEEDR_OFFSET: u32 = 0x08; pub const SPEED_MASK: u32 = 0b11; pub const SPEED_LOW: u32 = 0b00; pub const SPEED_LOW_ALT: u32 = 0b10; pub const SPEED_MEDIUM: u32 = 0b01; pub const SPEED_HIGH: u32 = 0b11; pub const PUPDR_OFFSET: u32 = 0x0C; pub const PUPD_MASK: u32 = 0b11; pub const PUPD_NEITHER: u32 = 0b00; pub const PUPD_UP: u32 = 0b01; pub const PUPD_DOWN: u32 = 0b10; pub const BSRR_OFFSET: u32 = 0x18; pub const BSRR_RESET_OFFSET: u8 = 16; pub const AFRL_OFFSET: u32 = 0x20; pub const AFR_MASK: u32 = 0b1111; pub const AF0: u32 = 0b0000; pub const AF1: u32 = 0b0001; pub const AF2: u32 = 0b0010; pub const AF3: u32 = 0b0011; pub const AF4: u32 = 0b0100; pub const AF5: u32 = 0b0101; pub const AF6: u32 = 0b0110; pub const AF7: u32 = 0b0111; pub const AFRH_OFFSET: u32 = 0x24; pub const MODER_OFFSET: u32 = 0x00; pub const MODE_MASK: u32 = 0b11; pub const MODE_INPUT: u32 = 0b00; pub const MODE_OUTPUT: u32 = 0b01; pub const MODE_ALTERNATE: u32 = 0b10; pub const MODE_ANALOG: u32 = 0b11;
* (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
random_line_split
demo-dacsinewave.py
#!/usr/bin/python from ABE_ADCDACPi import ADCDACPi import time import math """ ================================================ ABElectronics ADCDAC Pi 2-Channel ADC, 2-Channel DAC | DAC sine wave generator demo Version 1.0 Created 17/05/2014 Version 1.1 16/11/2014 updated code and functions to PEP8 format run with: python demo-dacsinewave.py ================================================ # this demo uses the set_dac_raw method to generate a sine wave from a # predefined set of values """ adcdac = ADCDACPi(1) # create an instance of the ADCDAC Pi with a DAC gain set to 1 DACLookup_FullSine_12Bit = \ [2048, 2073, 2098, 2123, 2148, 2174, 2199, 2224, 2249, 2274, 2299, 2324, 2349, 2373, 2398, 2423, 2448, 2472, 2497, 2521, 2546, 2570, 2594, 2618, 2643, 2667, 2690, 2714, 2738, 2762, 2785, 2808, 2832, 2855, 2878, 2901, 2924, 2946, 2969, 2991, 3013, 3036, 3057, 3079, 3101, 3122, 3144, 3165, 3186, 3207, 3227, 3248, 3268, 3288, 3308, 3328, 3347, 3367, 3386, 3405, 3423, 3442, 3460, 3478, 3496, 3514, 3531, 3548, 3565, 3582, 3599, 3615, 3631, 3647, 3663, 3678, 3693, 3708, 3722, 3737, 3751, 3765, 3778, 3792, 3805, 3817, 3830, 3842, 3854, 3866, 3877, 3888, 3899, 3910, 3920, 3930, 3940, 3950, 3959, 3968, 3976, 3985, 3993, 4000, 4008, 4015, 4022, 4028, 4035, 4041, 4046, 4052, 4057, 4061, 4066, 4070, 4074, 4077, 4081, 4084, 4086, 4088, 4090, 4092, 4094, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4094, 4092, 4090, 4088, 4086, 4084, 4081, 4077, 4074, 4070, 4066, 4061, 4057, 4052, 4046, 4041, 4035, 4028, 4022, 4015, 4008, 4000, 3993, 3985, 3976, 3968, 3959, 3950, 3940, 3930, 3920, 3910, 3899, 3888, 3877, 3866, 3854, 3842, 3830, 3817, 3805, 3792, 3778, 3765, 3751, 3737, 3722, 3708, 3693, 3678, 3663, 3647, 3631, 3615, 3599, 3582, 3565, 3548, 3531, 3514, 3496, 3478, 3460, 3442, 3423, 3405, 3386, 3367, 3347, 3328, 3308, 3288, 3268, 3248, 3227, 3207, 3186, 3165, 3144, 3122, 3101, 3079, 3057, 3036, 3013, 2991, 2969, 2946, 2924, 2901, 2878, 2855, 2832, 2808, 2785, 2762, 2738, 2714, 2690, 2667, 2643, 2618, 2594, 2570, 2546, 2521, 2497, 2472, 2448, 2423, 2398, 2373, 2349, 2324, 2299, 2274, 2249, 2224, 2199, 2174, 2148, 2123, 2098, 2073, 2048, 2023, 1998, 1973, 1948, 1922, 1897, 1872, 1847, 1822, 1797, 1772, 1747, 1723, 1698, 1673, 1648, 1624, 1599, 1575, 1550, 1526, 1502, 1478, 1453, 1429, 1406, 1382, 1358, 1334, 1311, 1288, 1264, 1241, 1218, 1195, 1172, 1150, 1127, 1105, 1083, 1060, 1039, 1017, 995, 974, 952, 931, 910, 889, 869, 848, 828, 808, 788, 768, 749, 729, 710, 691, 673, 654, 636, 618, 600, 582, 565, 548, 531, 514, 497, 481, 465, 449, 433, 418, 403, 388, 374, 359, 345, 331, 318, 304, 291, 279, 266, 254, 242, 230, 219, 208, 197, 186, 176, 166, 156, 146, 137, 128, 120, 111, 103, 96, 88, 81, 74, 68, 61, 55, 50, 44, 39, 35, 30, 26, 22, 19, 15, 12, 10, 8, 6, 4, 2, 1, 1, 0, 0, 0, 1, 1, 2, 4, 6, 8, 10, 12, 15, 19, 22, 26, 30, 35, 39, 44, 50, 55, 61, 68, 74, 81, 88, 96, 103, 111, 120, 128, 137, 146, 156, 166, 176, 186, 197, 208, 219, 230, 242, 254, 266, 279, 291, 304, 318, 331, 345, 359, 374, 388, 403, 418, 433, 449, 465, 481, 497, 514, 531, 548, 565, 582, 600, 618, 636, 654, 673, 691, 710, 729, 749, 768, 788, 808, 828, 848, 869, 889, 910, 931, 952, 974, 995, 1017, 1039, 1060, 1083, 1105, 1127, 1150, 1172, 1195, 1218, 1241, 1264, 1288, 1311, 1334, 1358, 1382, 1406, 1429, 1453, 1478, 1502, 1526, 1550, 1575, 1599, 1624, 1648, 1673, 1698, 1723, 1747, 1772, 1797, 1822, 1847, 1872, 1897, 1922, 1948, 1973, 1998, 2023] while True:
for val in DACLookup_FullSine_12Bit: adcdac.set_dac_raw(1, val)
conditional_block
demo-dacsinewave.py
#!/usr/bin/python from ABE_ADCDACPi import ADCDACPi import time import math """ ================================================ ABElectronics ADCDAC Pi 2-Channel ADC, 2-Channel DAC | DAC sine wave generator demo Version 1.0 Created 17/05/2014 Version 1.1 16/11/2014 updated code and functions to PEP8 format run with: python demo-dacsinewave.py ================================================ # this demo uses the set_dac_raw method to generate a sine wave from a # predefined set of values """ adcdac = ADCDACPi(1) # create an instance of the ADCDAC Pi with a DAC gain set to 1 DACLookup_FullSine_12Bit = \ [2048, 2073, 2098, 2123, 2148, 2174, 2199, 2224,
3186, 3207, 3227, 3248, 3268, 3288, 3308, 3328, 3347, 3367, 3386, 3405, 3423, 3442, 3460, 3478, 3496, 3514, 3531, 3548, 3565, 3582, 3599, 3615, 3631, 3647, 3663, 3678, 3693, 3708, 3722, 3737, 3751, 3765, 3778, 3792, 3805, 3817, 3830, 3842, 3854, 3866, 3877, 3888, 3899, 3910, 3920, 3930, 3940, 3950, 3959, 3968, 3976, 3985, 3993, 4000, 4008, 4015, 4022, 4028, 4035, 4041, 4046, 4052, 4057, 4061, 4066, 4070, 4074, 4077, 4081, 4084, 4086, 4088, 4090, 4092, 4094, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4094, 4092, 4090, 4088, 4086, 4084, 4081, 4077, 4074, 4070, 4066, 4061, 4057, 4052, 4046, 4041, 4035, 4028, 4022, 4015, 4008, 4000, 3993, 3985, 3976, 3968, 3959, 3950, 3940, 3930, 3920, 3910, 3899, 3888, 3877, 3866, 3854, 3842, 3830, 3817, 3805, 3792, 3778, 3765, 3751, 3737, 3722, 3708, 3693, 3678, 3663, 3647, 3631, 3615, 3599, 3582, 3565, 3548, 3531, 3514, 3496, 3478, 3460, 3442, 3423, 3405, 3386, 3367, 3347, 3328, 3308, 3288, 3268, 3248, 3227, 3207, 3186, 3165, 3144, 3122, 3101, 3079, 3057, 3036, 3013, 2991, 2969, 2946, 2924, 2901, 2878, 2855, 2832, 2808, 2785, 2762, 2738, 2714, 2690, 2667, 2643, 2618, 2594, 2570, 2546, 2521, 2497, 2472, 2448, 2423, 2398, 2373, 2349, 2324, 2299, 2274, 2249, 2224, 2199, 2174, 2148, 2123, 2098, 2073, 2048, 2023, 1998, 1973, 1948, 1922, 1897, 1872, 1847, 1822, 1797, 1772, 1747, 1723, 1698, 1673, 1648, 1624, 1599, 1575, 1550, 1526, 1502, 1478, 1453, 1429, 1406, 1382, 1358, 1334, 1311, 1288, 1264, 1241, 1218, 1195, 1172, 1150, 1127, 1105, 1083, 1060, 1039, 1017, 995, 974, 952, 931, 910, 889, 869, 848, 828, 808, 788, 768, 749, 729, 710, 691, 673, 654, 636, 618, 600, 582, 565, 548, 531, 514, 497, 481, 465, 449, 433, 418, 403, 388, 374, 359, 345, 331, 318, 304, 291, 279, 266, 254, 242, 230, 219, 208, 197, 186, 176, 166, 156, 146, 137, 128, 120, 111, 103, 96, 88, 81, 74, 68, 61, 55, 50, 44, 39, 35, 30, 26, 22, 19, 15, 12, 10, 8, 6, 4, 2, 1, 1, 0, 0, 0, 1, 1, 2, 4, 6, 8, 10, 12, 15, 19, 22, 26, 30, 35, 39, 44, 50, 55, 61, 68, 74, 81, 88, 96, 103, 111, 120, 128, 137, 146, 156, 166, 176, 186, 197, 208, 219, 230, 242, 254, 266, 279, 291, 304, 318, 331, 345, 359, 374, 388, 403, 418, 433, 449, 465, 481, 497, 514, 531, 548, 565, 582, 600, 618, 636, 654, 673, 691, 710, 729, 749, 768, 788, 808, 828, 848, 869, 889, 910, 931, 952, 974, 995, 1017, 1039, 1060, 1083, 1105, 1127, 1150, 1172, 1195, 1218, 1241, 1264, 1288, 1311, 1334, 1358, 1382, 1406, 1429, 1453, 1478, 1502, 1526, 1550, 1575, 1599, 1624, 1648, 1673, 1698, 1723, 1747, 1772, 1797, 1822, 1847, 1872, 1897, 1922, 1948, 1973, 1998, 2023] while True: for val in DACLookup_FullSine_12Bit: adcdac.set_dac_raw(1, val)
2249, 2274, 2299, 2324, 2349, 2373, 2398, 2423, 2448, 2472, 2497, 2521, 2546, 2570, 2594, 2618, 2643, 2667, 2690, 2714, 2738, 2762, 2785, 2808, 2832, 2855, 2878, 2901, 2924, 2946, 2969, 2991, 3013, 3036, 3057, 3079, 3101, 3122, 3144, 3165,
random_line_split
server.js
(function() { 'use strict'; var express = require('express'); var path = require('path');
var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.engine('html', require('ejs').renderFile); app.set('view engine', 'html'); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, '../client'))); app.use('/', routes); app.set('port', process.env.PORT || 3000); var server = app.listen(app.get('port'), function() { console.log('Express server listening on port ' + server.address().port); }); module.exports = app; }());
var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routes = require('./routes.js');
random_line_split
index.js
module.exports = { "methods": { "wiki": function(msg, sender, api) { var query = msg.match(/\".+\"/)[0]; query = query.substring(1, query.length-1); var base = "http://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&rawcontinue&redirects&titles="+encodeURIComponent(query); api.request(base, function(err, res, body) { var info = JSON.parse(body); var page; for (f in info.query.pages) { page = info.query.pages[f]; } if (page.missing === undefined) { var text; var testpos = 0; while (true)
text = text.replace(/<\/?[^>]+(>|$)/g, ""); if (text.indexOf("\n") > 0) text = text.substr(0, text.indexOf("\n")); else if (text.indexOf("\n") === 0) text = text.substr(1); if (text.length === text.lastIndexOf("may refer to:") + 13) { api.randomMessage("oddresult", {"query": query}); return; } api.say(text); } else { api.randomMessage("nodefs", {"query": query}); } }); } } }
{ var pos = page.extract.indexOf(".", testpos); if (pos === -1) { api.randomMessage("oddresult", {"query": query}); return; } text = page.extract.substr(0, pos+1); var bstart = text.lastIndexOf("<b>"); var bend = text.lastIndexOf("</b>"); if (bstart < bend || (bstart === -1 && bend === -1)) break; testpos = pos + 1; }
conditional_block
index.js
module.exports = { "methods": { "wiki": function(msg, sender, api) { var query = msg.match(/\".+\"/)[0]; query = query.substring(1, query.length-1); var base = "http://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&rawcontinue&redirects&titles="+encodeURIComponent(query); api.request(base, function(err, res, body) { var info = JSON.parse(body); var page; for (f in info.query.pages) { page = info.query.pages[f]; } if (page.missing === undefined) { var text; var testpos = 0; while (true) { var pos = page.extract.indexOf(".", testpos); if (pos === -1) { api.randomMessage("oddresult", {"query": query}); return; } text = page.extract.substr(0, pos+1); var bstart = text.lastIndexOf("<b>"); var bend = text.lastIndexOf("</b>"); if (bstart < bend || (bstart === -1 && bend === -1))
text = text.replace(/<\/?[^>]+(>|$)/g, ""); if (text.indexOf("\n") > 0) text = text.substr(0, text.indexOf("\n")); else if (text.indexOf("\n") === 0) text = text.substr(1); if (text.length === text.lastIndexOf("may refer to:") + 13) { api.randomMessage("oddresult", {"query": query}); return; } api.say(text); } else { api.randomMessage("nodefs", {"query": query}); } }); } } }
break; testpos = pos + 1; }
random_line_split
require.d.ts
// require-2.1.1.d.ts // (c) 2012 Josh Baldwin // require.d.ts may be freely distributed under the MIT license. // For all details and documentation: // https://github.com/jbaldwin/require.d.ts interface RequireShim { // List of dependencies. deps?: string[]; // Name the module will be exported as. exports?: string; // Initialize function with all dependcies passed in, // if the function returns a value then that value is used // as the module export value instead of the object // found via the 'exports' string. init?: (...dependencies: any[]) => any; } interface RequireConfig { // The root path to use for all module lookups. baseUrl?: string; // Path mappings for module names not found directly under // baseUrl. paths?: { [key: string]: string; }; // Dictionary of Shim's. // does not cover case of key->string[] shim?: { [key: string]: RequireShim; }; /** * For the given module prefix, instead of loading the * module with the given ID, substitude a different * module ID. * * @example * requirejs.config({ * map: { * 'some/newmodule': { * 'foo': 'foo1.2' * }, * 'some/oldmodule': { * 'foo': 'foo1.0' * } * } * }); **/ map?: { [id: string]: { [id: string]: string; }; }; // AMD configurations, use module.config() to access in // define() functions config?: { [id: string]: { }; }; // Configures loading modules from CommonJS packages. packages?: { }; // The number of seconds to wait before giving up on loading // a script. The default is 7 seconds. waitSeconds?: number; // A name to give to a loading context. This allows require.js // to load multiple versions of modules in a page, as long as // each top-level require call specifies a unique context string. context?: string; // An array of dependencies to load. deps?: string[]; // A function to pass to require that should be require after // deps have been loaded. callback?: (...modules: any[]) => void; // If set to true, an error will be thrown if a script loads // that does not call define() or have shim exports string // value that can be checked. enforceDefine?: bool; // If set to true, document.createElementNS() will be used // to create script elements. xhtml?: bool; /** * Extra query string arguments appended to URLs that RequireJS * uses to fetch resources. Most useful to cachce bust when * the browser or server is not configured correcty. * * @example * urlArgs: "bust= + (new Date()).getTime() **/ urlArgs?: string; /** * Specify the value for the type="" attribute used for script * tags inserted into the document by RequireJS. Default is * "text/javascript". To use Firefox's JavasScript 1.8 * features, use "text/javascript;version=1.8". **/ scriptType?: string; } // not sure what to do with this guy interface RequireModule { config(): { }; } interface RequireMap { prefix: string; name: string; parentMap: RequireMap; url: string; originalName: string; fullName: string; } interface Require { // Configure require.js config(config: RequireConfig): void; // Start the main app logic. // Callback is optional. // Can alternatively use deps and callback. (module: string): any; (modules: string[], ready?: (...modules: any[]) => void, errorCallback?: (err : RequireError) => void): void; // Generate URLs from require module toUrl(module: string): string;
// On Error override onError(): void; // Undefine a module undef(module: string): void; // Semi-private function, overload in special instance of undef() onResourceLoad(context: Object, map: RequireMap, depArray: RequireMap[]): void; } interface RequireError { requireType: string; requireModules: string[]; originalError?: string; contextName? : string; requireMap?: any; } interface RequireDefine { /** * Define Simple Name/Value Pairs * @config Dictionary of Named/Value pairs for the config. **/ (config: { [key: string]: any; }): void; /** * Define function. * @func: The function module. **/ (func: () => any): void; /** * Define function with dependencies. * @deps List of dependencies module IDs. * @ready Callback function when the dependencies are loaded. * @deps module dependencies * @return module definition **/ (deps: string[], ready: (...deps: any[]) => any): void; /** * Define module with simplified CommonJS wrapper. * @ready * @require requirejs instance * @exports exports object * @module module * @return module definition **/ (ready: (require: Require, exports: { [key: string]: any; }, module: RequireModule) => any): void; /** * Define a module with a name and dependencies. * @name The name of the module. * @deps List of dependencies module IDs. * @ready Callback function when the dependencies are loaded. * @deps module dependencies * @return module definition **/ (name: string, deps: string[], ready: (...deps: any[]) => any): void; } // Ambient declarations for 'require' and 'define' declare var require: Require; declare var define: RequireDefine;
random_line_split
logger.rs
/* Copyright (C) 2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ // Author: Frank Honza <[email protected]> use std; use std::fmt::Write; use super::rfb::{RFBState, RFBTransaction}; use crate::jsonbuilder::{JsonBuilder, JsonError}; fn
(tx: &RFBTransaction, js: &mut JsonBuilder) -> Result<(), JsonError> { js.open_object("rfb")?; // Protocol version if let Some(tx_spv) = &tx.tc_server_protocol_version { js.open_object("server_protocol_version")?; js.set_string("major", &tx_spv.major)?; js.set_string("minor", &tx_spv.minor)?; js.close()?; } if let Some(tx_cpv) = &tx.ts_client_protocol_version { js.open_object("client_protocol_version")?; js.set_string("major", &tx_cpv.major)?; js.set_string("minor", &tx_cpv.minor)?; js.close()?; } // Authentication js.open_object("authentication")?; if let Some(chosen_security_type) = tx.chosen_security_type { js.set_uint("security_type", chosen_security_type as u64)?; } match tx.chosen_security_type { Some(2) => { js.open_object("vnc")?; if let Some(ref sc) = tx.tc_vnc_challenge { let mut s = String::new(); for &byte in &sc.secret[..] { write!(&mut s, "{:02x}", byte).expect("Unable to write"); } js.set_string("challenge", &s)?; } if let Some(ref sr) = tx.ts_vnc_response { let mut s = String::new(); for &byte in &sr.secret[..] { write!(&mut s, "{:02x}", byte).expect("Unable to write"); } js.set_string("response", &s)?; } js.close()?; } _ => () } if let Some(security_result) = &tx.tc_security_result { let _ = match security_result.status { 0 => js.set_string("security_result", "OK")?, 1 => js.set_string("security-result", "FAIL")?, 2 => js.set_string("security_result", "TOOMANY")?, _ => js.set_string("security_result", &format!("UNKNOWN ({})", security_result.status))?, }; } js.close()?; // Close authentication. if let Some(ref reason) = tx.tc_failure_reason { js.set_string("server_security_failure_reason", &reason.reason_string)?; } // Client/Server init if let Some(s) = &tx.ts_client_init { js.set_bool("screen_shared", s.shared != 0)?; } if let Some(tc_server_init) = &tx.tc_server_init { js.open_object("framebuffer")?; js.set_uint("width", tc_server_init.width as u64)?; js.set_uint("height", tc_server_init.height as u64)?; js.set_string_from_bytes("name", &tc_server_init.name)?; js.open_object("pixel_format")?; js.set_uint("bits_per_pixel", tc_server_init.pixel_format.bits_per_pixel as u64)?; js.set_uint("depth", tc_server_init.pixel_format.depth as u64)?; js.set_bool("big_endian", tc_server_init.pixel_format.big_endian_flag != 0)?; js.set_bool("true_color", tc_server_init.pixel_format.true_colour_flag != 0)?; js.set_uint("red_max", tc_server_init.pixel_format.red_max as u64)?; js.set_uint("green_max", tc_server_init.pixel_format.green_max as u64)?; js.set_uint("blue_max", tc_server_init.pixel_format.blue_max as u64)?; js.set_uint("red_shift", tc_server_init.pixel_format.red_shift as u64)?; js.set_uint("green_shift", tc_server_init.pixel_format.green_shift as u64)?; js.set_uint("blue_shift", tc_server_init.pixel_format.blue_shift as u64)?; js.set_uint("depth", tc_server_init.pixel_format.depth as u64)?; js.close()?; js.close()?; } js.close()?; return Ok(()); } #[no_mangle] pub unsafe extern "C" fn rs_rfb_logger_log(_state: &mut RFBState, tx: *mut std::os::raw::c_void, js: &mut JsonBuilder) -> bool { let tx = cast_pointer!(tx, RFBTransaction); log_rfb(tx, js).is_ok() }
log_rfb
identifier_name
logger.rs
/* Copyright (C) 2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ // Author: Frank Honza <[email protected]> use std; use std::fmt::Write; use super::rfb::{RFBState, RFBTransaction}; use crate::jsonbuilder::{JsonBuilder, JsonError}; fn log_rfb(tx: &RFBTransaction, js: &mut JsonBuilder) -> Result<(), JsonError> { js.open_object("rfb")?; // Protocol version if let Some(tx_spv) = &tx.tc_server_protocol_version { js.open_object("server_protocol_version")?; js.set_string("major", &tx_spv.major)?; js.set_string("minor", &tx_spv.minor)?; js.close()?; } if let Some(tx_cpv) = &tx.ts_client_protocol_version { js.open_object("client_protocol_version")?; js.set_string("major", &tx_cpv.major)?; js.set_string("minor", &tx_cpv.minor)?; js.close()?; } // Authentication js.open_object("authentication")?;
match tx.chosen_security_type { Some(2) => { js.open_object("vnc")?; if let Some(ref sc) = tx.tc_vnc_challenge { let mut s = String::new(); for &byte in &sc.secret[..] { write!(&mut s, "{:02x}", byte).expect("Unable to write"); } js.set_string("challenge", &s)?; } if let Some(ref sr) = tx.ts_vnc_response { let mut s = String::new(); for &byte in &sr.secret[..] { write!(&mut s, "{:02x}", byte).expect("Unable to write"); } js.set_string("response", &s)?; } js.close()?; } _ => () } if let Some(security_result) = &tx.tc_security_result { let _ = match security_result.status { 0 => js.set_string("security_result", "OK")?, 1 => js.set_string("security-result", "FAIL")?, 2 => js.set_string("security_result", "TOOMANY")?, _ => js.set_string("security_result", &format!("UNKNOWN ({})", security_result.status))?, }; } js.close()?; // Close authentication. if let Some(ref reason) = tx.tc_failure_reason { js.set_string("server_security_failure_reason", &reason.reason_string)?; } // Client/Server init if let Some(s) = &tx.ts_client_init { js.set_bool("screen_shared", s.shared != 0)?; } if let Some(tc_server_init) = &tx.tc_server_init { js.open_object("framebuffer")?; js.set_uint("width", tc_server_init.width as u64)?; js.set_uint("height", tc_server_init.height as u64)?; js.set_string_from_bytes("name", &tc_server_init.name)?; js.open_object("pixel_format")?; js.set_uint("bits_per_pixel", tc_server_init.pixel_format.bits_per_pixel as u64)?; js.set_uint("depth", tc_server_init.pixel_format.depth as u64)?; js.set_bool("big_endian", tc_server_init.pixel_format.big_endian_flag != 0)?; js.set_bool("true_color", tc_server_init.pixel_format.true_colour_flag != 0)?; js.set_uint("red_max", tc_server_init.pixel_format.red_max as u64)?; js.set_uint("green_max", tc_server_init.pixel_format.green_max as u64)?; js.set_uint("blue_max", tc_server_init.pixel_format.blue_max as u64)?; js.set_uint("red_shift", tc_server_init.pixel_format.red_shift as u64)?; js.set_uint("green_shift", tc_server_init.pixel_format.green_shift as u64)?; js.set_uint("blue_shift", tc_server_init.pixel_format.blue_shift as u64)?; js.set_uint("depth", tc_server_init.pixel_format.depth as u64)?; js.close()?; js.close()?; } js.close()?; return Ok(()); } #[no_mangle] pub unsafe extern "C" fn rs_rfb_logger_log(_state: &mut RFBState, tx: *mut std::os::raw::c_void, js: &mut JsonBuilder) -> bool { let tx = cast_pointer!(tx, RFBTransaction); log_rfb(tx, js).is_ok() }
if let Some(chosen_security_type) = tx.chosen_security_type { js.set_uint("security_type", chosen_security_type as u64)?; }
random_line_split
logger.rs
/* Copyright (C) 2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ // Author: Frank Honza <[email protected]> use std; use std::fmt::Write; use super::rfb::{RFBState, RFBTransaction}; use crate::jsonbuilder::{JsonBuilder, JsonError}; fn log_rfb(tx: &RFBTransaction, js: &mut JsonBuilder) -> Result<(), JsonError>
#[no_mangle] pub unsafe extern "C" fn rs_rfb_logger_log(_state: &mut RFBState, tx: *mut std::os::raw::c_void, js: &mut JsonBuilder) -> bool { let tx = cast_pointer!(tx, RFBTransaction); log_rfb(tx, js).is_ok() }
{ js.open_object("rfb")?; // Protocol version if let Some(tx_spv) = &tx.tc_server_protocol_version { js.open_object("server_protocol_version")?; js.set_string("major", &tx_spv.major)?; js.set_string("minor", &tx_spv.minor)?; js.close()?; } if let Some(tx_cpv) = &tx.ts_client_protocol_version { js.open_object("client_protocol_version")?; js.set_string("major", &tx_cpv.major)?; js.set_string("minor", &tx_cpv.minor)?; js.close()?; } // Authentication js.open_object("authentication")?; if let Some(chosen_security_type) = tx.chosen_security_type { js.set_uint("security_type", chosen_security_type as u64)?; } match tx.chosen_security_type { Some(2) => { js.open_object("vnc")?; if let Some(ref sc) = tx.tc_vnc_challenge { let mut s = String::new(); for &byte in &sc.secret[..] { write!(&mut s, "{:02x}", byte).expect("Unable to write"); } js.set_string("challenge", &s)?; } if let Some(ref sr) = tx.ts_vnc_response { let mut s = String::new(); for &byte in &sr.secret[..] { write!(&mut s, "{:02x}", byte).expect("Unable to write"); } js.set_string("response", &s)?; } js.close()?; } _ => () } if let Some(security_result) = &tx.tc_security_result { let _ = match security_result.status { 0 => js.set_string("security_result", "OK")?, 1 => js.set_string("security-result", "FAIL")?, 2 => js.set_string("security_result", "TOOMANY")?, _ => js.set_string("security_result", &format!("UNKNOWN ({})", security_result.status))?, }; } js.close()?; // Close authentication. if let Some(ref reason) = tx.tc_failure_reason { js.set_string("server_security_failure_reason", &reason.reason_string)?; } // Client/Server init if let Some(s) = &tx.ts_client_init { js.set_bool("screen_shared", s.shared != 0)?; } if let Some(tc_server_init) = &tx.tc_server_init { js.open_object("framebuffer")?; js.set_uint("width", tc_server_init.width as u64)?; js.set_uint("height", tc_server_init.height as u64)?; js.set_string_from_bytes("name", &tc_server_init.name)?; js.open_object("pixel_format")?; js.set_uint("bits_per_pixel", tc_server_init.pixel_format.bits_per_pixel as u64)?; js.set_uint("depth", tc_server_init.pixel_format.depth as u64)?; js.set_bool("big_endian", tc_server_init.pixel_format.big_endian_flag != 0)?; js.set_bool("true_color", tc_server_init.pixel_format.true_colour_flag != 0)?; js.set_uint("red_max", tc_server_init.pixel_format.red_max as u64)?; js.set_uint("green_max", tc_server_init.pixel_format.green_max as u64)?; js.set_uint("blue_max", tc_server_init.pixel_format.blue_max as u64)?; js.set_uint("red_shift", tc_server_init.pixel_format.red_shift as u64)?; js.set_uint("green_shift", tc_server_init.pixel_format.green_shift as u64)?; js.set_uint("blue_shift", tc_server_init.pixel_format.blue_shift as u64)?; js.set_uint("depth", tc_server_init.pixel_format.depth as u64)?; js.close()?; js.close()?; } js.close()?; return Ok(()); }
identifier_body
serverFarmSku.ts
export class Tier { public static readonly free = 'Free'; public static readonly shared = 'Shared'; public static readonly basic = 'Basic'; public static readonly standard = 'Standard'; public static readonly premium = 'Premium'; public static readonly premiumV2 = 'PremiumV2'; public static readonly premiumContainer = 'PremiumContainer'; public static readonly isolated = 'Isolated'; public static readonly dynamic = 'Dynamic'; public static readonly elasticPremium = 'ElasticPremium'; public static readonly elasticIsolated = 'ElasticIsolated'; } export class SkuCode { public static readonly Basic = { B1: 'B1', B2: 'B2', B3: 'B3', }; public static readonly Free = { F1: 'F1', }; public static readonly Shared = { D1: 'D1', }; public static readonly Standard = { S1: 'S1', S2: 'S2', S3: 'S3', }; public static readonly Premium = { P1: 'P1', P2: 'P2', P3: 'P3', }; public static readonly PremiumContainer = { PC2: 'PC2', PC3: 'PC3', PC4: 'PC4', }; public static readonly PremiumV2 = { P1V2: 'P1V2', P2V2: 'P2V2', P3V2: 'P3V2', }; public static readonly Isolated = { I1: 'I1', I2: 'I2', I3: 'I3', };
EP1CPU: 'EP1-C', EP1Memory: 'EP1-M', EP2CPU: 'EP2-C', EP2Memory: 'EP2-M', EP3CPU: 'EP3-C', EP3Memory: 'EP3-M', }; }
public static readonly ElasticPremium = { EP1: 'EP1', EP2: 'EP2', EP3: 'EP3',
random_line_split
serverFarmSku.ts
export class Tier { public static readonly free = 'Free'; public static readonly shared = 'Shared'; public static readonly basic = 'Basic'; public static readonly standard = 'Standard'; public static readonly premium = 'Premium'; public static readonly premiumV2 = 'PremiumV2'; public static readonly premiumContainer = 'PremiumContainer'; public static readonly isolated = 'Isolated'; public static readonly dynamic = 'Dynamic'; public static readonly elasticPremium = 'ElasticPremium'; public static readonly elasticIsolated = 'ElasticIsolated'; } export class
{ public static readonly Basic = { B1: 'B1', B2: 'B2', B3: 'B3', }; public static readonly Free = { F1: 'F1', }; public static readonly Shared = { D1: 'D1', }; public static readonly Standard = { S1: 'S1', S2: 'S2', S3: 'S3', }; public static readonly Premium = { P1: 'P1', P2: 'P2', P3: 'P3', }; public static readonly PremiumContainer = { PC2: 'PC2', PC3: 'PC3', PC4: 'PC4', }; public static readonly PremiumV2 = { P1V2: 'P1V2', P2V2: 'P2V2', P3V2: 'P3V2', }; public static readonly Isolated = { I1: 'I1', I2: 'I2', I3: 'I3', }; public static readonly ElasticPremium = { EP1: 'EP1', EP2: 'EP2', EP3: 'EP3', EP1CPU: 'EP1-C', EP1Memory: 'EP1-M', EP2CPU: 'EP2-C', EP2Memory: 'EP2-M', EP3CPU: 'EP3-C', EP3Memory: 'EP3-M', }; }
SkuCode
identifier_name
util.rs
use hyper::header::{Accept, Connection, ContentType, Headers, Quality, QualityItem, qitem}; use hyper::mime::{Mime, SubLevel, TopLevel}; use protobuf::{self, Message}; use proto::mesos::*; pub fn protobuf_headers() -> Headers { let mut headers = Headers::new(); headers.set(Accept(vec![ qitem(Mime(TopLevel::Text, SubLevel::Html, vec![])), qitem(Mime(TopLevel::Application, SubLevel::Ext("x-protobuf".to_owned()), vec![])), ])); headers.set(ContentType(Mime(TopLevel::Application, SubLevel::Ext("x-protobuf".to_owned()), vec![]))); headers } pub fn framework_id<'a>(id: &'a str) -> FrameworkID { let mut framework_id = FrameworkID::new(); framework_id.set_value(id.to_string()); framework_id } pub fn framework_info<'a>(user: &'a str, name: &'a str, failover_timeout: f64) -> FrameworkInfo { let mut framework_info = FrameworkInfo::new(); framework_info.set_user(user.to_string()); framework_info.set_name(name.to_string()); framework_info.set_failover_timeout(failover_timeout); framework_info } pub fn task_id<'a>(id: &'a str) -> TaskID { let mut task_id = TaskID::new(); task_id.set_value(id.to_string()); task_id } pub fn task_info<'a>(name: &'a str, task_id: &TaskID, agent_id: &AgentID, command: &CommandInfo, resources: Vec<Resource>) -> TaskInfo { let mut task_info = TaskInfo::new(); task_info.set_name(name.to_string()); task_info.set_task_id(task_id.clone()); task_info.set_agent_id(agent_id.clone()); task_info.set_command(command.clone()); task_info.set_resources(protobuf::RepeatedField::from_vec(resources)); task_info } pub fn task_info_for_container<'a>(name: &'a str, task_id: &TaskID, agent_id: &AgentID, command: &CommandInfo, container: &ContainerInfo, resources: Vec<Resource>) -> TaskInfo { let mut task_info = TaskInfo::new(); task_info.set_name(name.to_string()); task_info.set_task_id(task_id.clone()); task_info.set_agent_id(agent_id.clone()); task_info.set_command(command.clone()); task_info.set_container(container.clone()); task_info.set_resources(protobuf::RepeatedField::from_vec(resources)); task_info } pub fn launch_operation(task_infos: Vec<TaskInfo>) -> Operation { let mut launch = Operation_Launch::new(); launch.set_task_infos(protobuf::RepeatedField::from_vec(task_infos)); let mut operation = Operation::new(); operation.set_field_type(Operation_Type::LAUNCH); operation.set_launch(launch); operation } pub fn scalar<'a>(name: &'a str, role: &'a str, value: f64) -> Resource { let mut scalar = Value_Scalar::new(); scalar.set_value(value); let mut res = Resource::new(); res.set_name(name.to_string()); res.set_role(role.to_string()); res.set_field_type(Value_Type::SCALAR); res.set_scalar(scalar); res } pub fn get_scalar_resource_sum<'a>(name: &'a str, offers: Vec<&Offer>) -> f64
{ offers.iter() .flat_map(|o| o.get_resources()) .filter(|r| r.get_name() == "mem") .map(|c| c.get_scalar()) .fold(0f64, |acc, mem_res| acc + mem_res.get_value()) }
identifier_body
util.rs
use hyper::header::{Accept, Connection, ContentType, Headers, Quality, QualityItem, qitem}; use hyper::mime::{Mime, SubLevel, TopLevel}; use protobuf::{self, Message}; use proto::mesos::*; pub fn protobuf_headers() -> Headers { let mut headers = Headers::new(); headers.set(Accept(vec![ qitem(Mime(TopLevel::Text, SubLevel::Html, vec![])), qitem(Mime(TopLevel::Application, SubLevel::Ext("x-protobuf".to_owned()), vec![])), ])); headers.set(ContentType(Mime(TopLevel::Application, SubLevel::Ext("x-protobuf".to_owned()), vec![]))); headers } pub fn framework_id<'a>(id: &'a str) -> FrameworkID { let mut framework_id = FrameworkID::new(); framework_id.set_value(id.to_string()); framework_id } pub fn framework_info<'a>(user: &'a str, name: &'a str, failover_timeout: f64) -> FrameworkInfo { let mut framework_info = FrameworkInfo::new(); framework_info.set_user(user.to_string()); framework_info.set_name(name.to_string()); framework_info.set_failover_timeout(failover_timeout); framework_info } pub fn task_id<'a>(id: &'a str) -> TaskID { let mut task_id = TaskID::new(); task_id.set_value(id.to_string()); task_id } pub fn task_info<'a>(name: &'a str, task_id: &TaskID, agent_id: &AgentID, command: &CommandInfo, resources: Vec<Resource>) -> TaskInfo { let mut task_info = TaskInfo::new(); task_info.set_name(name.to_string()); task_info.set_task_id(task_id.clone()); task_info.set_agent_id(agent_id.clone()); task_info.set_command(command.clone()); task_info.set_resources(protobuf::RepeatedField::from_vec(resources)); task_info } pub fn task_info_for_container<'a>(name: &'a str, task_id: &TaskID, agent_id: &AgentID, command: &CommandInfo, container: &ContainerInfo, resources: Vec<Resource>) -> TaskInfo { let mut task_info = TaskInfo::new(); task_info.set_name(name.to_string()); task_info.set_task_id(task_id.clone()); task_info.set_agent_id(agent_id.clone()); task_info.set_command(command.clone()); task_info.set_container(container.clone()); task_info.set_resources(protobuf::RepeatedField::from_vec(resources)); task_info } pub fn launch_operation(task_infos: Vec<TaskInfo>) -> Operation { let mut launch = Operation_Launch::new(); launch.set_task_infos(protobuf::RepeatedField::from_vec(task_infos)); let mut operation = Operation::new(); operation.set_field_type(Operation_Type::LAUNCH); operation.set_launch(launch); operation } pub fn scalar<'a>(name: &'a str, role: &'a str, value: f64) -> Resource { let mut scalar = Value_Scalar::new(); scalar.set_value(value);
res.set_role(role.to_string()); res.set_field_type(Value_Type::SCALAR); res.set_scalar(scalar); res } pub fn get_scalar_resource_sum<'a>(name: &'a str, offers: Vec<&Offer>) -> f64 { offers.iter() .flat_map(|o| o.get_resources()) .filter(|r| r.get_name() == "mem") .map(|c| c.get_scalar()) .fold(0f64, |acc, mem_res| acc + mem_res.get_value()) }
let mut res = Resource::new(); res.set_name(name.to_string());
random_line_split
util.rs
use hyper::header::{Accept, Connection, ContentType, Headers, Quality, QualityItem, qitem}; use hyper::mime::{Mime, SubLevel, TopLevel}; use protobuf::{self, Message}; use proto::mesos::*; pub fn protobuf_headers() -> Headers { let mut headers = Headers::new(); headers.set(Accept(vec![ qitem(Mime(TopLevel::Text, SubLevel::Html, vec![])), qitem(Mime(TopLevel::Application, SubLevel::Ext("x-protobuf".to_owned()), vec![])), ])); headers.set(ContentType(Mime(TopLevel::Application, SubLevel::Ext("x-protobuf".to_owned()), vec![]))); headers } pub fn framework_id<'a>(id: &'a str) -> FrameworkID { let mut framework_id = FrameworkID::new(); framework_id.set_value(id.to_string()); framework_id } pub fn framework_info<'a>(user: &'a str, name: &'a str, failover_timeout: f64) -> FrameworkInfo { let mut framework_info = FrameworkInfo::new(); framework_info.set_user(user.to_string()); framework_info.set_name(name.to_string()); framework_info.set_failover_timeout(failover_timeout); framework_info } pub fn task_id<'a>(id: &'a str) -> TaskID { let mut task_id = TaskID::new(); task_id.set_value(id.to_string()); task_id } pub fn task_info<'a>(name: &'a str, task_id: &TaskID, agent_id: &AgentID, command: &CommandInfo, resources: Vec<Resource>) -> TaskInfo { let mut task_info = TaskInfo::new(); task_info.set_name(name.to_string()); task_info.set_task_id(task_id.clone()); task_info.set_agent_id(agent_id.clone()); task_info.set_command(command.clone()); task_info.set_resources(protobuf::RepeatedField::from_vec(resources)); task_info } pub fn task_info_for_container<'a>(name: &'a str, task_id: &TaskID, agent_id: &AgentID, command: &CommandInfo, container: &ContainerInfo, resources: Vec<Resource>) -> TaskInfo { let mut task_info = TaskInfo::new(); task_info.set_name(name.to_string()); task_info.set_task_id(task_id.clone()); task_info.set_agent_id(agent_id.clone()); task_info.set_command(command.clone()); task_info.set_container(container.clone()); task_info.set_resources(protobuf::RepeatedField::from_vec(resources)); task_info } pub fn
(task_infos: Vec<TaskInfo>) -> Operation { let mut launch = Operation_Launch::new(); launch.set_task_infos(protobuf::RepeatedField::from_vec(task_infos)); let mut operation = Operation::new(); operation.set_field_type(Operation_Type::LAUNCH); operation.set_launch(launch); operation } pub fn scalar<'a>(name: &'a str, role: &'a str, value: f64) -> Resource { let mut scalar = Value_Scalar::new(); scalar.set_value(value); let mut res = Resource::new(); res.set_name(name.to_string()); res.set_role(role.to_string()); res.set_field_type(Value_Type::SCALAR); res.set_scalar(scalar); res } pub fn get_scalar_resource_sum<'a>(name: &'a str, offers: Vec<&Offer>) -> f64 { offers.iter() .flat_map(|o| o.get_resources()) .filter(|r| r.get_name() == "mem") .map(|c| c.get_scalar()) .fold(0f64, |acc, mem_res| acc + mem_res.get_value()) }
launch_operation
identifier_name
settings.py
# Django settings for test_remote_project project. import os.path import posixpath PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '[email protected]'), ) FIXTURE_DIRS = [ os.path.join(PROJECT_ROOT, 'fixtures'), ] MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'db.sqlite', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here:
# although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = 'mzdvd*#0=$g(-!v_vj_7^(=zrh3klia(u&amp;cqd3nr7p^khh^ui#' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'test_remote_project.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'test_remote_project.wsgi.application' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. os.path.join(PROJECT_ROOT, 'templates'), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', 'cities_light', 'djangorestframework', 'south', 'autocomplete_light', 'remote_autocomplete', 'remote_autocomplete_inline', 'navigation_autocomplete', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'console':{ 'level':'DEBUG', 'class':'logging.StreamHandler', }, }, 'loggers': { 'django.request': { 'handlers':['console'], 'propagate': True, 'level':'DEBUG', }, 'cities_light': { 'handlers':['console'], 'propagate': True, 'level':'DEBUG', }, } }
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
random_line_split
gui.py
import cairo from gi.repository import Gtk from gi.repository import Gdk from pylsner import plugin class Window(Gtk.Window): def __init__(self): super(Window, self).__init__(skip_pager_hint=True, skip_taskbar_hint=True, ) self.set_title('Pylsner') screen = self.get_screen() self.width = screen.get_width() self.height = screen.get_height() self.set_size_request(self.width, self.height) self.set_position(Gtk.WindowPosition.CENTER) rgba = screen.get_rgba_visual() self.set_visual(rgba) self.override_background_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(0, 0, 0, 0), ) self.set_wmclass('pylsner', 'pylsner') self.set_type_hint(Gdk.WindowTypeHint.DOCK) self.stick() self.set_keep_below(True) drawing_area = Gtk.DrawingArea() drawing_area.connect('draw', self.redraw) self.refresh_cnt = 0 self.add(drawing_area) self.connect('destroy', lambda q: Gtk.main_quit()) self.widgets = [] self.show_all() def refresh(self, force=False): self.refresh_cnt += 1 if self.refresh_cnt >= 60000: self.refresh_cnt = 0 redraw_required = False for wid in self.widgets:
if redraw_required: self.queue_draw() return True def redraw(self, _, ctx): ctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL) for wid in self.widgets: wid.redraw(ctx) class Widget: def __init__(self, name='default', metric={'plugin': 'time'}, indicator={'plugin': 'arc'}, fill={'plugin': 'rgba_255'}, ): self.name = name MetricPlugin = plugin.load_plugin('metrics', metric['plugin']) self.metric = MetricPlugin(**metric) IndicatorPlugin = plugin.load_plugin('indicators', indicator['plugin']) self.indicator = IndicatorPlugin(**indicator) FillPlugin = plugin.load_plugin('fills', fill['plugin']) self.fill = FillPlugin(**fill) def refresh(self): self.metric.refresh() self.fill.refresh(self.metric.value) def redraw(self, ctx): ctx.set_source(self.fill.pattern) self.indicator.redraw(ctx, self.metric.value)
if (self.refresh_cnt % wid.metric.refresh_rate == 0) or force: wid.refresh() redraw_required = True
conditional_block
gui.py
import cairo from gi.repository import Gtk from gi.repository import Gdk from pylsner import plugin class Window(Gtk.Window): def __init__(self): super(Window, self).__init__(skip_pager_hint=True, skip_taskbar_hint=True, ) self.set_title('Pylsner') screen = self.get_screen() self.width = screen.get_width() self.height = screen.get_height() self.set_size_request(self.width, self.height) self.set_position(Gtk.WindowPosition.CENTER) rgba = screen.get_rgba_visual() self.set_visual(rgba) self.override_background_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(0, 0, 0, 0), ) self.set_wmclass('pylsner', 'pylsner') self.set_type_hint(Gdk.WindowTypeHint.DOCK) self.stick() self.set_keep_below(True) drawing_area = Gtk.DrawingArea() drawing_area.connect('draw', self.redraw) self.refresh_cnt = 0 self.add(drawing_area) self.connect('destroy', lambda q: Gtk.main_quit()) self.widgets = [] self.show_all() def refresh(self, force=False): self.refresh_cnt += 1 if self.refresh_cnt >= 60000: self.refresh_cnt = 0 redraw_required = False for wid in self.widgets: if (self.refresh_cnt % wid.metric.refresh_rate == 0) or force: wid.refresh() redraw_required = True if redraw_required: self.queue_draw() return True def redraw(self, _, ctx): ctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL) for wid in self.widgets: wid.redraw(ctx) class Widget: def
(self, name='default', metric={'plugin': 'time'}, indicator={'plugin': 'arc'}, fill={'plugin': 'rgba_255'}, ): self.name = name MetricPlugin = plugin.load_plugin('metrics', metric['plugin']) self.metric = MetricPlugin(**metric) IndicatorPlugin = plugin.load_plugin('indicators', indicator['plugin']) self.indicator = IndicatorPlugin(**indicator) FillPlugin = plugin.load_plugin('fills', fill['plugin']) self.fill = FillPlugin(**fill) def refresh(self): self.metric.refresh() self.fill.refresh(self.metric.value) def redraw(self, ctx): ctx.set_source(self.fill.pattern) self.indicator.redraw(ctx, self.metric.value)
__init__
identifier_name
gui.py
import cairo from gi.repository import Gtk from gi.repository import Gdk from pylsner import plugin class Window(Gtk.Window): def __init__(self): super(Window, self).__init__(skip_pager_hint=True, skip_taskbar_hint=True, ) self.set_title('Pylsner') screen = self.get_screen() self.width = screen.get_width() self.height = screen.get_height() self.set_size_request(self.width, self.height) self.set_position(Gtk.WindowPosition.CENTER) rgba = screen.get_rgba_visual() self.set_visual(rgba) self.override_background_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(0, 0, 0, 0), ) self.set_wmclass('pylsner', 'pylsner')
self.stick() self.set_keep_below(True) drawing_area = Gtk.DrawingArea() drawing_area.connect('draw', self.redraw) self.refresh_cnt = 0 self.add(drawing_area) self.connect('destroy', lambda q: Gtk.main_quit()) self.widgets = [] self.show_all() def refresh(self, force=False): self.refresh_cnt += 1 if self.refresh_cnt >= 60000: self.refresh_cnt = 0 redraw_required = False for wid in self.widgets: if (self.refresh_cnt % wid.metric.refresh_rate == 0) or force: wid.refresh() redraw_required = True if redraw_required: self.queue_draw() return True def redraw(self, _, ctx): ctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL) for wid in self.widgets: wid.redraw(ctx) class Widget: def __init__(self, name='default', metric={'plugin': 'time'}, indicator={'plugin': 'arc'}, fill={'plugin': 'rgba_255'}, ): self.name = name MetricPlugin = plugin.load_plugin('metrics', metric['plugin']) self.metric = MetricPlugin(**metric) IndicatorPlugin = plugin.load_plugin('indicators', indicator['plugin']) self.indicator = IndicatorPlugin(**indicator) FillPlugin = plugin.load_plugin('fills', fill['plugin']) self.fill = FillPlugin(**fill) def refresh(self): self.metric.refresh() self.fill.refresh(self.metric.value) def redraw(self, ctx): ctx.set_source(self.fill.pattern) self.indicator.redraw(ctx, self.metric.value)
self.set_type_hint(Gdk.WindowTypeHint.DOCK)
random_line_split
gui.py
import cairo from gi.repository import Gtk from gi.repository import Gdk from pylsner import plugin class Window(Gtk.Window):
class Widget: def __init__(self, name='default', metric={'plugin': 'time'}, indicator={'plugin': 'arc'}, fill={'plugin': 'rgba_255'}, ): self.name = name MetricPlugin = plugin.load_plugin('metrics', metric['plugin']) self.metric = MetricPlugin(**metric) IndicatorPlugin = plugin.load_plugin('indicators', indicator['plugin']) self.indicator = IndicatorPlugin(**indicator) FillPlugin = plugin.load_plugin('fills', fill['plugin']) self.fill = FillPlugin(**fill) def refresh(self): self.metric.refresh() self.fill.refresh(self.metric.value) def redraw(self, ctx): ctx.set_source(self.fill.pattern) self.indicator.redraw(ctx, self.metric.value)
def __init__(self): super(Window, self).__init__(skip_pager_hint=True, skip_taskbar_hint=True, ) self.set_title('Pylsner') screen = self.get_screen() self.width = screen.get_width() self.height = screen.get_height() self.set_size_request(self.width, self.height) self.set_position(Gtk.WindowPosition.CENTER) rgba = screen.get_rgba_visual() self.set_visual(rgba) self.override_background_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(0, 0, 0, 0), ) self.set_wmclass('pylsner', 'pylsner') self.set_type_hint(Gdk.WindowTypeHint.DOCK) self.stick() self.set_keep_below(True) drawing_area = Gtk.DrawingArea() drawing_area.connect('draw', self.redraw) self.refresh_cnt = 0 self.add(drawing_area) self.connect('destroy', lambda q: Gtk.main_quit()) self.widgets = [] self.show_all() def refresh(self, force=False): self.refresh_cnt += 1 if self.refresh_cnt >= 60000: self.refresh_cnt = 0 redraw_required = False for wid in self.widgets: if (self.refresh_cnt % wid.metric.refresh_rate == 0) or force: wid.refresh() redraw_required = True if redraw_required: self.queue_draw() return True def redraw(self, _, ctx): ctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL) for wid in self.widgets: wid.redraw(ctx)
identifier_body
DeleteNodeBST.py
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: node = parent = None def deleteNode(self, root: TreeNode, key: int) -> TreeNode: # search for the node and its parent self.findNodeAndParent(root, key) if self.node == root and not root.left and not root.right: return None if self.node: self.deleteNodeHelper(self.node, self.parent) return root def deleteNodeHelper(self, node, parent): # if node is a leaf if not node.left and not node.right: if parent: if parent.left == node: parent.left = None else:
return # if node has only one child if not node.left or not node.right: child = node.left if not node.right else node.right node.val = child.val node.left = child.left node.right = child.right return # node has two children successor, succesorParent = self.getNodeSuccessor(node) node.val = successor.val self.deleteNodeHelper(successor, succesorParent) def getNodeSuccessor(self, node): succesorParent = node successor = node.right while successor.left: succesorParent = successor successor = successor.left return successor, succesorParent def findNodeAndParent(self, root, key): if not root: return if root.val == key: self.node = root return self.parent = root if key < root.val: self.findNodeAndParent(root.left, key) else: self.findNodeAndParent(root.right, key) root = TreeNode(10) root.left = TreeNode(3) root.left.left = TreeNode(2) root.left.right = TreeNode(8) root.left.right.left = TreeNode(7) root.left.right.right = TreeNode(9) root.right = TreeNode(15) root.right.left = TreeNode(13) root.right.right = TreeNode(17) root.right.right.right = TreeNode(19) ob = Solution() root = TreeNode(50) root = ob.deleteNode(root, 50) print(root)
parent.right = None
conditional_block
DeleteNodeBST.py
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: node = parent = None def deleteNode(self, root: TreeNode, key: int) -> TreeNode: # search for the node and its parent self.findNodeAndParent(root, key) if self.node == root and not root.left and not root.right: return None if self.node: self.deleteNodeHelper(self.node, self.parent) return root def deleteNodeHelper(self, node, parent): # if node is a leaf if not node.left and not node.right: if parent: if parent.left == node: parent.left = None else: parent.right = None return # if node has only one child if not node.left or not node.right: child = node.left if not node.right else node.right node.val = child.val node.left = child.left node.right = child.right return # node has two children successor, succesorParent = self.getNodeSuccessor(node) node.val = successor.val self.deleteNodeHelper(successor, succesorParent) def getNodeSuccessor(self, node): succesorParent = node successor = node.right while successor.left: succesorParent = successor successor = successor.left return successor, succesorParent def
(self, root, key): if not root: return if root.val == key: self.node = root return self.parent = root if key < root.val: self.findNodeAndParent(root.left, key) else: self.findNodeAndParent(root.right, key) root = TreeNode(10) root.left = TreeNode(3) root.left.left = TreeNode(2) root.left.right = TreeNode(8) root.left.right.left = TreeNode(7) root.left.right.right = TreeNode(9) root.right = TreeNode(15) root.right.left = TreeNode(13) root.right.right = TreeNode(17) root.right.right.right = TreeNode(19) ob = Solution() root = TreeNode(50) root = ob.deleteNode(root, 50) print(root)
findNodeAndParent
identifier_name
DeleteNodeBST.py
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: node = parent = None def deleteNode(self, root: TreeNode, key: int) -> TreeNode: # search for the node and its parent self.findNodeAndParent(root, key) if self.node == root and not root.left and not root.right: return None if self.node: self.deleteNodeHelper(self.node, self.parent) return root def deleteNodeHelper(self, node, parent): # if node is a leaf
def getNodeSuccessor(self, node): succesorParent = node successor = node.right while successor.left: succesorParent = successor successor = successor.left return successor, succesorParent def findNodeAndParent(self, root, key): if not root: return if root.val == key: self.node = root return self.parent = root if key < root.val: self.findNodeAndParent(root.left, key) else: self.findNodeAndParent(root.right, key) root = TreeNode(10) root.left = TreeNode(3) root.left.left = TreeNode(2) root.left.right = TreeNode(8) root.left.right.left = TreeNode(7) root.left.right.right = TreeNode(9) root.right = TreeNode(15) root.right.left = TreeNode(13) root.right.right = TreeNode(17) root.right.right.right = TreeNode(19) ob = Solution() root = TreeNode(50) root = ob.deleteNode(root, 50) print(root)
if not node.left and not node.right: if parent: if parent.left == node: parent.left = None else: parent.right = None return # if node has only one child if not node.left or not node.right: child = node.left if not node.right else node.right node.val = child.val node.left = child.left node.right = child.right return # node has two children successor, succesorParent = self.getNodeSuccessor(node) node.val = successor.val self.deleteNodeHelper(successor, succesorParent)
identifier_body
DeleteNodeBST.py
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: node = parent = None def deleteNode(self, root: TreeNode, key: int) -> TreeNode: # search for the node and its parent self.findNodeAndParent(root, key) if self.node == root and not root.left and not root.right: return None if self.node: self.deleteNodeHelper(self.node, self.parent) return root def deleteNodeHelper(self, node, parent): # if node is a leaf if not node.left and not node.right: if parent: if parent.left == node: parent.left = None else:
# if node has only one child if not node.left or not node.right: child = node.left if not node.right else node.right node.val = child.val node.left = child.left node.right = child.right return # node has two children successor, succesorParent = self.getNodeSuccessor(node) node.val = successor.val self.deleteNodeHelper(successor, succesorParent) def getNodeSuccessor(self, node): succesorParent = node successor = node.right while successor.left: succesorParent = successor successor = successor.left return successor, succesorParent def findNodeAndParent(self, root, key): if not root: return if root.val == key: self.node = root return self.parent = root if key < root.val: self.findNodeAndParent(root.left, key) else: self.findNodeAndParent(root.right, key) root = TreeNode(10) root.left = TreeNode(3) root.left.left = TreeNode(2) root.left.right = TreeNode(8) root.left.right.left = TreeNode(7) root.left.right.right = TreeNode(9) root.right = TreeNode(15) root.right.left = TreeNode(13) root.right.right = TreeNode(17) root.right.right.right = TreeNode(19) ob = Solution() root = TreeNode(50) root = ob.deleteNode(root, 50) print(root)
parent.right = None return
random_line_split
directdl_tv.py
# -*- coding: utf-8 -*- ''' Specto Add-on Copyright (C) 2015 lambda This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import re,urllib,urlparse,json,base64
from resources.lib.libraries import control from resources.lib.libraries import cleantitle from resources.lib.libraries import client from resources.lib import resolvers class source: def __init__(self): self.base_link = 'http://directdownload.tv' self.search_link = 'L2FwaT9rZXk9NEIwQkI4NjJGMjRDOEEyOSZxdWFsaXR5W109SERUViZxdWFsaXR5W109RFZEUklQJnF1YWxpdHlbXT03MjBQJnF1YWxpdHlbXT1XRUJETCZxdWFsaXR5W109V0VCREwxMDgwUCZsaW1pdD0yMCZrZXl3b3JkPQ==' def get_show(self, imdb, tvdb, tvshowtitle, year): try: url = tvshowtitle url = client.replaceHTMLCodes(url) url = url.encode('utf-8') return url except: return def get_episode(self, url, imdb, tvdb, title, date, season, episode): try: if url == None: return url = '%s S%02dE%02d' % (url, int(season), int(episode)) url = client.replaceHTMLCodes(url) url = url.encode('utf-8') return url except: return def get_sources(self, url, hosthdDict, hostDict, locDict): try: sources = [] if url == None: return sources if (control.setting('realdedrid_user') == '' and control.setting('premiumize_user') == ''): raise Exception() query = base64.urlsafe_b64decode(self.search_link) + urllib.quote_plus(url) query = urlparse.urljoin(self.base_link, query) result = client.request(query) result = json.loads(result) title, hdlr = re.compile('(.+?) (S\d*E\d*)$').findall(url)[0] title = cleantitle.tv(title) hdlr = [hdlr] links = [] for i in result: try: t = i['showName'] t = client.replaceHTMLCodes(t) t = cleantitle.tv(t) if not t == title: raise Exception() y = i['release'] y = re.compile('[\.|\(|\[|\s](\d{4}|S\d*E\d*)[\.|\)|\]|\s]').findall(y)[-1] y = y.upper() if not any(x == y for x in hdlr): raise Exception() quality = i['quality'] if quality == 'WEBDL1080P': quality = '1080p' elif quality in ['720P', 'WEBDL']: quality = 'HD' else: quality = 'SD' size = i['size'] size = float(size)/1024 info = '%.2f GB' % size url = i['links'] for x in url.keys(): links.append({'url': url[x], 'quality': quality, 'info': info}) except: pass for i in links: try: url = i['url'] if len(url) > 1: raise Exception() url = url[0] host = (urlparse.urlparse(url).netloc).replace('www.', '').rsplit('.', 1)[0].lower() if not host in hosthdDict: raise Exception() sources.append({'source': host, 'quality': i['quality'], 'provider': 'DirectDL', 'url': url, 'info': i['info']}) except: pass return sources except: return sources def resolve(self, url): try: url = resolvers.request(url) return url except: return
random_line_split
directdl_tv.py
# -*- coding: utf-8 -*- ''' Specto Add-on Copyright (C) 2015 lambda This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import re,urllib,urlparse,json,base64 from resources.lib.libraries import control from resources.lib.libraries import cleantitle from resources.lib.libraries import client from resources.lib import resolvers class source: def __init__(self): self.base_link = 'http://directdownload.tv' self.search_link = 'L2FwaT9rZXk9NEIwQkI4NjJGMjRDOEEyOSZxdWFsaXR5W109SERUViZxdWFsaXR5W109RFZEUklQJnF1YWxpdHlbXT03MjBQJnF1YWxpdHlbXT1XRUJETCZxdWFsaXR5W109V0VCREwxMDgwUCZsaW1pdD0yMCZrZXl3b3JkPQ==' def get_show(self, imdb, tvdb, tvshowtitle, year): try: url = tvshowtitle url = client.replaceHTMLCodes(url) url = url.encode('utf-8') return url except: return def get_episode(self, url, imdb, tvdb, title, date, season, episode): try: if url == None: return url = '%s S%02dE%02d' % (url, int(season), int(episode)) url = client.replaceHTMLCodes(url) url = url.encode('utf-8') return url except: return def get_sources(self, url, hosthdDict, hostDict, locDict): try: sources = [] if url == None: return sources if (control.setting('realdedrid_user') == '' and control.setting('premiumize_user') == ''): raise Exception() query = base64.urlsafe_b64decode(self.search_link) + urllib.quote_plus(url) query = urlparse.urljoin(self.base_link, query) result = client.request(query) result = json.loads(result) title, hdlr = re.compile('(.+?) (S\d*E\d*)$').findall(url)[0] title = cleantitle.tv(title) hdlr = [hdlr] links = [] for i in result: try: t = i['showName'] t = client.replaceHTMLCodes(t) t = cleantitle.tv(t) if not t == title: raise Exception() y = i['release'] y = re.compile('[\.|\(|\[|\s](\d{4}|S\d*E\d*)[\.|\)|\]|\s]').findall(y)[-1] y = y.upper() if not any(x == y for x in hdlr): raise Exception() quality = i['quality'] if quality == 'WEBDL1080P':
elif quality in ['720P', 'WEBDL']: quality = 'HD' else: quality = 'SD' size = i['size'] size = float(size)/1024 info = '%.2f GB' % size url = i['links'] for x in url.keys(): links.append({'url': url[x], 'quality': quality, 'info': info}) except: pass for i in links: try: url = i['url'] if len(url) > 1: raise Exception() url = url[0] host = (urlparse.urlparse(url).netloc).replace('www.', '').rsplit('.', 1)[0].lower() if not host in hosthdDict: raise Exception() sources.append({'source': host, 'quality': i['quality'], 'provider': 'DirectDL', 'url': url, 'info': i['info']}) except: pass return sources except: return sources def resolve(self, url): try: url = resolvers.request(url) return url except: return
quality = '1080p'
conditional_block
directdl_tv.py
# -*- coding: utf-8 -*- ''' Specto Add-on Copyright (C) 2015 lambda This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import re,urllib,urlparse,json,base64 from resources.lib.libraries import control from resources.lib.libraries import cleantitle from resources.lib.libraries import client from resources.lib import resolvers class source: def __init__(self): self.base_link = 'http://directdownload.tv' self.search_link = 'L2FwaT9rZXk9NEIwQkI4NjJGMjRDOEEyOSZxdWFsaXR5W109SERUViZxdWFsaXR5W109RFZEUklQJnF1YWxpdHlbXT03MjBQJnF1YWxpdHlbXT1XRUJETCZxdWFsaXR5W109V0VCREwxMDgwUCZsaW1pdD0yMCZrZXl3b3JkPQ==' def get_show(self, imdb, tvdb, tvshowtitle, year): try: url = tvshowtitle url = client.replaceHTMLCodes(url) url = url.encode('utf-8') return url except: return def
(self, url, imdb, tvdb, title, date, season, episode): try: if url == None: return url = '%s S%02dE%02d' % (url, int(season), int(episode)) url = client.replaceHTMLCodes(url) url = url.encode('utf-8') return url except: return def get_sources(self, url, hosthdDict, hostDict, locDict): try: sources = [] if url == None: return sources if (control.setting('realdedrid_user') == '' and control.setting('premiumize_user') == ''): raise Exception() query = base64.urlsafe_b64decode(self.search_link) + urllib.quote_plus(url) query = urlparse.urljoin(self.base_link, query) result = client.request(query) result = json.loads(result) title, hdlr = re.compile('(.+?) (S\d*E\d*)$').findall(url)[0] title = cleantitle.tv(title) hdlr = [hdlr] links = [] for i in result: try: t = i['showName'] t = client.replaceHTMLCodes(t) t = cleantitle.tv(t) if not t == title: raise Exception() y = i['release'] y = re.compile('[\.|\(|\[|\s](\d{4}|S\d*E\d*)[\.|\)|\]|\s]').findall(y)[-1] y = y.upper() if not any(x == y for x in hdlr): raise Exception() quality = i['quality'] if quality == 'WEBDL1080P': quality = '1080p' elif quality in ['720P', 'WEBDL']: quality = 'HD' else: quality = 'SD' size = i['size'] size = float(size)/1024 info = '%.2f GB' % size url = i['links'] for x in url.keys(): links.append({'url': url[x], 'quality': quality, 'info': info}) except: pass for i in links: try: url = i['url'] if len(url) > 1: raise Exception() url = url[0] host = (urlparse.urlparse(url).netloc).replace('www.', '').rsplit('.', 1)[0].lower() if not host in hosthdDict: raise Exception() sources.append({'source': host, 'quality': i['quality'], 'provider': 'DirectDL', 'url': url, 'info': i['info']}) except: pass return sources except: return sources def resolve(self, url): try: url = resolvers.request(url) return url except: return
get_episode
identifier_name
directdl_tv.py
# -*- coding: utf-8 -*- ''' Specto Add-on Copyright (C) 2015 lambda This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import re,urllib,urlparse,json,base64 from resources.lib.libraries import control from resources.lib.libraries import cleantitle from resources.lib.libraries import client from resources.lib import resolvers class source: def __init__(self): self.base_link = 'http://directdownload.tv' self.search_link = 'L2FwaT9rZXk9NEIwQkI4NjJGMjRDOEEyOSZxdWFsaXR5W109SERUViZxdWFsaXR5W109RFZEUklQJnF1YWxpdHlbXT03MjBQJnF1YWxpdHlbXT1XRUJETCZxdWFsaXR5W109V0VCREwxMDgwUCZsaW1pdD0yMCZrZXl3b3JkPQ==' def get_show(self, imdb, tvdb, tvshowtitle, year): try: url = tvshowtitle url = client.replaceHTMLCodes(url) url = url.encode('utf-8') return url except: return def get_episode(self, url, imdb, tvdb, title, date, season, episode):
def get_sources(self, url, hosthdDict, hostDict, locDict): try: sources = [] if url == None: return sources if (control.setting('realdedrid_user') == '' and control.setting('premiumize_user') == ''): raise Exception() query = base64.urlsafe_b64decode(self.search_link) + urllib.quote_plus(url) query = urlparse.urljoin(self.base_link, query) result = client.request(query) result = json.loads(result) title, hdlr = re.compile('(.+?) (S\d*E\d*)$').findall(url)[0] title = cleantitle.tv(title) hdlr = [hdlr] links = [] for i in result: try: t = i['showName'] t = client.replaceHTMLCodes(t) t = cleantitle.tv(t) if not t == title: raise Exception() y = i['release'] y = re.compile('[\.|\(|\[|\s](\d{4}|S\d*E\d*)[\.|\)|\]|\s]').findall(y)[-1] y = y.upper() if not any(x == y for x in hdlr): raise Exception() quality = i['quality'] if quality == 'WEBDL1080P': quality = '1080p' elif quality in ['720P', 'WEBDL']: quality = 'HD' else: quality = 'SD' size = i['size'] size = float(size)/1024 info = '%.2f GB' % size url = i['links'] for x in url.keys(): links.append({'url': url[x], 'quality': quality, 'info': info}) except: pass for i in links: try: url = i['url'] if len(url) > 1: raise Exception() url = url[0] host = (urlparse.urlparse(url).netloc).replace('www.', '').rsplit('.', 1)[0].lower() if not host in hosthdDict: raise Exception() sources.append({'source': host, 'quality': i['quality'], 'provider': 'DirectDL', 'url': url, 'info': i['info']}) except: pass return sources except: return sources def resolve(self, url): try: url = resolvers.request(url) return url except: return
try: if url == None: return url = '%s S%02dE%02d' % (url, int(season), int(episode)) url = client.replaceHTMLCodes(url) url = url.encode('utf-8') return url except: return
identifier_body
inputgroup.tsx
import React from 'react'; import { LabIcon } from '../icon'; import { classes } from '../utils'; /** * InputGroup component properties */ export interface IInputGroupProps extends React.InputHTMLAttributes<HTMLInputElement> { /** * Right icon adornment */ rightIcon?: string | LabIcon; } /** * InputGroup component * * @param props Component properties * @returns Component */ export function InputGroup(props: IInputGroupProps): JSX.Element { const { className, rightIcon, ...others } = props; return ( <div className={classes('jp-InputGroup', className)}> <input {...others}></input>
<span className="jp-InputGroupAction"> {typeof rightIcon === 'string' ? ( <LabIcon.resolveReact icon={rightIcon} elementPosition="center" tag="span" /> ) : ( <rightIcon.react elementPosition="center" tag="span" /> )} </span> )} </div> ); }
{rightIcon && (
random_line_split
object-safety-issue-22040.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Regression test for #22040. use std::fmt::Debug; trait Expr: Debug + PartialEq { fn print_element_count(&self); } //#[derive(PartialEq)] #[derive(Debug)] struct SExpr<'x> { elements: Vec<Box<Expr+ 'x>>, } impl<'x> PartialEq for SExpr<'x> { fn eq(&self, other:&SExpr<'x>) -> bool { println!("L1: {} L2: {}", self.elements.len(), other.elements.len()); //~^ ERROR E0038 let result = self.elements.len() == other.elements.len(); println!("Got compare {}", result); return result; } } impl <'x> SExpr<'x> { fn new() -> SExpr<'x> { return SExpr{elements: Vec::new(),}; } } impl <'x> Expr for SExpr<'x> { fn print_element_count(&self)
} fn main() { let a: Box<Expr> = Box::new(SExpr::new()); //~ ERROR E0038 let b: Box<Expr> = Box::new(SExpr::new()); //~ ERROR E0038 // assert_eq!(a , b); }
{ println!("element count: {}", self.elements.len()); }
identifier_body
object-safety-issue-22040.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Regression test for #22040. use std::fmt::Debug; trait Expr: Debug + PartialEq { fn print_element_count(&self); } //#[derive(PartialEq)] #[derive(Debug)] struct SExpr<'x> { elements: Vec<Box<Expr+ 'x>>, } impl<'x> PartialEq for SExpr<'x> { fn
(&self, other:&SExpr<'x>) -> bool { println!("L1: {} L2: {}", self.elements.len(), other.elements.len()); //~^ ERROR E0038 let result = self.elements.len() == other.elements.len(); println!("Got compare {}", result); return result; } } impl <'x> SExpr<'x> { fn new() -> SExpr<'x> { return SExpr{elements: Vec::new(),}; } } impl <'x> Expr for SExpr<'x> { fn print_element_count(&self) { println!("element count: {}", self.elements.len()); } } fn main() { let a: Box<Expr> = Box::new(SExpr::new()); //~ ERROR E0038 let b: Box<Expr> = Box::new(SExpr::new()); //~ ERROR E0038 // assert_eq!(a , b); }
eq
identifier_name
object-safety-issue-22040.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Regression test for #22040. use std::fmt::Debug; trait Expr: Debug + PartialEq { fn print_element_count(&self); } //#[derive(PartialEq)] #[derive(Debug)] struct SExpr<'x> { elements: Vec<Box<Expr+ 'x>>, } impl<'x> PartialEq for SExpr<'x> { fn eq(&self, other:&SExpr<'x>) -> bool { println!("L1: {} L2: {}", self.elements.len(), other.elements.len()); //~^ ERROR E0038 let result = self.elements.len() == other.elements.len();
impl <'x> SExpr<'x> { fn new() -> SExpr<'x> { return SExpr{elements: Vec::new(),}; } } impl <'x> Expr for SExpr<'x> { fn print_element_count(&self) { println!("element count: {}", self.elements.len()); } } fn main() { let a: Box<Expr> = Box::new(SExpr::new()); //~ ERROR E0038 let b: Box<Expr> = Box::new(SExpr::new()); //~ ERROR E0038 // assert_eq!(a , b); }
println!("Got compare {}", result); return result; } }
random_line_split
ConnectionDetailHeader.test.tsx
/* * Copyright 2020, EnMasse authors.
import { IConnectionHeaderDetailProps, ConnectionDetailHeader } from "components/ConnectionDetail/ConnectionDetailHeader"; import { render, fireEvent } from "@testing-library/react"; describe("Connection Detail Header with all connection details", () => { test("it renders ConnectionDetailHeader component with all props details at top of the page", () => { const props: IConnectionHeaderDetailProps = { hostname: "myapp1", creationTimestamp: "2020-01-20T11:44:28.607Z", containerId: "1.219.2.1.33904", protocol: "AMQP", product: "QpidJMS", version: "0.31.0", encrypted: true, platform: "0.8.0_152.25.125.b16, Oracle Corporation", os: "Mac OS X 10.13.6,x86_64", messageIn: 2, messageOut: 1 }; const { getByText } = render( <ConnectionDetailHeader {...props} addressSpaceType={"standard"} /> ); getByText(props.hostname); getByText(props.containerId); getByText(props.protocol); const seeMoreNode = getByText("See more details"); fireEvent.click(seeMoreNode); getByText("Hide details"); getByText(props.product + ""); getByText(props.version + ""); getByText(props.platform + ""); getByText(props.os + ""); getByText(props.messageIn + " Message in/sec"); getByText(props.messageOut + " Message out/sec"); }); });
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ import * as React from "react";
random_line_split
sessionQuizView.tsx
import * as React from "react"; import { connect } from "react-redux"; import { Link } from "react-router" import * as MediaQuery from "react-responsive" import DashboardContainer from "../../containers/dashboard/dashboardContainer" import PresentationContainer from "../../containers/dashboard/presentationContainer" import RemoteContainer from "../../containers/quiz/remoteContainer" export interface StateProps { rooms: { id: number, teacher: string}[] isTeacher: boolean roomOwner: string } export interface ActionProps { updateRooms() joinRoom(roomId: number) leaveRoom() closeRoom() openRoom() } type Props = StateProps & ActionProps; export class View extends React.Component<Props, any> { props: Props render()
}
{ const { rooms, isTeacher, roomOwner, updateRooms, joinRoom, leaveRoom, closeRoom, openRoom } = this.props let dashboard: boolean = (this.props as any).location.pathname == "/dashboard", presentation: boolean = (this.props as any).location.pathname == "/presentation", remote: boolean = (this.props as any).location.pathname == "/remote" return ( <div> <div> <button onClick={ updateRooms }>Update rooms</button> <button onClick={ leaveRoom }>Leave room</button> { roomOwner != null && <button onClick={ closeRoom }>Close room</button> } { isTeacher && <button onClick={ openRoom }>Open room</button> } Current room: { roomOwner != null ? roomOwner : "none" } <br/> { rooms.map(room => { return <button key={ room.id } onClick={ () => joinRoom(room.id) }> Join Room { room.teacher } </button> })} </div> { remote && <RemoteContainer/>} { dashboard && <DashboardContainer/>} { presentation && <PresentationContainer/>} </div> ) }
identifier_body
sessionQuizView.tsx
import * as React from "react"; import { connect } from "react-redux"; import { Link } from "react-router" import * as MediaQuery from "react-responsive" import DashboardContainer from "../../containers/dashboard/dashboardContainer" import PresentationContainer from "../../containers/dashboard/presentationContainer" import RemoteContainer from "../../containers/quiz/remoteContainer" export interface StateProps { rooms: { id: number, teacher: string}[] isTeacher: boolean roomOwner: string } export interface ActionProps { updateRooms() joinRoom(roomId: number) leaveRoom() closeRoom() openRoom() } type Props = StateProps & ActionProps; export class View extends React.Component<Props, any> { props: Props render() { const { rooms,
joinRoom, leaveRoom, closeRoom, openRoom } = this.props let dashboard: boolean = (this.props as any).location.pathname == "/dashboard", presentation: boolean = (this.props as any).location.pathname == "/presentation", remote: boolean = (this.props as any).location.pathname == "/remote" return ( <div> <div> <button onClick={ updateRooms }>Update rooms</button> <button onClick={ leaveRoom }>Leave room</button> { roomOwner != null && <button onClick={ closeRoom }>Close room</button> } { isTeacher && <button onClick={ openRoom }>Open room</button> } Current room: { roomOwner != null ? roomOwner : "none" } <br/> { rooms.map(room => { return <button key={ room.id } onClick={ () => joinRoom(room.id) }> Join Room { room.teacher } </button> })} </div> { remote && <RemoteContainer/>} { dashboard && <DashboardContainer/>} { presentation && <PresentationContainer/>} </div> ) } }
isTeacher, roomOwner, updateRooms,
random_line_split
sessionQuizView.tsx
import * as React from "react"; import { connect } from "react-redux"; import { Link } from "react-router" import * as MediaQuery from "react-responsive" import DashboardContainer from "../../containers/dashboard/dashboardContainer" import PresentationContainer from "../../containers/dashboard/presentationContainer" import RemoteContainer from "../../containers/quiz/remoteContainer" export interface StateProps { rooms: { id: number, teacher: string}[] isTeacher: boolean roomOwner: string } export interface ActionProps { updateRooms() joinRoom(roomId: number) leaveRoom() closeRoom() openRoom() } type Props = StateProps & ActionProps; export class View extends React.Component<Props, any> { props: Props
() { const { rooms, isTeacher, roomOwner, updateRooms, joinRoom, leaveRoom, closeRoom, openRoom } = this.props let dashboard: boolean = (this.props as any).location.pathname == "/dashboard", presentation: boolean = (this.props as any).location.pathname == "/presentation", remote: boolean = (this.props as any).location.pathname == "/remote" return ( <div> <div> <button onClick={ updateRooms }>Update rooms</button> <button onClick={ leaveRoom }>Leave room</button> { roomOwner != null && <button onClick={ closeRoom }>Close room</button> } { isTeacher && <button onClick={ openRoom }>Open room</button> } Current room: { roomOwner != null ? roomOwner : "none" } <br/> { rooms.map(room => { return <button key={ room.id } onClick={ () => joinRoom(room.id) }> Join Room { room.teacher } </button> })} </div> { remote && <RemoteContainer/>} { dashboard && <DashboardContainer/>} { presentation && <PresentationContainer/>} </div> ) } }
render
identifier_name
cart-monitor.js
/** * Watches for changes to the quantity of items in the shopping cart, to update * cart count indicators on the storefront. */ define(['modules/jquery-mozu', 'modules/api'], function ($, api) { $(document).ready(function () { var $cartCount = $('[data-mz-role="cartmonitor"]'), timeout; function waitAndGetCart() { return setTimeout(function() { api.get('cartsummary').then(function (summary) { updateCartCount(summary.count()); }); }, 500); } function checkForCartUpdates(apiObject) { if (!apiObject || !apiObject.type) return; switch (apiObject.type) { case "cart": case "cart-summary": clearTimeout(timeout); updateCartCount(apiObject.count() || 0); break; case "cartitem": if (!apiObject.unsynced) timeout = waitAndGetCart(); break; } } function updateCartCount(count) {
api.on('sync', checkForCartUpdates); api.on('spawn', checkForCartUpdates); var savedCount = $.cookie('mozucartcount'); if (savedCount === null) waitAndGetCart(); $cartCount.text(savedCount || 0); }); });
$cartCount.text(count); $.cookie('mozucartcount', count, { path: '/' }); }
identifier_body
cart-monitor.js
/** * Watches for changes to the quantity of items in the shopping cart, to update * cart count indicators on the storefront.
var $cartCount = $('[data-mz-role="cartmonitor"]'), timeout; function waitAndGetCart() { return setTimeout(function() { api.get('cartsummary').then(function (summary) { updateCartCount(summary.count()); }); }, 500); } function checkForCartUpdates(apiObject) { if (!apiObject || !apiObject.type) return; switch (apiObject.type) { case "cart": case "cart-summary": clearTimeout(timeout); updateCartCount(apiObject.count() || 0); break; case "cartitem": if (!apiObject.unsynced) timeout = waitAndGetCart(); break; } } function updateCartCount(count) { $cartCount.text(count); $.cookie('mozucartcount', count, { path: '/' }); } api.on('sync', checkForCartUpdates); api.on('spawn', checkForCartUpdates); var savedCount = $.cookie('mozucartcount'); if (savedCount === null) waitAndGetCart(); $cartCount.text(savedCount || 0); }); });
*/ define(['modules/jquery-mozu', 'modules/api'], function ($, api) { $(document).ready(function () {
random_line_split
cart-monitor.js
/** * Watches for changes to the quantity of items in the shopping cart, to update * cart count indicators on the storefront. */ define(['modules/jquery-mozu', 'modules/api'], function ($, api) { $(document).ready(function () { var $cartCount = $('[data-mz-role="cartmonitor"]'), timeout; function waitAndGetCart() { return setTimeout(function() { api.get('cartsummary').then(function (summary) { updateCartCount(summary.count()); }); }, 500); } function checkForCartUpdates(apiObject) { if (!apiObject || !apiObject.type) return; switch (apiObject.type) { case "cart": case "cart-summary": clearTimeout(timeout); updateCartCount(apiObject.count() || 0); break; case "cartitem": if (!apiObject.unsynced) timeout = waitAndGetCart(); break; } } function up
ount) { $cartCount.text(count); $.cookie('mozucartcount', count, { path: '/' }); } api.on('sync', checkForCartUpdates); api.on('spawn', checkForCartUpdates); var savedCount = $.cookie('mozucartcount'); if (savedCount === null) waitAndGetCart(); $cartCount.text(savedCount || 0); }); });
dateCartCount(c
identifier_name
camera.py
#!/usr/bin/python3.7 import ssl import remi.gui as gui from remi import start, App class Camera(App): def __init__(self, *args, **kwargs): super(Camera, self).__init__(*args) def video_widgets(self): width = '300' height = '300' self.video = gui.Widget(_type='video') self.video.style['overflow'] = 'hidden' self.video.attributes['autoplay'] = 'true' self.video.attributes['width'] = width self.video.attributes['height'] = height def video_start(self, widget, callback_function): self.execute_javascript(""" var params={}; var frame = 0; document.video_stop = false; const video = document.querySelector('video'); video.setAttribute("playsinline", true); const canvas = document.createElement('canvas'); navigator.mediaDevices.getUserMedia({video: { facingMode: { ideal: "environment" } }, audio: false}). then((stream) => {video.srcObject = stream}); const render = () => { if (document.video_stop) { return; } if (frame==30) { canvas.width = video.videoWidth; canvas.height = video.videoHeight; canvas.getContext('2d').drawImage(video, 0, 0); params['image']=canvas.toDataURL() remi.sendCallbackParam('%(id)s','%(callback_function)s',params) frame = 0; } frame+=1; requestAnimationFrame(render); } requestAnimationFrame(render); """%{'id':str(id(self)), 'callback_function': str(callback_function)}) def video_stop(self, widget): self.execute_javascript(""" document.video_stop = true; const video = document.querySelector('video'); video.srcObject.getTracks()[0].stop(); """) def process_image(self, **kwargs): image = kwargs['image'] print('I am here') ### Do whatever you want with the image here return def main(self): self.video_widgets() screen = [self.video] start_button = gui.Button('Start Video') start_button.onclick.do(self.video_start, 'process_image') screen.append(start_button) stop_button = gui.Button('Stop Video') stop_button.onclick.do(self.video_stop) screen.append(stop_button) return gui.VBox(children=screen) if __name__ == "__main__":
# certfile='./ssl_keys/fullchain.pem', # keyfile='./ssl_keys/privkey.pem', # ssl_version=ssl.PROTOCOL_TLSv1_2,
start(Camera, address='0.0.0.0', port=2020, multiple_instance=True, enable_file_cache=True, start_browser=False, debug=False)
conditional_block
camera.py
#!/usr/bin/python3.7 import ssl import remi.gui as gui from remi import start, App class Camera(App): def __init__(self, *args, **kwargs): super(Camera, self).__init__(*args) def video_widgets(self): width = '300' height = '300' self.video = gui.Widget(_type='video') self.video.style['overflow'] = 'hidden' self.video.attributes['autoplay'] = 'true' self.video.attributes['width'] = width self.video.attributes['height'] = height def video_start(self, widget, callback_function): self.execute_javascript(""" var params={}; var frame = 0; document.video_stop = false; const video = document.querySelector('video'); video.setAttribute("playsinline", true); const canvas = document.createElement('canvas'); navigator.mediaDevices.getUserMedia({video: { facingMode: { ideal: "environment" } }, audio: false}). then((stream) => {video.srcObject = stream}); const render = () => { if (document.video_stop) { return; } if (frame==30) { canvas.width = video.videoWidth; canvas.height = video.videoHeight; canvas.getContext('2d').drawImage(video, 0, 0); params['image']=canvas.toDataURL() remi.sendCallbackParam('%(id)s','%(callback_function)s',params) frame = 0; } frame+=1; requestAnimationFrame(render); } requestAnimationFrame(render); """%{'id':str(id(self)), 'callback_function': str(callback_function)}) def video_stop(self, widget): self.execute_javascript(""" document.video_stop = true; const video = document.querySelector('video'); video.srcObject.getTracks()[0].stop();
print('I am here') ### Do whatever you want with the image here return def main(self): self.video_widgets() screen = [self.video] start_button = gui.Button('Start Video') start_button.onclick.do(self.video_start, 'process_image') screen.append(start_button) stop_button = gui.Button('Stop Video') stop_button.onclick.do(self.video_stop) screen.append(stop_button) return gui.VBox(children=screen) if __name__ == "__main__": start(Camera, address='0.0.0.0', port=2020, multiple_instance=True, enable_file_cache=True, start_browser=False, debug=False) # certfile='./ssl_keys/fullchain.pem', # keyfile='./ssl_keys/privkey.pem', # ssl_version=ssl.PROTOCOL_TLSv1_2,
""") def process_image(self, **kwargs): image = kwargs['image']
random_line_split
camera.py
#!/usr/bin/python3.7 import ssl import remi.gui as gui from remi import start, App class Camera(App): def __init__(self, *args, **kwargs): super(Camera, self).__init__(*args) def video_widgets(self): width = '300' height = '300' self.video = gui.Widget(_type='video') self.video.style['overflow'] = 'hidden' self.video.attributes['autoplay'] = 'true' self.video.attributes['width'] = width self.video.attributes['height'] = height def video_start(self, widget, callback_function):
def video_stop(self, widget): self.execute_javascript(""" document.video_stop = true; const video = document.querySelector('video'); video.srcObject.getTracks()[0].stop(); """) def process_image(self, **kwargs): image = kwargs['image'] print('I am here') ### Do whatever you want with the image here return def main(self): self.video_widgets() screen = [self.video] start_button = gui.Button('Start Video') start_button.onclick.do(self.video_start, 'process_image') screen.append(start_button) stop_button = gui.Button('Stop Video') stop_button.onclick.do(self.video_stop) screen.append(stop_button) return gui.VBox(children=screen) if __name__ == "__main__": start(Camera, address='0.0.0.0', port=2020, multiple_instance=True, enable_file_cache=True, start_browser=False, debug=False) # certfile='./ssl_keys/fullchain.pem', # keyfile='./ssl_keys/privkey.pem', # ssl_version=ssl.PROTOCOL_TLSv1_2,
self.execute_javascript(""" var params={}; var frame = 0; document.video_stop = false; const video = document.querySelector('video'); video.setAttribute("playsinline", true); const canvas = document.createElement('canvas'); navigator.mediaDevices.getUserMedia({video: { facingMode: { ideal: "environment" } }, audio: false}). then((stream) => {video.srcObject = stream}); const render = () => { if (document.video_stop) { return; } if (frame==30) { canvas.width = video.videoWidth; canvas.height = video.videoHeight; canvas.getContext('2d').drawImage(video, 0, 0); params['image']=canvas.toDataURL() remi.sendCallbackParam('%(id)s','%(callback_function)s',params) frame = 0; } frame+=1; requestAnimationFrame(render); } requestAnimationFrame(render); """%{'id':str(id(self)), 'callback_function': str(callback_function)})
identifier_body
camera.py
#!/usr/bin/python3.7 import ssl import remi.gui as gui from remi import start, App class Camera(App): def __init__(self, *args, **kwargs): super(Camera, self).__init__(*args) def video_widgets(self): width = '300' height = '300' self.video = gui.Widget(_type='video') self.video.style['overflow'] = 'hidden' self.video.attributes['autoplay'] = 'true' self.video.attributes['width'] = width self.video.attributes['height'] = height def video_start(self, widget, callback_function): self.execute_javascript(""" var params={}; var frame = 0; document.video_stop = false; const video = document.querySelector('video'); video.setAttribute("playsinline", true); const canvas = document.createElement('canvas'); navigator.mediaDevices.getUserMedia({video: { facingMode: { ideal: "environment" } }, audio: false}). then((stream) => {video.srcObject = stream}); const render = () => { if (document.video_stop) { return; } if (frame==30) { canvas.width = video.videoWidth; canvas.height = video.videoHeight; canvas.getContext('2d').drawImage(video, 0, 0); params['image']=canvas.toDataURL() remi.sendCallbackParam('%(id)s','%(callback_function)s',params) frame = 0; } frame+=1; requestAnimationFrame(render); } requestAnimationFrame(render); """%{'id':str(id(self)), 'callback_function': str(callback_function)}) def video_stop(self, widget): self.execute_javascript(""" document.video_stop = true; const video = document.querySelector('video'); video.srcObject.getTracks()[0].stop(); """) def process_image(self, **kwargs): image = kwargs['image'] print('I am here') ### Do whatever you want with the image here return def
(self): self.video_widgets() screen = [self.video] start_button = gui.Button('Start Video') start_button.onclick.do(self.video_start, 'process_image') screen.append(start_button) stop_button = gui.Button('Stop Video') stop_button.onclick.do(self.video_stop) screen.append(stop_button) return gui.VBox(children=screen) if __name__ == "__main__": start(Camera, address='0.0.0.0', port=2020, multiple_instance=True, enable_file_cache=True, start_browser=False, debug=False) # certfile='./ssl_keys/fullchain.pem', # keyfile='./ssl_keys/privkey.pem', # ssl_version=ssl.PROTOCOL_TLSv1_2,
main
identifier_name
CellularEmporium.tsx
import { useBackend } from '../backend'; import { Button, Section, Icon, Stack, LabeledList, Box, NoticeBox } from '../components'; import { Window } from '../layouts';
can_readapt: boolean; genetic_points_remaining: number; } type Ability = { name: string; desc: string; dna_cost: number; helptext: string; owned: boolean; } export const CellularEmporium = (props, context) => { const { act, data } = useBackend<CellularEmporiumContext>(context); const { can_readapt, genetic_points_remaining } = data; return ( <Window width={900} height={480}> <Window.Content> <Section fill scrollable title={"Genetic Points"} buttons={ <Stack> <Stack.Item fontSize="16px"> {genetic_points_remaining && genetic_points_remaining}{' '} <Icon name="dna" color="#DD66DD" /> </Stack.Item> <Stack.Item> <Button icon="undo" content="Readapt" disabled={!can_readapt} onClick={() => act('readapt')} /> </Stack.Item> </Stack> }><AbilityList /> </Section> </Window.Content> </Window> ); }; const AbilityList = (props, context) => { const { act, data } = useBackend<CellularEmporiumContext>(context); const { abilities, genetic_points_remaining } = data; if (!abilities) { return <NoticeBox>None</NoticeBox>; } else { return ( <LabeledList> {abilities.map(ability => ( <LabeledList.Item key={ability.name} className="candystripe" label={ability.name} buttons={( <Stack> <Stack.Item> {ability.dna_cost} </Stack.Item> <Stack.Item> <Icon name="dna" color={ability.owned ? "#DD66DD" : "gray"} /> </Stack.Item> <Stack.Item> <Button content={'Evolve'} disabled={ability.owned || ability.dna_cost > genetic_points_remaining} onClick={() => act('evolve', { name: ability.name, })} /> </Stack.Item> </Stack> )}> {ability.desc} <Box color="good"> {ability.helptext} </Box> </LabeledList.Item> ))} </LabeledList>); } };
type CellularEmporiumContext = { abilities: Ability[];
random_line_split
patient.medication.component.ts
import { Router, ActivatedRoute, Params } from '@angular/router'; import { Component } from '@angular/core'; import { Apollo } from 'apollo-angular'; import gql from 'graphql-tag'; interface QueryResponse { patient loading } interface PatientMedication { name: string; dose: string; prescribedOn: string; }
export class PatientMedicationComponent { public patientMedications: PatientMedication[]; public loading: boolean; id: string; constructor(private apollo: Apollo, private activatedRoute: ActivatedRoute) { } ngOnInit() { this.activatedRoute.params.subscribe((params: Params) => { this.id = params['id']; this.apollo.query<QueryResponse>({ query: gql` query { patient(nhsNumber:"${this.id}"){medications{name,dose,prescribedOn}}}` }).subscribe(({ data }) => { this.loading = data.loading; this.patientMedications = data.patient.medications; }); }); } }
@Component({ selector: 'patient-medication', templateUrl: './patient.medication.component.html' })
random_line_split
patient.medication.component.ts
import { Router, ActivatedRoute, Params } from '@angular/router'; import { Component } from '@angular/core'; import { Apollo } from 'apollo-angular'; import gql from 'graphql-tag'; interface QueryResponse { patient loading } interface PatientMedication { name: string; dose: string; prescribedOn: string; } @Component({ selector: 'patient-medication', templateUrl: './patient.medication.component.html' }) export class PatientMedicationComponent { public patientMedications: PatientMedication[]; public loading: boolean; id: string; constructor(private apollo: Apollo, private activatedRoute: ActivatedRoute)
ngOnInit() { this.activatedRoute.params.subscribe((params: Params) => { this.id = params['id']; this.apollo.query<QueryResponse>({ query: gql` query { patient(nhsNumber:"${this.id}"){medications{name,dose,prescribedOn}}}` }).subscribe(({ data }) => { this.loading = data.loading; this.patientMedications = data.patient.medications; }); }); } }
{ }
identifier_body
patient.medication.component.ts
import { Router, ActivatedRoute, Params } from '@angular/router'; import { Component } from '@angular/core'; import { Apollo } from 'apollo-angular'; import gql from 'graphql-tag'; interface QueryResponse { patient loading } interface PatientMedication { name: string; dose: string; prescribedOn: string; } @Component({ selector: 'patient-medication', templateUrl: './patient.medication.component.html' }) export class PatientMedicationComponent { public patientMedications: PatientMedication[]; public loading: boolean; id: string; constructor(private apollo: Apollo, private activatedRoute: ActivatedRoute) { }
() { this.activatedRoute.params.subscribe((params: Params) => { this.id = params['id']; this.apollo.query<QueryResponse>({ query: gql` query { patient(nhsNumber:"${this.id}"){medications{name,dose,prescribedOn}}}` }).subscribe(({ data }) => { this.loading = data.loading; this.patientMedications = data.patient.medications; }); }); } }
ngOnInit
identifier_name
token.py
#!/usr/bin/python # -*- coding: utf-8 -*- import mysql.connector #from token find userId #return 0 for error def findUser(userToken, cnx): userQuery = 'SELECT user_id FROM user_token WHERE user_token = %s' try: userCursor = cnx.cursor() userCursor.execute(userQuery, (userToken, )) return userCursor.fetchone() #return 0 for db error except mysql.connector.Error as err: print('Something went wrong: {}'.format(err)) return '0' finally: userCursor.close() #create new token #return 1 for success #return 0 for error def addToken(userId, userToken, cnx):
#delete token #return 1 for success #return 0 for fail def deleteToken(userId, cnx): cleanQuery = 'DELETE FROM user_token WHERE user_id = %s' try: cleanCursor = cnx.cursor() cleanCursor.execute(cleanQuery, (userId, )) cnx.commit() return '1' except mysql.connector.Error as err: cnx.rollback() print('Something went wrong: {}'.format(err)) return '0' finally: cleanCursor.close()
addQuery = 'INSERT INTO user_token (user_id, user_token) VALUES (%s, %s) ON DUPLICATE KEY UPDATE user_token = %s' try: addCursor = cnx.cursor() addCursor.execute(addQuery, (userId, userToken, userToken)) cnx.commit() return '1' except mysql.connector.Error as err: print('Something went wrong: {}'.format(err)) cnx.rollback() return '0' finally: addCursor.close()
identifier_body
token.py
#!/usr/bin/python # -*- coding: utf-8 -*- import mysql.connector #from token find userId #return 0 for error def findUser(userToken, cnx): userQuery = 'SELECT user_id FROM user_token WHERE user_token = %s' try: userCursor = cnx.cursor() userCursor.execute(userQuery, (userToken, )) return userCursor.fetchone() #return 0 for db error except mysql.connector.Error as err: print('Something went wrong: {}'.format(err)) return '0' finally: userCursor.close() #create new token #return 1 for success #return 0 for error def addToken(userId, userToken, cnx): addQuery = 'INSERT INTO user_token (user_id, user_token) VALUES (%s, %s) ON DUPLICATE KEY UPDATE user_token = %s' try:
addCursor = cnx.cursor() addCursor.execute(addQuery, (userId, userToken, userToken)) cnx.commit() return '1' except mysql.connector.Error as err: print('Something went wrong: {}'.format(err)) cnx.rollback() return '0' finally: addCursor.close() #delete token #return 1 for success #return 0 for fail def deleteToken(userId, cnx): cleanQuery = 'DELETE FROM user_token WHERE user_id = %s' try: cleanCursor = cnx.cursor() cleanCursor.execute(cleanQuery, (userId, )) cnx.commit() return '1' except mysql.connector.Error as err: cnx.rollback() print('Something went wrong: {}'.format(err)) return '0' finally: cleanCursor.close()
random_line_split