Dump a GeoJSON-like `dict` to a multipolygon WKB string.

    Input parameters and output are similar to :funct:`_dump_point`.
329561
def _dump_multipolygon(obj, big_endian, meta):
    
    coords = obj['coordinates']
    vertex = coords[0][0][0]
    num_dims = len(vertex)

    wkb_string, byte_fmt, byte_order = _header_bytefmt_byteorder(
        'MultiPolygon', num_dims, big_endian, meta
    )

    poly_type = _WKB[_INT_TO_DIM_LABEL.get(num_dims)]['Polygon']
    if big_endian:
        poly_type = BIG_ENDIAN + poly_type
    else:
        poly_type = LITTLE_ENDIAN + poly_type[::-1]

    # apped the number of polygons
    wkb_string += struct.pack('%sl' % byte_order, len(coords))

    for polygon in coords:
        # append polygon header
        wkb_string += poly_type
        # append the number of rings in this polygon
        wkb_string += struct.pack('%sl' % byte_order, len(polygon))
        for ring in polygon:
            # append the number of vertices in this ring
            wkb_string += struct.pack('%sl' % byte_order, len(ring))
            for vertex in ring:
                wkb_string += struct.pack(byte_fmt, *vertex)

    return wkb_string
1055059
def dumps(obj, mesh_filename=None, *args, **kwargs): # pylint: disable=unused-argument
    '''
    

    '''
    point_template = '<point x="%f" y="%f" z="%f" name="%s"/>\n'
    file_template = """
    <!DOCTYPE PickedPoints>
    <PickedPoints>
     <DocumentData>
      <DateTime time="16:00:00" date="2014-12-31"/>
      <User name="bodylabs"/>
      <DataFileName name="%s"/>
     </DocumentData>
     %s
    </PickedPoints>
    """
    from blmath.numerics import isnumericarray

    if not isinstance(obj, dict) or not all([isnumericarray(point) for point in obj.itervalues()]):
        raise ValueError('obj should be a dict of points')

    points = '\n'.join([point_template % (tuple(xyz) + (name,)) for name, xyz in obj.iteritems()])

    return file_template % (mesh_filename, points)
1058878
def dump_dict(self):
        """"""

        dump_dict = dict()

        dump_dict['Structure'] = self.name

        # Refer to the __set_format__ method for an explanation
        # of the following construct.
        for keys in self.__keys__:
            for key in keys:

                val = getattr(self, key)
                if isinstance(val, (int, long)):
                    if key == 'TimeDateStamp' or key == 'dwTimeStamp':
                        try:
                            val = '0x%-8X [%s UTC]' % (val, time.asctime(time.gmtime(val)))
                        except ValueError as e:
                            val = '0x%-8X [INVALID TIME]' % val
                else:
                    val = ''.join(chr(d) if chr(d) in string.printable
                                  else "\\x%02x" % d for d in
                                    [ord(c) if not isinstance(c, int) else c for c in val])

                dump_dict[key] = {'FileOffset': self.__field_offsets__[key] + self.__file_offset__,
                                  'Offset': self.__field_offsets__[key],
                                  'Value': val}

        return dump_dict
959103
def json_dump(obj,       # type: Any
              fp,        # type: IO[str]
              **kwargs   # type: Any
             ):  # type: (...) -> None
    
    if six.PY2:
        kwargs['encoding'] = 'utf-8'
    json.dump(convert_to_dict(obj), fp, **kwargs)
880976
def toposimplify(geojson, p):
        
        proc_out = subprocess.run(
            ['geo2topo'],
            input=bytes(
                json.dumps(geojson),
                'utf-8'),
            stdout=subprocess.PIPE
        )
        proc_out = subprocess.run(
            ['toposimplify', '-P', p],
            input=proc_out.stdout,
            stdout=subprocess.PIPE,
            stderr=subprocess.DEVNULL
        )
        topojson = json.loads(proc_out.stdout)
        # Standardize object name
        topojson['objects']['divisions'] = topojson['objects'].pop('-')
        return topojson
704512
def dump(obj, path, **kw):
    
    open_kw = {'mode': 'w'}
    if PY3:  # pragma: no cover
        open_kw['encoding'] = 'utf-8'

    # avoid indented lines ending with ", " on PY2
    if kw.get('indent') and kw.get('separators') is None:
        kw['separators'] = (',', ': ')

    with open(str(path), **open_kw) as fp:
        return json.dump(obj, fp, **kw)
384379
def dump_json_file(json_data, pwd_dir_path, dump_file_name):
    
    class PythonObjectEncoder(json.JSONEncoder):
        def default(self, obj):
            try:
                return super().default(self, obj)
            except TypeError:
                return str(obj)

    logs_dir_path = os.path.join(pwd_dir_path, "logs")
    if not os.path.isdir(logs_dir_path):
        os.makedirs(logs_dir_path)

    dump_file_path = os.path.join(logs_dir_path, dump_file_name)

    try:
        with io.open(dump_file_path, 'w', encoding='utf-8') as outfile:
            if is_py2:
                outfile.write(
                    unicode(json.dumps(
                        json_data,
                        indent=4,
                        separators=(',', ':'),
                        ensure_ascii=False,
                        cls=PythonObjectEncoder
                    ))
                )
            else:
                json.dump(
                    json_data,
                    outfile,
                    indent=4,
                    separators=(',', ':'),
                    ensure_ascii=False,
                    cls=PythonObjectEncoder
                )

        msg = "dump file: {}".format(dump_file_path)
        logger.color_print(msg, "BLUE")

    except TypeError as ex:
        msg = "Failed to dump json file: {}\nReason: {}".format(dump_file_path, ex)
        logger.color_print(msg, "RED")
