Create GSSHAPY Structure Objects Method
324803
def _createStructure(self, linkResult, replaceParamFile):
        
        # Constants
        WEIRS = ('WEIR', 'SAG_WEIR')

        CULVERTS = ('ROUND_CULVERT', 'RECT_CULVERT')

        CURVES = ('RATING_CURVE', 'SCHEDULED_RELEASE', 'RULE_CURVE')

        header = linkResult['header']

        # Initialize GSSHAPY StreamLink object
        link = StreamLink(linkNumber=header['link'],
                          type=linkResult['type'],
                          numElements=header['numstructs'])

        # Associate StreamLink with ChannelInputFile
        link.channelInputFile = self

        # Create Structure objects
        for s in linkResult['structures']:
            structType = s['structtype']

            # Cases
            if structType in WEIRS:
                # Weir type handler
                # Initialize GSSHAPY Weir object
                weir = Weir(type=structType,
                            crestLength=vrp(s['crest_length'], replaceParamFile),
                            crestLowElevation=vrp(s['crest_low_elev'], replaceParamFile),
                            dischargeCoeffForward=vrp(s['discharge_coeff_forward'], replaceParamFile),
                            dischargeCoeffReverse=vrp(s['discharge_coeff_reverse'], replaceParamFile),
                            crestLowLocation=vrp(s['crest_low_loc'], replaceParamFile),
                            steepSlope=vrp(s['steep_slope'], replaceParamFile),
                            shallowSlope=vrp(s['shallow_slope'], replaceParamFile))

                # Associate Weir with StreamLink
                weir.streamLink = link

            elif structType in CULVERTS:
                # Culvert type handler
                # Initialize GSSHAPY Culvert object
                culvert = Culvert(type=structType,
                                  upstreamInvert=vrp(s['upinvert'], replaceParamFile),
                                  downstreamInvert=vrp(s['downinvert'], replaceParamFile),
                                  inletDischargeCoeff=vrp(s['inlet_disch_coeff'], replaceParamFile),
                                  reverseFlowDischargeCoeff=vrp(s['rev_flow_disch_coeff'], replaceParamFile),
                                  slope=vrp(s['slope'], replaceParamFile),
                                  length=vrp(s['length'], replaceParamFile),
                                  roughness=vrp(s['rough_coeff'], replaceParamFile),
                                  diameter=vrp(s['diameter'], replaceParamFile),
                                  width=vrp(s['width'], replaceParamFile),
                                  height=vrp(s['height'], replaceParamFile))

                # Associate Culvert with StreamLink
                culvert.streamLink = link

            elif structType in CURVES:
                # Curve type handler
                pass

        return link
182442
def _createGsshaPyObjects(self, eventChunk):
        
        ## TODO: Add Support for RADAR file format type values

        # Create GSSHAPY PrecipEvent
        event = PrecipEvent(description=eventChunk['description'],
                            nrGag=eventChunk['nrgag'],
                            nrPds=eventChunk['nrpds'])

        # Associate PrecipEvent with PrecipFile
        event.precipFile = self

        gages = []
        for coord in eventChunk['coords']:
            # Create GSSHAPY PrecipGage object
            gage = PrecipGage(description=coord['description'],
                              x=coord['x'],
                              y=coord['y'])

            # Associate PrecipGage with PrecipEvent
            gage.event = event

            # Append to gages list for association with PrecipValues
            gages.append(gage)

        for valLine in eventChunk['valLines']:
            for index, value in enumerate(valLine['values']):
                # Create GSSHAPY PrecipValue object
                val = PrecipValue(valueType=valLine['type'],
                                  dateTime=valLine['dateTime'],
                                  value=value)

                # Associate PrecipValue with PrecipEvent and PrecipGage
                val.event = event
                val.gage = gages[index]
