コード例 #1
0
ファイル: xslt_root.c プロジェクト: abed-hawa/amara
static PyObject *root_prime(XsltRootObject *self, PyObject *args)
{
  PyObject *context;
  PyObject *nodes = self->prime_instructions;
  Py_ssize_t i, size;

  if (!PyArg_ParseTuple(args, "O:prime", &context))
    return NULL;

  if (PyDict_Size(self->sourceNodes)) {
    PyObject *documents = PyObject_GetAttrString(context, "documents");
    if (documents == NULL)
      return NULL;
    if (PyDict_Merge(documents, self->sourceNodes, 1) < 0) {
      Py_DECREF(documents);
      return NULL;
    }
    Py_DECREF(documents);
  }

  /* Call `prime()` for those nodes that have it defined. */
  size = PyList_GET_SIZE(nodes);
  for (i = 0; i < size; i++) {
    PyObject *result = PyList_GET_ITEM(nodes, i);
    PyObject *func = PyObject_GetAttr(result, prime_string);
    if (func == NULL) return NULL;
    result = PyObject_Call(func, args, NULL);
    Py_DECREF(func);
    if (result == NULL) return NULL;
  }

  Py_INCREF(Py_None);
  return Py_None;
}
コード例 #2
0
/* For faster execution we keep a special dictionary for pydrivers, with
 * the needed modules and aliases.
 */
int bpy_pydriver_create_dict(void)
{
	PyObject *d, *mod;

	/* validate namespace for driver evaluation */
	if (bpy_pydriver_Dict) return -1;

	d = PyDict_New();
	if (d == NULL)
		return -1;
	else
		bpy_pydriver_Dict = d;

	/* import some modules: builtins, bpy, math, (Blender.noise )*/
	PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins());

	mod = PyImport_ImportModule("math");
	if (mod) {
		PyDict_Merge(d, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
		Py_DECREF(mod);
	}

	/* add bpy to global namespace */
	mod= PyImport_ImportModuleLevel((char *)"bpy", NULL, NULL, NULL, 0);
	if (mod) {
		PyDict_SetItemString(bpy_pydriver_Dict, "bpy", mod);
		Py_DECREF(mod);
	}

	return 0;
}
コード例 #3
0
/*
	Will check if the given dict contains one of the constants and if not present,
	will import them automatically.
*/
void PythonIntegration::AddGlobalsOnDemand(PyObject* dict) {

	if (PyDict_GetItemString(dict, "stat_strength")) {
		return; // Already imported
	}

	PyDict_Merge(dict, MainModuleDict, 0);
}
コード例 #4
0
ファイル: kdumpfile.c プロジェクト: jeffmahoney/libkdumpfile
static PyObject *
attr_dir_copy(PyObject *_self, PyObject *args)
{
	PyObject *dict = PyDict_New();
	if (!dict)
		return NULL;
	if (PyDict_Merge(dict, _self, 1) != 0) {
		Py_DECREF(dict);
		return NULL;
	}
	return dict;
}
コード例 #5
0
ElementDocumentWrapper::ElementDocumentWrapper(PyObject* self, const char* tag) : ElementWrapper< ElementDocument >(self, tag)
{
	Rocket::Core::String module_id(32, "document_%x", this);

	// Create a new module
	module = PyModule_New(module_id.CString());
	module_namespace = PyModule_GetDict(module);

	// Merging main into the module
	PyObject* builtins = PyImport_AddModule("__main__");
	PyObject* builtins_dict = PyModule_GetDict( builtins);
	PyDict_Merge(module_namespace, builtins_dict, 0);
}
コード例 #6
0
ファイル: python_tensor.cpp プロジェクト: inkawhich/pytorch
static THPObjectPtr get_tensor_dict() {
  auto torch = THPObjectPtr(PyImport_ImportModule("torch"));
  if (!torch) throw python_error();

  auto tensor_class = THPObjectPtr(PyObject_GetAttrString(torch, "Tensor"));
  if (!tensor_class) throw python_error();

  auto tensor_type = (PyTypeObject*)tensor_class.get();
  TORCH_ASSERTM(tensor_type->tp_base, "missing base type for Tensor");

  auto res = THPObjectPtr(PyDict_New());
  if (!res) throw python_error();

  if (PyDict_Merge(res.get(), tensor_type->tp_dict, 0) < 0) {
    throw python_error();
  }
  if (PyDict_Merge(res.get(), tensor_type->tp_base->tp_dict, 0) < 0) {
    throw python_error();
  }

  return res;
}
コード例 #7
0
ファイル: dictionaries.hpp プロジェクト: FireWalkerX/Nuitka
// Convert to dictionary, helper for builtin dict mainly.
NUITKA_MAY_BE_UNUSED static PyObject *TO_DICT( PyObject *seq_obj, PyObject *dict_obj )
{
    PyObject *result = PyDict_New();

    if ( seq_obj != NULL )
    {
        int res;

        if ( PyObject_HasAttrString( seq_obj, "keys" ) )
        {
            res = PyDict_Merge( result, seq_obj, 1 );
        }
        else
        {
            res = PyDict_MergeFromSeq2( result, seq_obj, 1 );
        }

        if ( res == -1 )
        {
            return NULL;
        }
    }

    if ( dict_obj != NULL )
    {
        int res = PyDict_Merge( result, dict_obj, 1 );

        if ( res == -1 )
        {
            return NULL;
        }

    }

    return result;
}
/*
 * Add globals from __main__ to a dictionary of them.
 */