1237671
def write_pretty_dict_str(out, obj, indent=2):
    """"""
    json.dump(obj,
              out,
              indent=indent,
              sort_keys=True,
              separators=(',', ': '),
              ensure_ascii=False,
              encoding="utf-8")
380156
def ret_dump(self, d_ret, **kwargs):
        
        b_print     = True
        for k, v in kwargs.items():
            if k == 'JSONprint':    b_print     = bool(v)
        if b_print:
            print(
                json.dumps(   
                    d_ret, 
                    indent      = 4,
                    sort_keys   = True
                )
        )
228385
def to_latlon(geojson, origin_espg=None):
    

    if isinstance(geojson, dict):

        # get epsg code:
        if origin_espg:
            code = origin_espg
        else:
            code = epsg_code(geojson)
        if code:
            origin = Proj(init='epsg:%s' % code)
            wgs84 = Proj(init='epsg:4326')
            wrapped = test_wrap_coordinates(geojson['coordinates'], origin, wgs84)
            new_coords = convert_coordinates(geojson['coordinates'], origin, wgs84, wrapped)
            if new_coords:
                geojson['coordinates'] = new_coords
            try:
                del geojson['crs']
            except KeyError:
                pass

    return geojson
408761
def ip_to_geojson(ipaddress, name="Point"):
    """"""

    geo = ip_to_geo(ipaddress)

    point = {
        "type": "FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "properties": {
                    "name": name
                },
                "geometry": {
                    "type": "Point",
                    "coordinates": [
                        geo["longitude"],
                        geo["latitude"]
                    ]
                }
            }
        ]
    }

    return point
1129253
def to_esri_wgs_json(self):
        
        try:
            return ('{ "xmin" : %s, '
                    '"ymin" : %s, '
                    '"xmax" : %s, '
                    '"ymax" : %s, '
                    '"spatialReference" : {"wkid" : %d} }'
                    % (self.left,
                       self.bottom,
                       self.right,
                       self.top,
                       self.wkid))
        except ValueError:
            raise Exception('One or more values could not be cast to a number. '
                            'Four bounding points must be real numbers. '
                            'WKID must be an integer.')
811183
def dumpJSON(self):
        
        numexp = self.number.get()
        expTime, _, _, _, _ = self.timing()
        if numexp == 0:
            numexp = -1

        data = dict(
            numexp=self.number.value(),
            app=self.app.value(),
            led_flsh=self.led(),
            dummy_out=self.dummy(),
            fast_clks=self.fastClk(),
            readout=self.readSpeed(),
            dwell=self.expose.value(),
            exptime=expTime,
            oscan=self.oscan(),
            oscany=self.oscany(),
            xbin=self.wframe.xbin.value(),
            ybin=self.wframe.ybin.value(),
            multipliers=self.nmult.getall(),
            clear=self.clear()
        )

        # only allow nodding in clear mode, even if GUI has got confused
        if data['clear'] and self.nodPattern:
            data['nodpattern'] = self.nodPattern

        # no mixing clear and multipliers, no matter what GUI says
        if data['clear']:
            data['multipliers'] = [1 for i in self.nmult.getall()]

        # add window mode
        if not self.isFF():
            if self.isDrift():
                # no clear, multipliers or oscan in drift
                for setting in ('clear', 'oscan', 'oscany'):
                    data[setting] = 0
                data['multipliers'] = [1 for i in self.nmult.getall()]

                for iw, (xsl, xsr, ys, nx, ny) in enumerate(self.wframe):
                    data['x{}start_left'.format(iw+1)] = xsl
                    data['x{}start_right'.format(iw+1)] = xsr
                    data['y{}start'.format(iw+1)] = ys
                    data['y{}size'.format(iw+1)] = ny
                    data['x{}size'.format(iw+1)] = nx
            else:
                # no oscany in window mode
                data['oscany'] = 0

                for iw, (xsll, xsul, xslr, xsur, ys, nx, ny) in enumerate(self.wframe):
                    data['x{}start_upperleft'.format(iw+1)] = xsul
                    data['x{}start_lowerleft'.format(iw+1)] = xsll
                    data['x{}start_upperright'.format(iw+1)] = xsur
                    data['x{}start_lowerright'.format(iw+1)] = xslr
                    data['y{}start'.format(iw+1)] = ys
                    data['x{}size'.format(iw+1)] = nx
                    data['y{}size'.format(iw+1)] = ny
        return data
554588
def dump(context=os.environ):
    

    output = {}
    for key, value in context.iteritems():
        if not key.startswith("BE_"):
            continue
        output[key[3:].lower()] = value

    return output
213293
def dumpJson(obj, **kwargs):
    
    def handleDateAndBinaryForJs(x):
        if six.PY3 and isinstance(x, six.binary_type):
            x = x.decode()
        if isinstance(x, datetime.datetime) or isinstance(x, datetime.date):
            return stringDate(x)
        else:
            return x
    d = json.dumps(obj, separators=(',', ':'), default=handleDateAndBinaryForJs, **kwargs)
    assert '\n' not in d
    return d
579391
def dumpb(obj, container_count=False, sort_keys=False, no_float32=True, default=None):
    """"""
    with BytesIO() as fp:
        dump(obj, fp, container_count=container_count, sort_keys=sort_keys, no_float32=no_float32, default=default)
        return fp.getvalue()
655182
def yaml_dump(dict_to_dump):
    
    yaml.SafeDumper.add_representer(OrderedDict, _dict_representer)
    return yaml.safe_dump(dict_to_dump, default_flow_style=False)