1108368
def _gi_build_stub(parent):
    
    classes = {}
    functions = {}
    constants = {}
    methods = {}
    for name in dir(parent):
        if name.startswith("__"):
            continue

        # Check if this is a valid name in python
        if not re.match(_identifier_re, name):
            continue

        try:
            obj = getattr(parent, name)
        except:
            continue

        if inspect.isclass(obj):
            classes[name] = obj
        elif inspect.isfunction(obj) or inspect.isbuiltin(obj):
            functions[name] = obj
        elif inspect.ismethod(obj) or inspect.ismethoddescriptor(obj):
            methods[name] = obj
        elif (
            str(obj).startswith("<flags")
            or str(obj).startswith("<enum ")
            or str(obj).startswith("<GType ")
            or inspect.isdatadescriptor(obj)
        ):
            constants[name] = 0
        elif isinstance(obj, (int, str)):
            constants[name] = obj
        elif callable(obj):
            # Fall back to a function for anything callable
            functions[name] = obj
        else:
            # Assume everything else is some manner of constant
            constants[name] = 0

    ret = ""

    if constants:
        ret += "# %s constants\n\n" % parent.__name__
    for name in sorted(constants):
        if name[0].isdigit():
            # GDK has some busted constant names like
            # Gdk.EventType.2BUTTON_PRESS
            continue

        val = constants[name]

        strval = str(val)
        if isinstance(val, str):
            strval = '"%s"' % str(val).replace("\\", "\\\\")
        ret += "%s = %s\n" % (name, strval)

    if ret:
        ret += "\n\n"
    if functions:
        ret += "# %s functions\n\n" % parent.__name__
    for name in sorted(functions):
        ret += "def %s(*args, **kwargs):\n" % name
        ret += "    pass\n"

    if ret:
        ret += "\n\n"
    if methods:
        ret += "# %s methods\n\n" % parent.__name__
    for name in sorted(methods):
        ret += "def %s(self, *args, **kwargs):\n" % name
        ret += "    pass\n"

    if ret:
        ret += "\n\n"
    if classes:
        ret += "# %s classes\n\n" % parent.__name__
    for name, obj in sorted(classes.items()):
        base = "object"
        if issubclass(obj, Exception):
            base = "Exception"
        ret += "class %s(%s):\n" % (name, base)

        classret = _gi_build_stub(obj)
        if not classret:
            classret = "pass\n"

        for line in classret.splitlines():
            ret += "    " + line + "\n"
        ret += "\n"

    return ret
306889
def add_Struct(self, struct=None,
                   Cls=None, Name=None, Poly=None,
                   mobile=False, shot=None,
                   Lim=None, Type=None,
                   dextraprop=None):
        
        # Check inputs
        C0a = struct is None
        C1a = all([ss is None for ss in [Cls,Name,Poly,Lim,Type]])
        if not np.sum([C0a,C1a])==1:
            msg = "Provide either:"
            msg += "\n    - struct: a Struct subclass instance"
            msg += "\n    - the keyword args to create one"
            msg += "\n        (Cls,Name,Poly,Lim,Type)\n"
            msg += "\n You provded:"
            msg += "\n    - struct: {0}, {1}".format(str(struct),
                                                     type(struct))
            raise Exception(msg)

        # Create struct if not provided
        if C0a:
            if not (type(Cls) is str or issubclass(Cls,Struct)):
                msg = "Cls must be either:"
                msg += "\n    - a Struct subclass"
                msg += "\n    - the str Name of it (e.g.: 'PFC','CoilPF',...)"
                raise Exception(msg)
            if type(Cls) is str:
                Cls = eval('%s'%Cls)

            # Preformat Lim and Type
            if Lim is None:
                Lim = self.Lim
            if Type is None:
                Type = self.Id.Type

            # Create instance
            struct = Cls(Poly=Poly, Name=Name, Lim=Lim, Type=Type,
                         mobile=mobile, shot=shot, Exp=self.Id.Exp)

        C0b = issubclass(struct.__class__, Struct)
        assert C0b, "struct must be a Struct subclass instance !"

        # Prepare dextraprop
        dextra = self.dextraprop
        lk = sorted([k[1:] for k in dextra.keys() if k!='lprop'])
        if dextraprop is None:
            if not dextra in [None,{}]:
                msg = "The current Config instance has the following extraprop:"
                msg += "\n    - " + "\n    - ".join(lk)
                msg += "\n  => Please specify a dextraprop for struct !"
                msg += "\n     (using the same keys !)"
                raise Exception(msg)
        else:
            assert isinstance(dextraprop,dict)
            assert all([k in lk for k in dextraprop.keys()])
            assert all([k in dextraprop.keys() for k in lk])
            dx = {}
            for k in lk:
                dk = 'd'+k
                dx[k] = {}
                for k0 in dextra[dk].keys():
                    dx[k][k0] = {}
                    for k1 in dextra[dk][k0].keys():
                        dx[k][k0][k1] = dextra[dk][k0][k1]
                if not struct.Id.Cls in dx[k].keys():
                    dx[k][struct.Id.Cls] = {struct.Id.Name:dextraprop[k]}
                else:
                    dx[k][struct.Id.Cls][struct.Id.Name] = dextraprop[k]

        # Set self.lStruct
        lS = self.lStruct + [struct]
        self._init(lStruct=lS, Lim=self.Lim, dextraprop=dx)
