create astroid for a living function object
358893
def object_build_function(node, member, localname):
    """"""
    # pylint: disable=deprecated-method; completely removed in 2.0
    args, varargs, varkw, defaults = inspect.getargspec(member)
    if varargs is not None:
        args.append(varargs)
    if varkw is not None:
        args.append(varkw)
    func = build_function(
        getattr(member, "__name__", None) or localname, args, defaults, member.__doc__
    )
    node.add_local_node(func, localname)
110902
def create_function_f_J(self):
        """"""
        return ca.Function(
            'J',
            [self.t, self.x, self.y, self.m, self.p, self.c, self.ng, self.nu],
            [ca.jacobian(self.f_x_rhs, self.x)],
            ['t', 'x', 'y', 'm', 'p', 'c', 'ng', 'nu'], ['J'], self.func_opt)
1045571
def _cellmagic(cls, options, obj, strict=False):
        ""
        options, failure = cls._process_magic(options, strict)
        if failure: return obj
        if not isinstance(obj, Dimensioned):
            return obj
        else:
            return StoreOptions.set_options(obj, options)
302699
function makeConstellations(agent) {
    let functor = function (id) {
        if (id === undefined) {
            return agent.request('get_universe_constellations', undefined);
        }
        else {
            return new ConstellationImpl(agent, id);
        }
    };
    functor.search = search_1.makeDefaultSearch(agent, "constellation" /* CONSTELLATION */);
    functor.names = function (ids) {
        if (ids === undefined) {
            return functor().then(ids => {
                return functor.names(ids);
            });
        }
        else {
            return names_1.getNames(agent, "constellation" /* CONSTELLATION */, ids);
        }
    };
    return functor;
}
425479
def propose_live(self):
        """"""

        # Copy a random live point.
        i = self.rstate.randint(self.nlive)
        u = self.live_u[i, :]

        # Check for ellipsoid overlap.
        ell_idxs = self.mell.within(u)
        nidx = len(ell_idxs)

        # Automatically trigger an update if we're not in any ellipsoid.
        if nidx == 0:
            try:
                # Expected ln(prior volume) at a given iteration.
                expected_vol = math.exp(self.saved_logvol[-1] - self.dlv)
            except:
                # Expected ln(prior volume) at the first iteration.
                expected_vol = math.exp(-self.dlv)
            pointvol = expected_vol / self.nlive  # minimum point volume

            # Update the bounding ellipsoids.
            bound = self.update(pointvol)
            if self.save_bounds:
                self.bound.append(bound)
            self.nbound += 1
            self.since_update = 0

            # Check for ellipsoid overlap (again).
            ell_idxs = self.mell.within(u)
            nidx = len(ell_idxs)

        # Pick a random ellipsoid that encompasses `u`.
        ell_idx = ell_idxs[self.rstate.randint(nidx)]

        # Choose axes.
        if self.sampling in ['rwalk', 'rstagger', 'rslice']:
            ax = self.mell.ells[ell_idx].axes
        elif self.sampling == 'slice':
            ax = self.mell.ells[ell_idx].paxes
        else:
            ax = np.identity(self.npdim)

        return u, ax
404248
def create(cls, obj, body, evaldict, defaults=None,
               doc=None, module=None, addsource=True, **attrs):
        
        if isinstance(obj, str): # "name(signature)"
            name, rest = obj.strip().split('(', 1)
            signature = rest[:-1] #strip a right parens
            func = None
        else: # a function
            name = None
            signature = None
            func = obj
        self = cls(func, name, signature, defaults, doc, module)
        ibody = '\n'.join('    ' + line for line in body.splitlines())
        return self.make('def %(name)s(%(signature)s):\n' + ibody,
                        evaldict, addsource, **attrs)
262678
def create(cls, path):
        """"""
        cmd = [HG, 'init', path]
        subprocess.check_call(cmd)
        return cls(path)
428692
def _project_on_ellipsoid(c, r, locations):
    """"""
    p0 = locations - c  # original locations

    l2 = 1 / np.sum(p0**2 / r**2, axis=1, keepdims=True)
    p = p0 * np.sqrt(l2)  # initial approximation (projection of points towards center of ellipsoid)

    fun = lambda x: np.sum((x.reshape(p0.shape) - p0)**2)              # minimize distance between new and old points
    con = lambda x: np.sum(x.reshape(p0.shape)**2 / r**2, axis=1) - 1  # new points constrained to surface of ellipsoid
    res = sp.optimize.minimize(fun, p, constraints={'type': 'eq', 'fun': con}, method='SLSQP')

    return res['x'].reshape(p0.shape) + c
