Esempio n. 1
0
def draw_field(v: FieldView,
               locale: Locale,
               theme: Theme,
               numbers_right: bool = False,
               border: bool = False):

    name_label, view = v
    header = py_.chain(locale.value).map_(
        lambda x: "{: ^{}}".format(x, CELL_WIDTH)).join().value()
    name_header = '{:<{}}'.format(name_label, CELL_WIDTH * len(locale.value))
    if numbers_right:
        name_header = ' '.join([name_header, ' ' * CELL_WIDTH])
        header = ' '.join([header, ' ' * CELL_WIDTH])
    else:
        header = ' '.join([' ' * CELL_WIDTH, header])
        name_header = ' '.join([' ' * CELL_WIDTH, name_header])

    sub_header = None
    if border:
        sub_header = "─" * CELL_WIDTH * len(locale.value)
        if numbers_right:
            sub_header += '─┐ ' + ' ' * CELL_WIDTH
            header += '  '
            name_header += '  '

        else:
            sub_header = ' ' * CELL_WIDTH + ' ┌─' + sub_header
            header = '  ' + header
            name_header = '  ' + name_header

    raw_rows = py_.map_(
        view, lambda row: py_.chain(row).map_(theme.value.get).join().value())
    line_numbers_fmt = '{{: {}{}}}'.format('<' if numbers_right else '>',
                                           CELL_WIDTH)
    line_numbers = py_.map_(list(range(1, FIELD_DIMENSIONS.i + 1)),
                            line_numbers_fmt.format)
    if numbers_right:
        columns = py_.zip_(raw_rows, line_numbers)
    else:
        columns = py_.zip_(line_numbers, raw_rows)

    column_separator = ' '
    if border:
        column_separator = ' │ '
    lines = [name_header, header]
    if border:
        lines.append(sub_header)
    lines += py_.map_(columns, column_separator.join)

    return py_.join(lines, '\n')
Esempio n. 2
0
def group_by_keys(dicts: Iterable[Dict[str, T]], default_value: Optional[T] = None) -> Dict[str, List[T]]:
    all_keys = py_.chain(dicts).flat_map(lambda d: list(d.keys())).uniq().value()
    # ^ это эквивалентно вот этому:
    # all_keys = py_.flat_map(dicts, lambda d: list(d.keys()))
    # all_keys = py_.uniq(all_keys)

    values = py_.map_(all_keys, lambda key: py_.invoke_map(dicts, 'get', key, default_value))
    return py_.zip_object(all_keys, values)
Esempio n. 3
0
def micro_draw(target_view: FieldView, current_view: FieldView,
               **kwargs) -> str:

    draw_left = draw_field(target_view, numbers_right=False,
                           **kwargs).split('\n')
    draw_right = draw_field(current_view, numbers_right=True,
                            **kwargs).split('\n')

    lines = py_.zip_(draw_left, draw_right)
    combo_lines = py_.map_(lines, lambda pair: ' : '.join(pair))
    return '\n'.join(combo_lines)