762245
function makeShapeAstForShapeIntersectRuntime(propTypeData) {
  const runtimeMerge = makeObjectMergeAstForShapeIntersectRuntime(propTypeData);
  return t.callExpression(
    t.memberExpression(
      makePropTypeImportNode(),
      t.identifier('shape'),
    ),
    [runtimeMerge],
  );
}
745074
def data_structure_builder(func):
    
    @wraps(func)
    def ds_builder_wrapper(function, *args, **kwargs):
        try:
            function = DSBuilder(function)
        except NoBuilder:
            pass
        return func(function, *args, **kwargs)

    return ds_builder_wrapper
685433
def _init_axes(self, data, method='plot',
                   xscale=None, sharex=False, sharey=False,
                   geometry=None, separate=None, **kwargs):
        
        if isinstance(sharex, bool):
            sharex = "all" if sharex else "none"
        if isinstance(sharey, bool):
            sharey = "all" if sharey else "none"

        # parse keywords
        axes_kw = {key: kwargs.pop(key) for key in utils.AXES_PARAMS if
                   key in kwargs}

        # handle geometry and group axes
        if geometry is not None and geometry[0] * geometry[1] == len(data):
            separate = True
        axes_groups = _group_axes_data(data, separate=separate)
        if geometry is None:
            geometry = (len(axes_groups), 1)
        nrows, ncols = geometry
        if axes_groups and nrows * ncols != len(axes_groups):
            # mismatching data and geometry
            raise ValueError("cannot group data into {0} axes with a "
                             "{1}x{2} grid".format(len(axes_groups), nrows,
                                                   ncols))

        # create grid spec
        gs = GridSpec(nrows, ncols)
        axarr = numpy.empty((nrows, ncols), dtype=object)

        # set default labels
        defxlabel = 'xlabel' not in axes_kw
        defylabel = 'ylabel' not in axes_kw
        flatdata = [s for group in axes_groups for s in group]
        for axis in ('x', 'y'):
            unit = _common_axis_unit(flatdata, axis=axis)
            if unit:
                axes_kw.setdefault('{}label'.format(axis),
                                   unit.to_string('latex_inline_dimensional'))

        # create axes for each group and draw each data object
        for group, (row, col) in zip_longest(
                axes_groups, itertools.product(range(nrows), range(ncols)),
                fillvalue=[]):
            # create Axes
            shared_with = {"none": None, "all": axarr[0, 0],
                           "row": axarr[row, 0], "col": axarr[0, col]}
            axes_kw["sharex"] = shared_with[sharex]
            axes_kw["sharey"] = shared_with[sharey]
            axes_kw['xscale'] = xscale if xscale else _parse_xscale(group)
            ax = axarr[row, col] = self.add_subplot(gs[row, col], **axes_kw)

            # plot data
            plot_func = getattr(ax, method)
            if method in ('imshow', 'pcolormesh'):
                for obj in group:
                    plot_func(obj, **kwargs)
            elif group:
                plot_func(*group, **kwargs)

            # set default axis labels
            for axis, share, pos, n, def_ in (
                    (ax.xaxis, sharex, row, nrows, defxlabel),
                    (ax.yaxis, sharey, col, ncols, defylabel),
            ):
                # hide label if shared axis and not bottom left panel
                if share == 'all' and pos < n - 1:
                    axis.set_label_text('')
                # otherwise set default status
                else:
                    axis.isDefault_label = def_

        return self.axes
776154
def structs2pandas(structs):
    """"""
    try:
        import pandas
        records = list(structs2records(structs))
        df = pandas.DataFrame.from_records(records)
        # TODO: do this for string columns, for now just for id
        # How can we check for string columns, this is not nice:
        # df.columns[df.dtypes == object]
        if 'id' in df:
            df["id"] = df["id"].apply(str.rstrip)
        return df
    except ImportError:
        # pandas not found, that's ok        
        return structs
490181
def _make_gist(contents, description='', filename='data.geojson'):
    
    ghapi = github3.GitHub()
    files = {filename: {'content': contents}}
    gist = ghapi.create_gist(description, files)

    return gist