486314
def main(arguments=None):
    
    from astrocalc.coords import unit_conversion
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="CRITICAL",
        options_first=True,
        projectName="astrocalc"
    )
    arguments, settings, log, dbConn = su.setup()

    # tab completion for raw_input
    readline.set_completer_delims(' \t\n;')
    readline.parse_and_bind("tab: complete")
    readline.set_completer(tab_complete)

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    # set options interactively if user requests
    if "interactiveFlag" in locals() and interactiveFlag:

        # load previous settings
        moduleDirectory = os.path.dirname(__file__) + "/resources"
        pathToPickleFile = "%(moduleDirectory)s/previousSettings.p" % locals()
        try:
            with open(pathToPickleFile):
                pass
            previousSettingsExist = True
        except:
            previousSettingsExist = False
        previousSettings = {}
        if previousSettingsExist:
            previousSettings = pickle.load(open(pathToPickleFile, "rb"))

        # x-raw-input
        # x-boolean-raw-input
        # x-raw-input-with-default-value-from-previous-settings

        # save the most recently used requests
        pickleMeObjects = []
        pickleMe = {}
        theseLocals = locals()
        for k in pickleMeObjects:
            pickleMe[k] = theseLocals[k]
        pickle.dump(pickleMe, open(pathToPickleFile, "wb"))

    # CALL FUNCTIONS/OBJECTS
    if coordflip:

        if cartesianFlag:
            converter = unit_conversion(
                log=log
            )
            x, y, z = converter.ra_dec_to_cartesian(
                ra="23 45 21.23232",
                dec="+01:58:5.45341"
            )
            print x, y, z
            return

        try:
            ra = float(ra)
            dec = float(dec)
            degree = True
        except Exception, e:
            degree = False

        if degree is True:
            converter = unit_conversion(
                log=log
            )
            try:
                ra = converter.ra_decimal_to_sexegesimal(
                    ra=ra,
                    delimiter=":"
                )
                dec = converter.dec_decimal_to_sexegesimal(
                    dec=dec,
                    delimiter=":"
                )
            except Exception, e:
                print e
                sys.exit(0)

            print ra, dec
        else:
            converter = unit_conversion(
                log=log
            )
            try:
                ra = converter.ra_sexegesimal_to_decimal(
                    ra=ra
                )
                dec = converter.dec_sexegesimal_to_decimal(
                    dec=dec
                )
            except Exception, e:
                print e
                sys.exit(0)
            print ra, dec

    if sep:
        from astrocalc.coords import separations
        calculator = separations(
            log=log,
            ra1=ra1,
            dec1=dec1,
            ra2=ra2,
            dec2=dec2,
        )
        angularSeparation, north, east = calculator.get()
        print """%(angularSeparation)s arcsec (%(north)s N, %(east)s E)""" % locals()

    if timeflip:
        try:
            inputMjd = float(datetime)
            if datetime[0] not in ["0", "1", "2"]:
                inputMjd = True
            else:
                inputMjd = False
        except:
            inputMjd = False
        from astrocalc.times import conversions
        converter = conversions(
            log=log
        )

        if inputMjd == False:
            try:
                mjd = converter.ut_datetime_to_mjd(utDatetime=datetime)
                print mjd
            except Exception, e:
                print e
        else:
            try:
                utDate = converter.mjd_to_ut_datetime(mjd=datetime)
                print utDate
            except Exception, e:
                print e

    if trans:
        # TRANSLATE COORDINATES ACROSS SKY
        from astrocalc.coords import translate
        newRa, newDec = translate(
            log=log,
            ra=ra,
            dec=dec,
            northArcsec=float(north),
            eastArcsec=float(east)
        ).get()
        from astrocalc.coords import unit_conversion
        converter = unit_conversion(
            log=log
        )
        ra = converter.ra_decimal_to_sexegesimal(
            ra=newRa,
            delimiter=":"
        )
        dec = converter.dec_decimal_to_sexegesimal(
            dec=newDec,
            delimiter=":"
        )

        print "%(newRa)s, %(newDec)s (%(ra)s, %(dec)s)" % locals()

    if now:
        from astrocalc.times import now
        mjd = now(
            log=log
        ).get_mjd()
        print mjd

    if dist and redshiftFlag:
        from astrocalc.distances import converter
        c = converter(log=log)
        if not hcFlag:
            hcFlag = 70.
        if not wmFlag:
            wmFlag = 0.3
        if not wvFlag:
            wvFlag = 0.7
        dists = c.redshift_to_distance(
            z=float(distVal),
            WM=float(wmFlag),
            WV=float(wvFlag),
            H0=float(hcFlag)
        )
        print "Distance Modulus: " + str(dists["dmod"]) + " mag"
        print "Luminousity Distance: " + str(dists["dl_mpc"]) + " Mpc"
        print "Angular Size Scale: " + str(dists["da_scale"]) + " kpc/arcsec"
        print "Angular Size Distance: " + str(dists["da_mpc"]) + " Mpc"
        print "Comoving Radial Distance: " + str(dists["dcmr_mpc"]) + " Mpc"

    if dist and mpcFlag:
        from astrocalc.distances import converter
        c = converter(log=log)
        z = c.distance_to_redshift(
            mpc=float(distVal)
        )
        print "z = %(z)s" % locals()

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
1267654
function buildNodeHierachy( nodeId, parentObject, json, allNodes, skins ) {

			var node = allNodes[ nodeId ];
			var nodeDef = json.nodes[ nodeId ];

			// build skeleton here as well

			if ( nodeDef.skin !== undefined ) {

				var meshes = node.isGroup === true ? node.children : [ node ];

				for ( var i = 0, il = meshes.length; i < il; i ++ ) {

					var mesh = meshes[ i ];
					var skinEntry = skins[ nodeDef.skin ];

					var bones = [];
					var boneInverses = [];

					for ( var j = 0, jl = skinEntry.joints.length; j < jl; j ++ ) {

						var jointId = skinEntry.joints[ j ];
						var jointNode = allNodes[ jointId ];

						if ( jointNode ) {

							bones.push( jointNode );

							var mat = new THREE.Matrix4();

							if ( skinEntry.inverseBindMatrices !== undefined ) {

								mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );

							}

							boneInverses.push( mat );

						} else {

							console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', jointId );

						}

					}

					mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );

				}

			}

			// build node hierachy

			parentObject.add( node );

			if ( nodeDef.children ) {

				var children = nodeDef.children;

				for ( var i = 0, il = children.length; i < il; i ++ ) {

					var child = children[ i ];
					buildNodeHierachy( child, node, json, allNodes, skins );

				}

			}

		}