Esempio n. 4
0
    def handle_geo_near(session, aConfig, querydict, user_id):
        def calc_dist(p1,  p2):
            po1 = tuple((p1[1], p1[0]))
            po2 = tuple((p2[1], p2[0]))
            return int(great_circle(po1, po2).m)

        statuscode, mimetype, body = 200, 'text/json', '{}'
        app = aConfig['gConfig']['wsgi']['application']
        db, collection = get_collection(aConfig, app, 'main', 'collection_features')
        limit = 100
        if 'limit' in querydict and isinstance(querydict['limit'], int):
            limit = querydict['limit']
        if 'geometry' in querydict:
            geojsonobj = querydict['geometry']
            if isinstance(geojsonobj, str) :
                try:
                    geojsonobj = json.loads(geojsonobj)
                except:
                    geojsonobj = {}
            if 'type' in geojsonobj:
                cond = {'geometry2d': {'$nearSphere': {'$geometry': geojsonobj}}}
                if 'webgis_type' in querydict:
                    if isinstance(querydict['webgis_type'], str) :
                        cond['properties.webgis_type'] = querydict['webgis_type']
                    if isinstance(querydict['webgis_type'], list):
                        cond['properties.webgis_type'] = {'$in': querydict['webgis_type']}
                minDistance = 0
                maxDistance = 0
                if 'min_distance' in querydict and (isinstance(querydict['min_distance'], float) or isinstance(querydict['min_distance'], int)):
                    minDistance = querydict['min_distance']
                if 'max_distance' in querydict and (isinstance(querydict['max_distance'], float) or isinstance(querydict['max_distance'], int)):
                    maxDistance = querydict['max_distance']
                cond['geometry2d']['$nearSphere']['$minDistance'] = minDistance
                cond['geometry2d']['$nearSphere']['$maxDistance'] = maxDistance
                arr = remove_mongo_id(list(collection.find(cond).limit(limit)))

                if 'is_calc_dist' in querydict and (querydict['is_calc_dist'] is True or querydict['is_calc_dist'].lower() == 'true'):
                    if geojsonobj['type'] == 'Point':
                        def get_dist(x = {}):
                            x['properties']['calc_dist'] = calc_dist(geojsonobj['coordinates'], x['geometry']['coordinates'])
                            return x
                        arr = _.map_(arr, get_dist)



                body = json.dumps(arr, ensure_ascii=True, indent=4)
            else:
                body = json.dumps({'result': 'geometry_geojson_required'}, ensure_ascii=True, indent=4)
        else:
            body = json.dumps({'result': 'geometry_required'}, ensure_ascii=True, indent=4)
        return statuscode, mimetype, body
Esempio n. 5
0
def find_sftp_server(client, server_name):
    # Finding a server by name is a little more complicated than I originally expected.  Rather than wasting resources
    # it's much easier to just go find it and then check if the return value of this method is None.
    # Load all of the server IDs in the account
    all_server_ids = py_.map(client.list_servers()['Servers'], 'ServerId')
    all_servers = py_.map_(
        all_server_ids,
        (lambda server_id: client.describe_server(ServerId=server_id)))
    host = py_.find(
        all_servers,
        {'Server': {
            'Tags': [{
                'Key': SERVER_NAME_KEY,
                'Value': server_name
            }]
        }})
    return host
Esempio n. 6
0
    def _try_place(acc: MatrixInt, desired_length: int) -> MatrixInt:
        available_cells = get_available_cells(acc, FIELD_DIMENSIONS)
        segments = find_straight_segments(available_cells, True) + \
            find_straight_segments(available_cells, False)

        available_segments = py_.filter_(
            segments, lambda segment: len(segment) >= desired_length)
        chosen_segment = choice(available_segments)

        len_diff = len(chosen_segment) - desired_length
        available_subsegments = py_.map_(
            list(range(len_diff + 1)),
            lambda x: chosen_segment[x:x + desired_length])
        chosen_subsegment = choice(available_subsegments)

        new_field = py_.clone_deep(acc)
        for c in chosen_subsegment:
            new_field[c.i][c.j] = CellState.CELL_DECK.value

        return new_field
Esempio n. 7
0
def handler(event, context):
    url = 'https://api.github.com/repos/stedolan/jq/commits?per_page=50'

    params = dict(Headers='User-Agent: request')

    response = requests.get(url=url, params=params)
    data = response.json()

    filtered = py_.filter(data,
                          {'commit.author.name' == 'commit.committer.name'})
    shas = py_.map_(filtered, '.sha')

    # print(json.dumps(shas, indent=2))
    return {
        'statusCode': 200,
        'body': json.dumps(shas),
        'headers': {
            'Content-Type': 'application/json'
        }
    }