727177
def structure(self, obj, cl):
        # type: (Any, Type[T]) -> T
        """"""

        return self._structure_func.dispatch(cl)(obj, cl)
315147
def create_dict_subclass(name, hash_func, slots, doc):
    

    hash_length = len(slots)

    # Returns array index -- raises a KeyError if the key does not match
    # its slot value.
    def index_or_key_error(key):
        index = hash_func(key)
        # Make sure the key is **exactly** the same.
        if key != slots[index]:
            raise KeyError(key)
        return index

    def init(self, *args, **kwargs):
        self._arr = [None] * hash_length
        self._len = 0

        # Delegate initialization to update provided by MutableMapping:
        self.update(*args, **kwargs)

    def getitem(self, key):
        index = index_or_key_error(key)
        if self._arr[index] is None:
            raise KeyError(key)
        return self._arr[index][1]

    def setitem(self, key, value):
        index = index_or_key_error(key)
        self._arr[index] = (key, value)

    def delitem(self, key):
        index = index_or_key_error(key)
        if self._arr[index] is None:
            raise KeyError(key)
        self._arr[index] = None

    def dict_iter(self):
        return (pair[0] for pair in self._arr if pair is not None)

    def dict_len(self):
        # TODO: Make this O(1) using auxiliary state?
        return sum(1 for _ in self)

    def dict_repr(self):
        arr_repr = (repr(pair) for pair in self._arr if pair is not None)
        return ''.join((name, '([', ', '.join(arr_repr), '])'))

    # Inheriting from MutableMapping gives us a whole whackload of methods for
    # free.
    bases = (collections.MutableMapping,)

    return type(name, bases, {
        '__init__': init,
        '__doc__': doc,

        '__getitem__': getitem,
        '__setitem__': setitem,
        '__delitem__': delitem,
        '__iter__': dict_iter,
        '__len__': dict_len,

        '__repr__': dict_repr,
    })
148729
def structure_to_abivars(structure, **kwargs):
    
    if not structure.is_ordered:
        raise ValueError("""\
Received disordered structure with partial occupancies that cannot be converted into an Abinit input
Please use OrderDisorderedStructureTransformation or EnumerateStructureTransformation
to build an appropriate supercell from partial occupancies or alternatively use the Virtual Crystal Approximation.""")

    types_of_specie = structure.types_of_specie
    natom = structure.num_sites

    znucl_type = [specie.number for specie in types_of_specie]
    znucl_atoms = structure.atomic_numbers

    typat = np.zeros(natom, np.int)
    for atm_idx, site in enumerate(structure):
        typat[atm_idx] = types_of_specie.index(site.specie) + 1

    rprim = ArrayWithUnit(structure.lattice.matrix, "ang").to("bohr")
    angdeg = structure.lattice.angles
    xred = np.reshape([site.frac_coords for site in structure], (-1, 3))

    # Set small values to zero. This usually happens when the CIF file
    # does not give structure parameters with enough digits.
    rprim = np.where(np.abs(rprim) > 1e-8, rprim, 0.0)
    xred = np.where(np.abs(xred) > 1e-8, xred, 0.0)

    # Info on atoms.
    d = dict(
        natom=natom,
        ntypat=len(types_of_specie),
        typat=typat,
        znucl=znucl_type,
        xred=xred,
    )

    # Add info on the lattice.
    # Should we use (rprim, acell) or (angdeg, acell) to specify the lattice?
    geomode = kwargs.pop("geomode", "rprim")
    if geomode == "automatic":
        geomode = "rprim"
        if structure.lattice.is_hexagonal: # or structure.lattice.is_rhombohedral
            geomode = "angdeg"
            angdeg = structure.lattice.angles
            # Here one could polish a bit the numerical values if they are not exact.
            # Note that in pmg the angles are 12, 20, 01 while in Abinit 12, 02, 01
            # One should make sure that the orientation is preserved (see Curtarolo's settings)

    if geomode == "rprim":
        d.update(
            acell=3 * [1.0],
            rprim=rprim,
        )

    elif geomode == "angdeg":
        d.update(
            acell=ArrayWithUnit(structure.lattice.abc, "ang").to("bohr"),
            angdeg=angdeg,
        )
    else:
        raise ValueError("Wrong value for geomode: %s" % geomode)

    return d