static int add_globals(JNIEnv *pEnv, PyObject *pGlobals) {
    PyObject *pMain;
    PyObject *pMainDict;
    int result;
    pMain = PyImport_AddModule("__main__");
    if (! pMain) {
        throwWrappedError(pEnv, __LINE__);
        return -1;
    }
    pMainDict = PyModule_GetDict(pMain);
    result = PyDict_Merge(pGlobals, pMainDict, 0);
    if (result) {
        throwWrappedError(pEnv, __LINE__);
    }
    return result;
}
コード例 #9
0
ファイル: _cstruct.c プロジェクト: TriOptima/tri.struct
static PyObject *
Struct_copy(PyObject *self)
{
    PyObject *copy;
    PyTypeObject *mytype;

    mytype = self->ob_type;
    copy = mytype->tp_new(mytype, NULL, NULL);

    if (copy == NULL)
        return NULL;
    if (0 == PyDict_Merge(copy, self, 1))
        return copy;
    Py_DECREF(copy);
    return NULL;
}
コード例 #10
0
static PyObject *
partial_call(partialobject *pto, PyObject *args, PyObject *kw)
{
    PyObject *ret;
    PyObject *argappl, *kwappl;

    assert (PyCallable_Check(pto->fn));
    assert (PyTuple_Check(pto->args));
    assert (PyDict_Check(pto->kw));

    if (PyTuple_GET_SIZE(pto->args) == 0) {
        argappl = args;
        Py_INCREF(args);
    } else if (PyTuple_GET_SIZE(args) == 0) {
        argappl = pto->args;
        Py_INCREF(pto->args);
    } else {
        argappl = PySequence_Concat(pto->args, args);
        if (argappl == NULL)
            return NULL;
        assert(PyTuple_Check(argappl));
    }

    if (PyDict_Size(pto->kw) == 0) {
        kwappl = kw;
        Py_XINCREF(kwappl);
    } else {
        kwappl = PyDict_Copy(pto->kw);
        if (kwappl == NULL) {
            Py_DECREF(argappl);
            return NULL;
        }
        if (kw != NULL) {
            if (PyDict_Merge(kwappl, kw, 1) != 0) {
                Py_DECREF(argappl);
                Py_DECREF(kwappl);
                return NULL;
            }
        }
    }

    ret = PyObject_Call(pto->fn, argappl, kwappl);
    Py_DECREF(argappl);
    Py_XDECREF(kwappl);
    return ret;
}
コード例 #11
0
ファイル: _functoolsmodule.c プロジェクト: 1st1/cpython
static PyObject *
partial_call(partialobject *pto, PyObject *args, PyObject *kwargs)
{
    PyObject *kwargs2, *res;

    assert (PyCallable_Check(pto->fn));
    assert (PyTuple_Check(pto->args));
    assert (PyDict_Check(pto->kw));

    if (PyDict_GET_SIZE(pto->kw) == 0) {
        /* kwargs can be NULL */
        kwargs2 = kwargs;
        Py_XINCREF(kwargs2);
    }
    else {
        /* bpo-27840, bpo-29318: dictionary of keyword parameters must be
           copied, because a function using "**kwargs" can modify the
           dictionary. */
        kwargs2 = PyDict_Copy(pto->kw);
        if (kwargs2 == NULL) {
            return NULL;
        }

        if (kwargs != NULL) {
            if (PyDict_Merge(kwargs2, kwargs, 1) != 0) {
                Py_DECREF(kwargs2);
                return NULL;
            }
        }
    }


    if (pto->use_fastcall) {
        res = partial_fastcall(pto,
                               &PyTuple_GET_ITEM(args, 0),
                               PyTuple_GET_SIZE(args),
                               kwargs2);
    }
    else {
        res = partial_call_impl(pto, args, kwargs2);
    }
    Py_XDECREF(kwargs2);
    return res;
}
コード例 #12
0
ファイル: content_model.c プロジェクト: H1d3r/binary_blobs
/* Given a list of states, return the union of the epsilon closures for each
 * of its member states.
 */