Esempio n. 8
0
def make_ship_from_str(string: str, locale: Locale) -> Ship:

    alpha = locale.value
    pattern = r'^([{}])(\d+)(?:([{}])(\d+))?$'.format(alpha, alpha)
    findings = findall(pattern, string)
    assert findings, 'Incorrect input'

    ship = py_.map_(findings[0],
                    lambda item: to_cell_coordinates(item, locale))
    if ship[2] is None:
        # single deck ship
        assert 0 <= ship[1] < FIELD_DIMENSIONS.i, 'Incorrect input'
        assert 0 <= ship[0] < FIELD_DIMENSIONS.j, 'Incorrect input'
        coord = Coord((ship[1], ship[0]))
        return Ship([coord])

    else:
        assert 0 <= ship[1] < FIELD_DIMENSIONS.i, 'Incorrect input'
        assert 0 <= ship[0] < FIELD_DIMENSIONS.j, 'Incorrect input'
        assert 0 <= ship[3] < FIELD_DIMENSIONS.i, 'Incorrect input'
        assert 0 <= ship[2] < FIELD_DIMENSIONS.j, 'Incorrect input'

        start = Coord((ship[1], ship[0]))
        finish = Coord((ship[3], ship[2]))
        diff = finish - start
        if diff.i and diff.j:
            raise Exception('Ship should be a straight line')

        if diff.i == 0:  # vertical
            increment = Coord((0, 1))
        else:  # horizontal
            increment = Coord((1, 0))

        ship = []
        current = start
        while current != finish:
            ship.append(current)
            current += increment

        ship.append(finish)
        return Ship(ship)
Esempio n. 9
0
 def find_JSerror(self, driver, title=None):
     error = driver.get_log('browser')
     result = 'nothing'
     if len(error) != 0:
         try:
             message = py_.map_(error, 'message')
             str1 = ''.join(str(e) for e in message)
             message = str1.replace('()', '<br>')
             refresh_condition = "Failed to load resource: the server responded with a status of"
             if re.findall(refresh_condition, message):
                 driver.refresh()
             else:
                 if title == None:
                     driver.assert_exist("//body", "xpath", "有JSError! ")
                 else:
                     driver.assert_exist("//body", "xpath",
                                         "有JSError! : %s" % title)
                 result = 'warning'
                 assert_equal(False, True, "JSerror:<br>%s" % (message))
         except:
             pass
         finally:
             return result