1062265
def create_for_object(self, parent_object, slot, role='m', title=None):
        
        from .db import Placeholder
        parent_attrs = get_parent_lookup_kwargs(parent_object)
        obj = self.create(
            slot=slot,
            role=role or Placeholder.MAIN,
            title=title or slot.title().replace('_', ' '),
            **parent_attrs
        )
        obj.parent = parent_object  # fill the reverse cache
        return obj
1252854
def create(obj: PersistedObject, obj_type: Type[Any], arg_name: str):
        

        return MissingMandatoryAttributeFiles('Multifile object ' + str(obj) + ' cannot be built from constructor of '
                                              'type ' + get_pretty_type_str(obj_type) +
                                              ', mandatory constructor argument \'' + arg_name + '\'was not found on '
                                              'filesystem')
783862
function autoscale(options) {
    options = options || {};
    return function(planet) {
      planet.onInit(function() {
        var width  = window.innerWidth + (options.extraWidth || 0);
        var height = window.innerHeight + (options.extraHeight || 0);
        planet.projection.scale(Math.min(width, height) / 2);
      });
    };
  }
169267
def _set_axis(self, param, unit):
        
        axisValues = []
        for astroObject in self.objectList:
            try:
                value = eval('astroObject.{0}'.format(param))
            except ac.HierarchyError:  # ie trying to call planet.star and one planet is a lone ranger
                value = np.nan

            if unit is None:  # no unit to rescale (a aq.unitless quanitity would otherwise fail with ValueError)
                axisValues.append(value)
            else:
                try:
                    axisValues.append(value.rescale(unit))
                except AttributeError:  # either nan or unitless
                    axisValues.append(value)

        return axisValues
735346
def create_opengl_object(gl_gen_function, n=1):
    """"""
    handle = gl.GLuint(1)
    gl_gen_function(n, byref(handle))  # Create n Empty Objects
    if n > 1:
        return [handle.value + el for el in range(n)]  # Return list of handle values
    else:
        return handle.value
754758
function createFlow(fromRight) {
        return rest(function (funcs) {
          funcs = baseFlatten(funcs, 1);
          var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru;
          if (fromRight) {
            funcs.reverse();
          }
          while (index--) {
            var func = funcs[index];
            if (typeof func != 'function') {
              throw new TypeError(FUNC_ERROR_TEXT);
            }
            if (prereq && !wrapper && getFuncName(func) == 'wrapper') {
              var wrapper = new LodashWrapper([], true);
            }
          }
          index = wrapper ? index : length;
          while (++index < length) {
            func = funcs[index];
            var funcName = getFuncName(func), data = funcName == 'wrapper' ? getData(func) : undefined;
            if (data && isLaziable(data[0]) && data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) && !data[4].length && data[9] == 1) {
              wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
            } else {
              wrapper = func.length == 1 && isLaziable(func) ? wrapper[funcName]() : wrapper.thru(func);
            }
          }
          return function () {
            var args = arguments, value = args[0];
            if (wrapper && args.length == 1 && isArray(value) && value.length >= LARGE_ARRAY_SIZE) {
              return wrapper.plant(value).value();
            }
            var index = 0, result = length ? funcs[index].apply(this, args) : value;
            while (++index < length) {
              result = funcs[index].call(this, result);
            }
            return result;
          };
        });
      }
803239
def _creation_function(self, idx, seed, preset):
        
        return lambda: self.env.instantiate(seed=seed, serial_id=idx, preset=preset)