static int set_epsilon_closure(PyObject *model, PyObject *state_set,
                               PyObject *states)
{
  PyObject *epsilon_set;
  int i;

  for (i = 0; i < PyList_GET_SIZE(states); i++) {
    epsilon_set = epsilon_closure(model, PyList_GET_ITEM(states, i));
    if (epsilon_set == NULL) {
      return -1;
    }
    if (PyDict_Merge(state_set, epsilon_set, 1) < 0) {
      Py_DECREF(epsilon_set);
      return -1;
    }
    Py_DECREF(epsilon_set);
  }
  return 0;
}
コード例 #13
0
static void sip_import_component_module(PyObject *d, const char *name)
{
#if PY_VERSION_HEX >= 0x02050000
    PyObject *mod = PyImport_ImportModule(name);
#else
    PyObject *mod = PyImport_ImportModule((char *)name);
#endif

    /*
     * Note that we don't complain if the module can't be imported.  This
     * is a favour to Linux distro packagers who like to split PyQt into
     * different sub-packages.
     */
    if (mod)
    {
        PyDict_Merge(d, PyModule_GetDict(mod), 0);
        Py_DECREF(mod);
    }
}
コード例 #14
0
ファイル: python_tensor.cpp プロジェクト: inkawhich/pytorch
static void py_initialize_tensor_type(PyTypeObject& type, const char* name, PyObject* tp_dict) {
  // NOTE: we don't use the typical static declaration of PyTypeObject because
  // we need to initialize as many types as there are VariableType instances.
  // The typical PyVarObject_HEAD_INIT(NULL, 0) is described in the Python
  // documentation: it initializes the refcnt to 1 and the other object header
  // fields to zero.
  memset(&type, 0, sizeof(PyTypeObject));
  ((PyObject*)&type)->ob_refcnt = 1;
  ((PyObject*)&type)->ob_type = &metaclass;
  type.tp_basicsize = sizeof(PyTensorType);
  type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
  type.tp_name = name;
  type.tp_new = Tensor_new;
  if (PyType_Ready(&type) < 0) {
    throw python_error();
  }
  if (PyDict_Merge(type.tp_dict, tp_dict, 0) < 0) {
    throw python_error();
  }
}
コード例 #15
0
ファイル: script.cpp プロジェクト: CoolJie2001/kbengine
//-------------------------------------------------------------------------------------
PyThreadState* Script::createInterpreter()
{
	PyThreadState* 	pCurInterpreter = PyThreadState_Get();
	PyObject * 		pCurPath = PySys_GetObject( "path" );

	PyThreadState* pNewInterpreter = Py_NewInterpreter();
	if (pNewInterpreter)
	{
		PySys_SetObject( "path", pCurPath );
#ifndef KBE_SINGLE_THREADED
		PyDict_Merge( PySys_GetObject( "modules" ), s_pOurInitTimeModules, 0 );
#endif

		PyThreadState* pSwapped = PyThreadState_Swap( pCurInterpreter );
		if( pSwapped != pNewInterpreter )
		{
			KBE_EXIT( "error creating new python interpreter" );
		}
	}

	return pNewInterpreter;
}
コード例 #16
0
ファイル: kdumpfile.c プロジェクト: jeffmahoney/libkdumpfile
static PyObject *
attr_dir_dict(PyObject *_self, PyObject *args)
{
	PyObject *view;
	PyObject *dict;

	view = attr_dir_viewdict(_self, NULL);
	if (!view)
		return NULL;
	dict = PyDict_New();
	if (!dict)
		goto err;
	if (PyDict_Merge(dict, view, 1) != 0)
		goto err_dict;
	Py_DECREF(view);
	return dict;

 err_dict:
	Py_DECREF(dict);
 err:
	Py_DECREF(view);
	return NULL;
}
コード例 #17
0
ファイル: script.cpp プロジェクト: CoolJie2001/kbengine
void Script::initThread( bool plusOwnInterpreter )
{
	if( s_defaultContext != NULL )
	{
		KBE_EXIT( "trying to initialise scripting when already initialised" );
	}

	PyEval_AcquireLock();

	PyThreadState * newTState = NULL;

	if (plusOwnInterpreter)
	{
		newTState = Py_NewInterpreter();

		PyObject * pMainPyPath = PyDict_GetItemString(
			s_pMainThreadState->interp->sysdict, "path" );
		PySys_SetObject( "path", pMainPyPath );

		PyDict_Merge( PySys_GetObject( "modules" ), s_pOurInitTimeModules, 0);
	}
	else
	{
		newTState = PyThreadState_New( s_pMainThreadState->interp );
	}

	if( newTState == NULL )
	{
		KBE_EXIT( "failed to create a new thread object" );
	}

	PyEval_ReleaseLock();

	s_defaultContext = newTState;
	Script::acquireLock();
}
コード例 #18
0
/* return -1 on error, else 0 */
int BPY_button_exec(bContext *C, const char *expr, double *value, const short verbose)
{
	PyGILState_STATE gilstate;
	PyObject *py_dict, *mod, *retval;
	int error_ret = 0;
	PyObject *main_mod = NULL;
	
	if (!value || !expr) return -1;

	if (expr[0] == '\0') {
		*value = 0.0;
		return error_ret;
	}

	bpy_context_set(C, &gilstate);

	PyC_MainModule_Backup(&main_mod);

	py_dict = PyC_DefaultNameSpace("<blender button>");

	mod = PyImport_ImportModule("math");
	if (mod) {
		PyDict_Merge(py_dict, PyModule_GetDict(mod), 0); /* 0 - don't overwrite existing values */
		Py_DECREF(mod);
	}
	else { /* highly unlikely but possibly */
		PyErr_Print();
		PyErr_Clear();
	}
	
	retval = PyRun_String(expr, Py_eval_input, py_dict, py_dict);
	
	if (retval == NULL) {
		error_ret = -1;
	}
	else {
		double val;

		if (PyTuple_Check(retval)) {
			/* Users my have typed in 10km, 2m
			 * add up all values */
			int i;
			val = 0.0;

			for (i = 0; i < PyTuple_GET_SIZE(retval); i++) {
				val += PyFloat_AsDouble(PyTuple_GET_ITEM(retval, i));
			}
		}
		else {
			val = PyFloat_AsDouble(retval);
		}
		Py_DECREF(retval);
		
		if (val == -1 && PyErr_Occurred()) {
			error_ret = -1;
		}
		else if (!finite(val)) {
			*value = 0.0;
		}
		else {
			*value = val;
		}
	}
	
	if (error_ret) {
		if (verbose) {
			BPy_errors_to_report(CTX_wm_reports(C));
		}
		else {
			PyErr_Clear();
		}
	}

	PyC_MainModule_Backup(&main_mod);
	
	bpy_context_clear(C, &gilstate);
	
	return error_ret;
}
コード例 #19
0
static PyObject *
partial_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
    PyObject *func, *pargs, *nargs, *pkw;
    partialobject *pto;

    if (PyTuple_GET_SIZE(args) < 1) {
        PyErr_SetString(PyExc_TypeError,
                        "type 'partial' takes at least one argument");
        return NULL;
    }

    pargs = pkw = NULL;
    func = PyTuple_GET_ITEM(args, 0);
    if (Py_TYPE(func) == &partial_type && type == &partial_type) {
        partialobject *part = (partialobject *)func;
        if (part->dict == NULL) {
            pargs = part->args;
            pkw = part->kw;
            func = part->fn;
            assert(PyTuple_Check(pargs));
            assert(PyDict_Check(pkw));
        }
    }
    if (!PyCallable_Check(func)) {
        PyErr_SetString(PyExc_TypeError,
                        "the first argument must be callable");
        return NULL;
    }

    /* create partialobject structure */
    pto = (partialobject *)type->tp_alloc(type, 0);
    if (pto == NULL)
        return NULL;

    pto->fn = func;
    Py_INCREF(func);

    nargs = PyTuple_GetSlice(args, 1, PY_SSIZE_T_MAX);
    if (nargs == NULL) {
        Py_DECREF(pto);
        return NULL;
    }
    if (pargs == NULL || PyTuple_GET_SIZE(pargs) == 0) {
        pto->args = nargs;
        Py_INCREF(nargs);
    }
    else if (PyTuple_GET_SIZE(nargs) == 0) {
        pto->args = pargs;
        Py_INCREF(pargs);
    }
    else {
        pto->args = PySequence_Concat(pargs, nargs);
        if (pto->args == NULL) {
            Py_DECREF(nargs);
            Py_DECREF(pto);
            return NULL;
        }
        assert(PyTuple_Check(pto->args));
    }
    Py_DECREF(nargs);

    if (pkw == NULL || PyDict_GET_SIZE(pkw) == 0) {
        if (kw == NULL) {
            pto->kw = PyDict_New();
        }
        else {
            Py_INCREF(kw);
            pto->kw = kw;
        }
    }
    else {
        pto->kw = PyDict_Copy(pkw);
        if (kw != NULL && pto->kw != NULL) {
            if (PyDict_Merge(pto->kw, kw, 1) != 0) {
                Py_DECREF(pto);
                return NULL;
            }
        }
    }
    if (pto->kw == NULL) {
        Py_DECREF(pto);
        return NULL;
    }

    return (PyObject *)pto;
}
コード例 #20
0
static PyObject *
partial_call(partialobject *pto, PyObject *args, PyObject *kw)
{
    PyObject *ret;
    PyObject *argappl, *kwappl;
    PyObject **stack;
    Py_ssize_t nargs;

    assert (PyCallable_Check(pto->fn));
    assert (PyTuple_Check(pto->args));
    assert (PyDict_Check(pto->kw));

    if (PyTuple_GET_SIZE(pto->args) == 0) {
        stack = &PyTuple_GET_ITEM(args, 0);
        nargs = PyTuple_GET_SIZE(args);
        argappl = NULL;
    }
    else if (PyTuple_GET_SIZE(args) == 0) {
        stack = &PyTuple_GET_ITEM(pto->args, 0);
        nargs = PyTuple_GET_SIZE(pto->args);
        argappl = NULL;
    }
    else {
        stack = NULL;
        argappl = PySequence_Concat(pto->args, args);
        if (argappl == NULL) {
            return NULL;
        }

        assert(PyTuple_Check(argappl));
    }

    if (PyDict_GET_SIZE(pto->kw) == 0) {
        kwappl = kw;
        Py_XINCREF(kwappl);
    }
    else {
        kwappl = PyDict_Copy(pto->kw);
        if (kwappl == NULL) {
            Py_XDECREF(argappl);
            return NULL;
        }

        if (kw != NULL) {
            if (PyDict_Merge(kwappl, kw, 1) != 0) {
                Py_XDECREF(argappl);
                Py_DECREF(kwappl);
                return NULL;
            }
        }
    }

    if (stack) {
        ret = _PyObject_FastCallDict(pto->fn, stack, nargs, kwappl);
    }
    else {
        ret = PyObject_Call(pto->fn, argappl, kwappl);
        Py_DECREF(argappl);
    }
    Py_XDECREF(kwappl);
    return ret;
}
コード例 #21
0
void ElementDocumentWrapper::LoadScript(Rocket::Core::Stream* stream, const Rocket::Core::String& source_name)
{	
	// If theres a source, check if the code is already loaded and just reuse it
	if (!source_name.Empty())
	{		
		Rocket::Core::String module_name = Rocket::Core::String(source_name).Replace("/", "_");
		module_name = module_name.Replace("\\", "_");
		module_name = module_name.Replace(".py", "");

		PyObject* modules = PyImport_GetModuleDict();
		PyObject* merge_module = PyDict_GetItemString(modules, module_name.CString());

#ifdef ROCKET_DEBUG
		// In debug builds, force module to NULL so that scripts are always reloaded
		merge_module = NULL;
#else
		if (merge_module)
		{
			Py_INCREF(merge_module);
		}
#endif

		if (!merge_module)
		{
			// Compile the code as a python module
			Rocket::Core::String source_buffer;
			PreprocessCode(source_buffer, stream);		
		
			PyObject* code = Py_CompileString(source_buffer.CString(), source_name.CString(), Py_file_input);
			if (code)
			{
				merge_module = PyImport_ExecCodeModule((char*)module_name.CString(), code);
				Py_DECREF(code);
			}			
		}

		if (merge_module)
		{
			PyObject* dict = PyModule_GetDict(merge_module);
			PyDict_Merge(module_namespace, dict, 0);
			Py_DECREF(merge_module);
		}
		else
		{
			Rocket::Core::Python::Utilities::PrintError();			
		}
	}
	else
	{
		// Compile directly onto the python module
		Rocket::Core::String source_buffer;
		PreprocessCode(source_buffer, stream);
		
		PyObject* result = PyRun_String(source_buffer.CString(), Py_file_input, module_namespace, module_namespace);
		if ( !result )
		{
			Rocket::Core::Python::Utilities::PrintError();
		}
		else
		{
			Py_DECREF(result);
		}	
	}
}
コード例 #22
0
static PyObject * ntracenative_frameSetLocals(PyObject *self, PyObject *args)
{
    PyObject *frameobj = NULL,*dict = NULL;
    PyFrameObject *frame;

    (void) self;

    
//printf("before parse\n");
    if (!PyArg_ParseTuple( args, "OO", &frameobj, &dict))
    {
	return NULL;
    }	

//printf("before framecheck frameobj=%p dict=%p\n", frameobj, dict);

    if ( frameobj == NULL || !PyFrame_Check(frameobj) ) // check if frame tame
    {
	return NULL;
    }

//printf("before dictcheck dict=%p\n", dict);
                             
    if ( !PyDict_Check(dict) )
    {
	return NULL;
    }	

//printf("allchecks ok\n");

    frame = (PyFrameObject *) frameobj;
    if (PyDict_CheckExact(frame->f_locals))    
    {
	PyObject *oldLocals;


//printf("set f_locals\n");

	PyDict_Merge(dict, frame->f_locals, 1); // 1 - add reference to keys and values
    	Py_INCREF(dict);


	oldLocals = frame->f_locals;

    	frame->f_locals = dict;

	if (oldLocals != NULL)
		Py_DECREF( oldLocals );
    }


#if 0
    if (PyDict_CheckExact(frame->f_globals))    
    {
	PyObject *oldLocals;

	PyDict_Merge(dict, frame->f_globals, 1); // 1 - add reference to keys and values
    	Py_INCREF(dict);


	oldLocals = frame->f_globals;

    	frame->f_globals = dict;

	if (oldLocals != NULL)
		Py_DECREF( oldLocals );
    }
#endif

    return Py_BuildValue("i", 0);
} 
コード例 #23
0
ファイル: dict.cpp プロジェクト: jvkersch/pyston
extern "C" int PyDict_Update(PyObject* a, PyObject* b) noexcept {
    return PyDict_Merge(a, b, 1);
}