Esempio n. 10
0
def pi_internal_sensor_queue_send_loop(aConfig):
    global gQueueSensor, gWebSocketConnection, gSensorControl, gSensorData

    def computeHeight(pressure):
        return 44330.8 * (1 - pow(pressure / 1013.25, 0.190263))

    def get_sensor_data(aConfig, key, device_serial_no, sensor_type, serial_no):
        global gSensorData
        ret = None
        if key == 'DOF10':
            if key in gSensorData and len(list(gSensorData[key].keys())):
                # print(gSensorData['DOF10'])
                ret = {
                    'type': sensor_type,
                    'device_serial_no': device_serial_no,
                    'serial_no': serial_no,
                    'timestamp': datetime.datetime.now(),
                    'value': {
                        'temp': float('{0:.1f}'.format(gSensorData['DOF10']['temperature'])),
                        'ypr': {
                            'yaw': float('{0:.5f}'.format(gSensorData['DOF10']['fusionPose'][2])),
                            'pitch': float('{0:.5f}'.format(gSensorData['DOF10']['fusionPose'][1])),
                            'roll': float('{0:.5f}'.format(gSensorData['DOF10']['fusionPose'][0])),
                        },
                        'quat':{
                            'w':float('{0:.5f}'.format(gSensorData['DOF10']['fusionQPose'][0])),
                            'x': float('{0:.5f}'.format(gSensorData['DOF10']['fusionQPose'][1])),
                            'y': float('{0:.5f}'.format(gSensorData['DOF10']['fusionQPose'][2])),
                            'z': float('{0:.5f}'.format(gSensorData['DOF10']['fusionQPose'][3])),
                        },
                        'height': float('{0:.1f}'.format(computeHeight(gSensorData['DOF10']['pressure']))),
                        'pressure': float('{0:.1f}'.format(gSensorData['DOF10']['pressure'])),
                    },
                    'op': OPERATOR['OP_TRANSFER'],
                }
        elif key.lower() == 'battery':
            if key in gSensorData and len(list(gSensorData[key].keys())):
                ret = {
                    'type': sensor_type,
                    'device_serial_no': device_serial_no,
                    'serial_no': serial_no,
                    'timestamp': datetime.datetime.now(),
                    'value': {
                        'bus_voltage': float('{0:.2f}'.format(gSensorData['battery']['bus_voltage'])),
                        'current': float('{0:.2f}'.format(gSensorData['battery']['current'])),
                        'power': float('{0:.2f}'.format(gSensorData['battery']['power'])),
                    },
                    'op': OPERATOR['OP_TRANSFER'],
                }
        return ret

    # def get_sensor_device(aConfig, key):
    #     ret = None
    #     if key == 'DOF10':
    #         try:
    #             import RTIMU
    #         except:
    #             print('RTIMU import error')
    #             return ret
    #         SETTINGS_FILE = "RTIMU_CONFIG"
    #         print("Using settings file [%s.ini]" % SETTINGS_FILE)
    #         if not os.path.exists(SETTINGS_FILE + ".ini"):
    #             print("Settings file does not exist, will be created")
    #         setting = RTIMU.Settings(SETTINGS_FILE)
    #         imu = RTIMU.RTIMU(setting)
    #         pressure = RTIMU.RTPressure(setting)
    #
    #         print("IMU Name: " + imu.IMUName())
    #         print("Pressure Name: " + pressure.pressureName())
    #         if (not imu.IMUInit()):
    #             print("IMU Init Failed")
    #             return None
    #         else:
    #             print("IMU Init Succeeded");
    #
    #             imu.setSlerpPower(0.02)
    #             imu.setGyroEnable(True)
    #             imu.setAccelEnable(True)
    #             imu.setCompassEnable(True)
    #
    #         if (not pressure.pressureInit()):
    #             print("Pressure sensor Init Failed")
    #             return None
    #         else:
    #             print("Pressure sensor Init Succeeded")
    #             ret = {
    #                 'imu': imu,
    #                 'pressure': pressure,
    #             }
    #     return ret

    def register(aConfig, device_serial_no, sensor_type, serial_no, wsurl):
        global gSensorControl, gWebSocketConnection
        try:
            if gWebSocketConnection is None:
                # print(wsurl)
                gWebSocketConnection = pi_create_websocket(wsurl)
            if gWebSocketConnection and not gWebSocketConnection.connected:
                gWebSocketConnection.connect(wsurl, sslopt={"cert_reqs": ssl.CERT_NONE, "check_hostname": False})
            if gWebSocketConnection and gWebSocketConnection.connected:
                item = {
                    'device_serial_no': device_serial_no,
                    'serial_no': serial_no,
                    'op': OPERATOR['OP_REGISTER'],
                    'type': sensor_type,
                    'enable':True,
                    'is_internal': True,
                    'interval': 1.0,
                }
                gWebSocketConnection.send(json.dumps(item, ensure_ascii=True))

        except Exception as e:
            print(e)
            print('register failed')

    def rtimulib_loop(serial_no):
        global gSensorControl, gSensorData
        try:
            import RTIMU
        except:
            print('RTIMU import error')
            return
        SETTINGS_FILE = "RTIMU_CONFIG"
        print("Using settings file [%s.ini]" % SETTINGS_FILE)
        if not os.path.exists(SETTINGS_FILE + ".ini"):
            print("Settings file does not exist, will be created")
        setting = RTIMU.Settings(SETTINGS_FILE)
        imu = RTIMU.RTIMU(setting)
        pressure = RTIMU.RTPressure(setting)

        print("IMU Name: " + imu.IMUName())
        print("Pressure Name: " + pressure.pressureName())
        if (not imu.IMUInit()):
            print("IMU Init Failed")
            return
        else:
            print("IMU Init Succeeded");

            imu.setSlerpPower(0.02)
            imu.setGyroEnable(True)
            imu.setAccelEnable(True)
            imu.setCompassEnable(True)

        if (not pressure.pressureInit()):
            print("Pressure sensor Init Failed")
            return None

        interval = float(imu.IMUGetPollInterval())
        if not 'DOF10' in gSensorData:
            gSensorData['DOF10'] = {}
        while True:
            sensor = _.find(gSensorControl['sensors'], {'serial_no': serial_no})
            if sensor and (sensor['enable'] is True or sensor['enable'].lower() == 'true'):
                if imu.IMURead():
                    gSensorData['DOF10'] = imu.getIMUData()
                    (gSensorData['DOF10']['pressureValid'], gSensorData['DOF10']['pressure'], gSensorData['DOF10']['temperatureValid'],gSensorData['DOF10']['temperature']) = pressure.pressureRead()

            else:
                interval = 1000.0
            gevent.sleep(interval / 1000.0)

    def pigpio_loop(key, i2c_addr, serial_no):
        global gSensorControl, gSensorData, aConfig
        try:
            import pigpio
        except:
            print('pigpio import error')
            return
        if key == 'battery':
            from INA226 import INA226Device
            ina226 = None
            try:
                ina226 = INA226Device(address=i2c_addr, initdata={'max_current_excepted':12})
            except Exception as e:
                print (e)
                return
            if ina226:
                if not 'battery' in gSensorData:
                    gSensorData['battery'] = {}
                interval = 1000.0
                while True:
                    sensor = _.find(gSensorControl['sensors'], {'serial_no': serial_no})
                    if sensor and (sensor['enable'] is True or sensor['enable'].lower() == 'true'):
                        gSensorData['battery']['bus_voltage'] = ina226.read_bus_voltage()
                        gSensorData['battery']['current'] = ina226.read_current_by_shuntvolt()
                        gSensorData['battery']['power'] = ina226.read_power()
                    else:
                        interval = 1000.0
                    gevent.sleep(interval / 1000.0)

    def loop(aConfig, device_serial_no, key, sensor_type, serial_no, wsurl):
        global gSensorControl, gWebSocketConnection
        register(aConfig, device_serial_no, sensor_type, serial_no, wsurl)
        sensor = _.find(gSensorControl['sensors'], {'serial_no': serial_no})
        if sensor:
            while True:
                sensor = _.find(gSensorControl['sensors'], {'serial_no': serial_no})
                interval = sensor['interval']
                if sensor and (sensor['enable'] is True or sensor['enable'].lower() == 'true'):
                    try:
                        if gWebSocketConnection is None:
                            gWebSocketConnection = pi_create_websocket(wsurl)
                        if gWebSocketConnection and not gWebSocketConnection.connected:
                            gWebSocketConnection.connect(wsurl, sslopt={"cert_reqs": ssl.CERT_NONE, "check_hostname": False})
                        item = get_sensor_data(aConfig, key, device_serial_no, sensor_type,  serial_no)
                        if gWebSocketConnection and item:
                            gWebSocketConnection.send(json.dumps(item,  ensure_ascii=True))
                    except Empty:
                        pass
                    except Exception as e:
                        # print('loop error')
                        # print(e)
                        pass
                    finally:
                        try:
                            gWebSocketConnection.send('')
                        except:
                            gWebSocketConnection.close()
                gevent.sleep(interval)
        else:
            print('cannot get sensor:%s' % serial_no)

    app = aConfig['gConfig']['wsgi']['application']
    if 'queue' in aConfig['gConfig']['applications'][app] \
            and 'internal_sensor' in aConfig['gConfig']['applications'][app]['queue'] \
            and 'websocket' in aConfig['gConfig']['applications'][app]:
        internal_sensor = aConfig['gConfig']['applications'][app]['queue']['internal_sensor']
        device_serial_no = None

        if 'device_info' in aConfig['gConfig']['applications'][app] \
                and 'serial_no' in aConfig['gConfig']['applications'][app]['device_info'] \
                and len(aConfig['gConfig']['applications'][app]['device_info']['serial_no']):
            device_serial_no = aConfig['gConfig']['applications'][app]['device_info']['serial_no']

        websocketcfg = aConfig['gConfig']['applications'][app]['websocket']
        wsurl = '%s://%s:%s%s' % (websocketcfg['remote_protocol'], websocketcfg['remote_host'], websocketcfg['remote_port'],
                                  websocketcfg['remote_base'])
        for key in internal_sensor.keys():
            serial_no = None
            chip = None
            sensor_type = None
            i2c_addr = None
            if 'enable' in internal_sensor[key] and internal_sensor[key]['enable'].lower() == 'true':
                interval = 1.0
                if 'i2c_addr' in internal_sensor[key]:
                    i2c_addr = int(internal_sensor[key]['i2c_addr'], 16)
                if 'queue_consume_interval' in internal_sensor[key]:
                    interval = float(internal_sensor[key]['queue_consume_interval'])
                if 'type' in internal_sensor[key]:
                    sensor_type = internal_sensor[key]['type']
                    if isinstance(sensor_type, str):
                        sensor_type = int(sensor_type)
                    elif isinstance(sensor_type, list):
                        sensor_type = _.map_(sensor_type, lambda x:int(x))
                if 'serial_no' in internal_sensor[key]:
                    serial_no = internal_sensor[key]['serial_no']
                if gSensorControl is None:
                    gSensorControl = {}
                if device_serial_no:
                    gSensorControl['device_serial_no'] = device_serial_no
                if not 'sensors' in gSensorControl:
                    gSensorControl['sensors'] = []
                if serial_no and sensor_type:
                    sensor = _.find(gSensorControl['sensors'], {'serial_no': serial_no})
                    sensor_index = _.find_index(gSensorControl['sensors'], {'serial_no': serial_no})
                    if sensor:
                        sensor['enable'] = True
                        sensor['is_internal'] = True
                        sensor['interval'] = interval
                        sensor['type'] = sensor_type
                        gSensorControl['sensors'][sensor_index] = sensor
                    else:
                        sensor = {}
                        sensor['serial_no'] = serial_no
                        sensor['enable'] = True
                        sensor['is_internal'] = True
                        sensor['interval'] = interval
                        sensor['type'] = sensor_type
                        gSensorControl['sensors'].append(sensor)
                    # device = get_sensor_device(aConfig, key)
                    if key == 'DOF10':
                        gevent.spawn(rtimulib_loop, serial_no)
                        gevent.spawn(loop, aConfig, device_serial_no, key, sensor_type, serial_no, wsurl)
                    elif key in ['battery']:
                        gevent.spawn(pigpio_loop, key, i2c_addr, serial_no)
                        gevent.spawn(loop, aConfig, device_serial_no, key, sensor_type, serial_no, wsurl)