113836
function (json, lib) {

        // Create skeletons and joints
        util$1.each(json.skins, function (skinInfo, idx) {
            var skeleton = new Skeleton({
                name: skinInfo.name
            });
            for (var i = 0; i < skinInfo.joints.length; i++) {
                var nodeIdx = skinInfo.joints[i];
                var node = lib.nodes[nodeIdx];
                var joint = new Joint({
                    name: node.name,
                    node: node,
                    index: skeleton.joints.length
                });
                skeleton.joints.push(joint);
            }
            skeleton.relativeRootNode = lib.nodes[skinInfo.skeleton] || this.rootNode;
            if (skinInfo.inverseBindMatrices) {
                var IBMInfo = json.accessors[skinInfo.inverseBindMatrices];
                var buffer = lib.bufferViews[IBMInfo.bufferView];

                var offset = IBMInfo.byteOffset || 0;
                var size = IBMInfo.count * 16;

                var array = new vendor.Float32Array(buffer, offset, size);

                skeleton.setJointMatricesArray(array);
            }
            else {
                skeleton.updateJointMatrices();
            }
            lib.skeletons[idx] = skeleton;
        }, this);

        function enableSkinningForMesh(mesh, skeleton, jointIndices) {
            mesh.skeleton = skeleton;
            mesh.joints = jointIndices;

            if (!skeleton.boundingBox) {
                skeleton.updateJointsBoundingBoxes(mesh.geometry);
            }
        }

        function getJointIndex(joint) {
            return joint.index;
        }

        util$1.each(json.nodes, function (nodeInfo, nodeIdx) {
            if (nodeInfo.skin != null) {
                var skinIdx = nodeInfo.skin;
                var skeleton = lib.skeletons[skinIdx];

                var node = lib.nodes[nodeIdx];
                var jointIndices = skeleton.joints.map(getJointIndex);
                if (node instanceof Mesh) {
                    enableSkinningForMesh(node, skeleton, jointIndices);
                }
                else {
                    // Mesh have multiple primitives
                    var children = node.children();
                    for (var i = 0; i < children.length; i++) {
                        enableSkinningForMesh(children[i], skeleton, jointIndices);
                    }
                }
            }
        }, this);
    }
938319
def _generate_struct_class_init(self, data_type):
        

        args = ['self']
        for field in data_type.all_fields:
            field_name_reserved_check = fmt_var(field.name, True)
            args.append('%s=None' % field_name_reserved_check)

        self.generate_multiline_list(args, before='def __init__', after=':')

        with self.indent():
            lineno = self.lineno

            # Call the parent constructor if a super type exists
            if data_type.parent_type:
                class_name = class_name_for_data_type(data_type)
                all_parent_fields = [fmt_func(f.name, check_reserved=True)
                              for f in data_type.parent_type.all_fields]
                self.generate_multiline_list(
                    all_parent_fields,
                    before='super({}, self).__init__'.format(class_name))

            # initialize each field
            for field in data_type.fields:
                field_var_name = fmt_var(field.name)
                self.emit('self._{}_value = None'.format(field_var_name))
                self.emit('self._{}_present = False'.format(field_var_name))

            # handle arguments that were set
            for field in data_type.fields:
                field_var_name = fmt_var(field.name, True)
                self.emit('if {} is not None:'.format(field_var_name))
                with self.indent():
                    self.emit('self.{0} = {0}'.format(field_var_name))

            if lineno == self.lineno:
                self.emit('pass')
            self.emit()
1095766
def _merge_struct(lhs, rhs, type_):
    """"""
    fields = type_.struct_type.fields
    lhs, rhs = list(lhs.list_value.values), list(rhs.list_value.values)
    candidate_type = fields[len(lhs) - 1].type
    first = rhs.pop(0)
    if first.HasField("null_value") or candidate_type.code in _UNMERGEABLE_TYPES:
        lhs.append(first)
    else:
        last = lhs.pop()
        lhs.append(_merge_by_type(last, first, candidate_type))
    return Value(list_value=ListValue(values=lhs + rhs))
745325
function createSectionStructure() {
    return {
        init: null,
        comments: [],
        attribs: {
            define: [],
            init: []
        },
        elements: {
            define: [],
            init: []
        },
        events: [],
        links: [],
        ons: [],
        statics: []
    };
}
469899
function(cls,methods) {
    var keys = Object.keys(methods);
    var len = keys.length;
    for (var i = 0; i < len; i++) {
      var key = keys[i];
      cls.prototype[key] = lib.method.createMethod(methods[key]);
    }
    return cls;
  }