Esempio n. 11
0
def draw_slots(diff, theme: Theme):
    keys = sorted(diff.keys())
    tile = theme.value[CellState.CELL_DECK.value]
    strings = py_.map_(keys,
                       lambda key: '{} ×{}'.format(tile * key, diff[key]))
    return ' '.join(strings)
Esempio n. 12
0
from typing import Dict, List, Optional, TypeVar, Iterable

from pydash import py_

from Coord import Coord
from config import Locale

T = TypeVar('T')

adjacent_square = py_.map_([
    (-1, -1), (-1, 0), (-1, 1),
    (0, -1), (0, 1),
    (1, -1), (1, 0), (1, 1),
], Coord)

orthogonal = py_.map_([(-1, 0), (0, -1), (0, 1), (1, 0)], Coord)


def group_by_keys(dicts: Iterable[Dict[str, T]], default_value: Optional[T] = None) -> Dict[str, List[T]]:
    all_keys = py_.chain(dicts).flat_map(lambda d: list(d.keys())).uniq().value()
    # ^ это эквивалентно вот этому:
    # all_keys = py_.flat_map(dicts, lambda d: list(d.keys()))
    # all_keys = py_.uniq(all_keys)

    values = py_.map_(all_keys, lambda key: py_.invoke_map(dicts, 'get', key, default_value))
    return py_.zip_object(all_keys, values)


def from_move(move: Coord, locale: Locale) -> str:
    return '{}{}'.format(locale.value[move.j], move.i + 1)