// ============================================================================= int * Epetra_NumPyIntVector::getArray(const Epetra_BlockMap & blockMap, PyObject * pyObject) { // Only build the tmp_array if it does not already exist if (!tmp_array) { // Default dimensions npy_intp defaultDims[ ] = { blockMap.NumMyPoints() }; // PyObject argument is a bool if (PyBool_Check(pyObject)) { tmp_array = (PyArrayObject *) PyArray_SimpleNew(1,defaultDims,NPY_INT); } // PyObject argument is not a bool ... try to build a contiguous // PyArrayObject from it else { tmp_array = (PyArrayObject *) PyArray_ContiguousFromObject(pyObject,NPY_INT,0,0); } // If any PyArray factory functions fail, clean up and throw a // PythonException if (!tmp_array) { cleanup(); throw PythonException(); } int nd = PyArray_NDIM(tmp_array); npy_intp arraySize = PyArray_MultiplyList(PyArray_DIMS(tmp_array),nd); if (arraySize != defaultDims[0]) { PyArrayObject * myArray = (PyArrayObject *) PyArray_SimpleNew(1,defaultDims,NPY_INT); if (!myArray) { cleanup(); throw PythonException(); } int * myData = (int *) PyArray_DATA(myArray); int * tmpData = (int *) PyArray_DATA(tmp_array); for (int i=0; i<defaultDims[0]; i++) { myData[i] = tmpData[i]; } Py_XDECREF(tmp_array); tmp_array = myArray; } } return (int*)(PyArray_DATA(tmp_array)); }
static int Context_setOptionNoAutoAnonymousLogin (Context *self, PyObject *value, void *closure) { if (!PyBool_Check (value)) { PyErr_SetString (PyExc_TypeError, "must be Boolean"); return -1; } smbc_setOptionNoAutoAnonymousLogin (self->context, value == Py_True); return 0; }
static unaryfunc* get_slot(PyObject* obj) { PyNumberMethods* number_methods = obj->ob_type->tp_as_number; if (number_methods == 0) return 0; return ( #if PY_VERSION_HEX >= 0x02040000 && defined(BOOST_PYTHON_BOOL_INT_STRICT) !PyBool_Check(obj) && #endif (PyInt_Check(obj) || PyLong_Check(obj))) ? &py_object_identity : 0; }
static int pshoutobj_set_bool(ShoutObjectAttr* attr, ShoutObject* self, PyObject* v) { long val; pshout_set_shout_int set_shout; if (!PyBool_Check(v)) { PyErr_SetString(PyExc_TypeError, "Boolean argument required"); return -1; } val = (v == Py_True) ? 1 : 0; set_shout = (pshout_set_shout_int)attr->set_shout; return set_shout(self->conn, val); }
//------------------------------------------------------------------------------------- int VolatileInfo::pySetOptimized(PyObject *value) { if (!PyBool_Check(value)) { PyErr_Format(PyExc_AssertionError, "%s: set pitch value is not bool!\n", scriptName()); PyErr_PrintEx(0); return 0; } optimized_ = value == Py_True; return 0; }
// set depth int Image_setDepth (PyImage * self, PyObject * value, void * closure) { // check parameter, report failure if (value == NULL || !PyBool_Check(value)) { PyErr_SetString(PyExc_TypeError, "The value must be a bool"); return -1; } // set scale if (self->m_image != NULL) self->m_image->setDepth(value == Py_True); // success return 0; }
static int Context_setOptionFallbackAfterKerberos (Context *self, PyObject *value, void *closure) { if (!PyBool_Check (value)) { PyErr_SetString (PyExc_TypeError, "must be Boolean"); return -1; } smbc_setOptionFallbackAfterKerberos (self->context, value == Py_True); return 0; }
// set flip static int VideoFFmpeg_setDeinterlace(PyImage *self, PyObject *value, void *closure) { // check parameter, report failure if (value == NULL || !PyBool_Check(value)) { PyErr_SetString(PyExc_TypeError, "The value must be a bool"); return -1; } // set deinterlace getFFmpeg(self)->setDeinterlace(value == Py_True); // success return 0; }
static PyObject * range_index(rangeobject *r, PyObject *ob) { PyObject *idx, *tmp; int contains; PyObject *format_tuple, *err_string; static PyObject *err_format = NULL; if (!PyLong_CheckExact(ob) && !PyBool_Check(ob)) { Py_ssize_t index; index = _PySequence_IterSearch((PyObject*)r, ob, PY_ITERSEARCH_INDEX); if (index == -1) return NULL; return PyLong_FromSsize_t(index); } contains = range_contains_long(r, ob); if (contains == -1) return NULL; if (!contains) goto value_error; tmp = PyNumber_Subtract(ob, r->start); if (tmp == NULL) return NULL; /* idx = (ob - r.start) // r.step */ idx = PyNumber_FloorDivide(tmp, r->step); Py_DECREF(tmp); return idx; value_error: /* object is not in the range */ if (err_format == NULL) { err_format = PyUnicode_FromString("%r is not in range"); if (err_format == NULL) return NULL; } format_tuple = PyTuple_Pack(1, ob); if (format_tuple == NULL) return NULL; err_string = PyUnicode_Format(err_format, format_tuple); Py_DECREF(format_tuple); if (err_string == NULL) return NULL; PyErr_SetObject(PyExc_ValueError, err_string); Py_DECREF(err_string); return NULL; }
static PyObject* intersection(PygtsSegment *self, PyObject *args) { PyObject *t_,*boundary_=NULL; PygtsTriangle *t; gboolean boundary=TRUE; GtsVertex *v; PygtsObject *vertex; SELF_CHECK /* Parse the args */ if(! PyArg_ParseTuple(args, "O|O", &t_, &boundary_) ) { return NULL; } /* Convert to PygtsObjects */ if(!pygts_triangle_check(t_)) { PyErr_SetString(PyExc_TypeError,"expected a Triangle and boolean"); return NULL; } t = PYGTS_TRIANGLE(t_); if( boundary_ != NULL ) { if(PyBool_Check(boundary_)==FALSE) { PyErr_SetString(PyExc_TypeError,"expected a Triangle and boolean"); return NULL; } if( boundary_ == Py_False ){ /* Default TRUE */ boundary = FALSE; } } v = GTS_VERTEX( gts_segment_triangle_intersection( PYGTS_SEGMENT_AS_GTS_SEGMENT(self), PYGTS_TRIANGLE_AS_GTS_TRIANGLE(t), boundary, GTS_POINT_CLASS(gts_vertex_class())) ); if( v == NULL ) { Py_INCREF(Py_None); return Py_None; } if( (vertex = pygts_vertex_new(v)) == NULL ) { return NULL; } return (PyObject *)vertex; }
static void x11_frame_output_cb(void *data, int video_width, int video_height, double video_pixel_aspect, int *dest_x, int *dest_y, int *dest_width, int *dest_height, double *dest_pixel_aspect, int *win_x, int *win_y) { x11_vo_user_data *user_data = (x11_vo_user_data *)data; PyObject *args, *result; PyGILState_STATE gstate; int success = 0; if (user_data->frame_output_callback && Py_IsInitialized()) { gstate = PyGILState_Ensure(); args = Py_BuildValue("(iid)", video_width, video_height, video_pixel_aspect); result = PyEval_CallObject(user_data->frame_output_callback, args); Py_DECREF(args); if (result) { if (PyBool_Check(result) || result == Py_None) { // Probably WeakCallback returning False because we're on shutdown. success = 0; } else if (!PyArg_ParseTuple(result, "(ii)(ii)(ii)d", dest_x, dest_y, win_x, win_y, dest_width, dest_height, dest_pixel_aspect)) { // FIXME: find a way to propagate this back to the main thread. printf("EXCEPTION: frame_output_cb returned bad arguments (%s).\n", result->ob_type->tp_name); PyErr_Print(); } else { success = 1; user_data->last_width = *dest_width; user_data->last_height = *dest_height; user_data->last_aspect = *dest_pixel_aspect; } Py_DECREF(result); } else { // FIXME: find a way to propagate this back to the main thread. printf("EXCEPTION in frame_output_cb!\n"); PyErr_Print(); } PyGILState_Release(gstate); } if (!success) { // Call to python space failed, but we need to set some sane defaults // here, or else xine does ugly things. So we'll use the last values. *dest_x = *dest_y = *win_x = *win_y = 0; *dest_width = user_data->last_width; *dest_height = user_data->last_height; *dest_pixel_aspect = user_data->last_aspect; } }
static nvlist_t * dict2nvl(PyObject *d) { nvlist_t *nvl; int err; PyObject *key, *value; int pos = 0; if (!PyDict_Check(d)) { PyErr_SetObject(PyExc_ValueError, d); return (NULL); } err = nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0); assert(err == 0); while (PyDict_Next(d, &pos, &key, &value)) { char *keystr = PyString_AsString(key); if (keystr == NULL) { PyErr_SetObject(PyExc_KeyError, key); nvlist_free(nvl); return (NULL); } if (PyDict_Check(value)) { nvlist_t *valnvl = dict2nvl(value); err = nvlist_add_nvlist(nvl, keystr, valnvl); nvlist_free(valnvl); } else if (value == Py_None) { err = nvlist_add_boolean(nvl, keystr); } else if (PyString_Check(value)) { char *valstr = PyString_AsString(value); err = nvlist_add_string(nvl, keystr, valstr); } else if (PyInt_Check(value)) { uint64_t valint = PyInt_AsUnsignedLongLongMask(value); err = nvlist_add_uint64(nvl, keystr, valint); } else if (PyBool_Check(value)) { boolean_t valbool = value == Py_True ? B_TRUE : B_FALSE; err = nvlist_add_boolean_value(nvl, keystr, valbool); } else { PyErr_SetObject(PyExc_ValueError, value); nvlist_free(nvl); return (NULL); } assert(err == 0); } return (nvl); }
bool FunctionParameter::check(PyObject* obj) { switch (type_) { case ParameterType::TENSOR: { return THPVariable_Check(obj); } case ParameterType::SCALAR: case ParameterType::DOUBLE: { // NOTE: we don't currently accept most NumPy types as Scalars. np.float64 // is okay because it's a subclass of PyFloat. We may want to change this // in the future. if (THPUtils_checkDouble(obj)) { return true; } if (THPVariable_Check(obj)) { auto& var = ((THPVariable*)obj)->cdata; return !var.requires_grad() && var.dim() == 0; } return false; } case ParameterType::INT64: { if (THPUtils_checkLong(obj)) { return true; } if (THPVariable_Check(obj)) { auto& var = ((THPVariable*)obj)->cdata; return at::isIntegralType(var.type().scalarType()) && !var.requires_grad() && var.dim() == 0; } return false; } case ParameterType::TENSOR_LIST: return PyTuple_Check(obj) || PyList_Check(obj); case ParameterType::INT_LIST: { if (PyTuple_Check(obj) || PyList_Check(obj)) { return true; } // if a size is specified (e.g. IntList[2]) we also allow passing a single int return size > 0 && THPUtils_checkLong(obj); } case ParameterType::GENERATOR: return THPGenerator_Check(obj); case ParameterType::BOOL: return PyBool_Check(obj); case ParameterType::STORAGE: return isStorage(obj); case ParameterType::PYOBJECT: return true; case ParameterType::SCALARTYPE: return THPDtype_Check(obj); case ParameterType::LAYOUT: return THPLayout_Check(obj); case ParameterType::DEVICE: return THPUtils_checkLong(obj) || THPUtils_checkString(obj) || THPDevice_Check(obj); case ParameterType::STRING: return THPUtils_checkString(obj); default: throw std::runtime_error("unknown parameter type"); } }
static int ids_core_Camera_setcontinuous_capture(ids_core_Camera *self, PyObject *value, void *closure) { int ret; if (value == NULL) { PyErr_SetString(PyExc_TypeError, "Cannot delete attribute 'continuous_capture'"); return -1; } if (!PyBool_Check(value)) { PyErr_SetString(PyExc_TypeError, "Attribute 'continuous_capture' must be boolean"); return -1; } /* Enable continuous capture */ if (value == Py_True) { ret = is_CaptureVideo(self->handle, IS_DONT_WAIT); switch (ret) { case IS_SUCCESS: break; case IS_TIMED_OUT: PyErr_SetString(PyExc_IOError, "Continuous capture start timed out."); return -1; case IS_NO_ACTIVE_IMG_MEM: PyErr_SetString(PyExc_IOError, "No image memory available."); return -1; default: raise_general_error(self, ret); return -1; } } /* Disable continuous capture */ else if (value == Py_False) { ret = is_StopLiveVideo(self->handle, IS_FORCE_VIDEO_STOP); switch (ret) { case IS_SUCCESS: break; default: raise_general_error(self, ret); return -1; } } else { PyErr_SetString(PyExc_ValueError, "Unknown boolean value"); return -1; } return 0; }
/* computeDistance */ PyObject * SymList_computeDistanceAngles(PyObject * obj, PyObject *args, PyObject *kwargs) { double rot1, tilt1, psi1, rot2, tilt2, psi2; PyObject *pyProjdirMode = Py_False; PyObject *pyCheckMirrors = Py_False; PyObject *pyObjectRotation = Py_False; if (PyArg_ParseTuple(args, "dddddd|OOO", &rot1, &tilt1, &psi1, &rot2, &tilt2, &psi2, &pyProjdirMode, &pyCheckMirrors, &pyObjectRotation)) { try { bool projdir_mode = false; bool check_mirrors = false; bool object_rotation = false; if (PyBool_Check(pyProjdirMode)) projdir_mode = (pyProjdirMode == Py_True); if (PyBool_Check(pyCheckMirrors)) check_mirrors = (pyCheckMirrors == Py_True); if (PyBool_Check(pyObjectRotation)) object_rotation = (pyObjectRotation == Py_True); SymListObject *self = (SymListObject*) obj; double dist=self->symlist->computeDistance(rot1,tilt1,psi1,rot2,tilt2,psi2, projdir_mode,check_mirrors,object_rotation); return PyFloat_FromDouble(dist); } catch (XmippError &xe) { PyErr_SetString(PyXmippError, xe.msg.c_str()); } } return NULL; }
Visitor::Result PythonVisitor::processNodeTopDown(simulation::Node* node) { PyObject *res=PyObject_CallMethod(m_PyVisitor,const_cast<char*>("processNodeTopDown"),const_cast<char*>("(O)"),SP_BUILD_PYSPTR(node)); if (!res) { printf("<SofaPython> exception\n"); PyErr_Print(); return Visitor::RESULT_PRUNE; } if (PyBool_Check(res)) return Visitor::RESULT_CONTINUE; return Visitor::RESULT_PRUNE; }
//----------------------------------------------------------------------------- // Variable_TypeByValue() // Return a variable type given a Python object or NULL if the Python // object does not have a corresponding variable type. //----------------------------------------------------------------------------- static udt_VariableType *Variable_TypeByValue( PyObject* value, // Python type SQLUINTEGER* size) // size to use (OUT) { if (value == Py_None) { *size = 1; return &ceString_VariableType; } if (ceString_Check(value)) { *size = ceString_GetSize(value); return &ceString_VariableType; } #if PY_MAJOR_VERSION < 3 if (PyUnicode_Check(value)) { *size = PyUnicode_GET_SIZE(value); return &vt_Unicode; } #endif if (ceBinary_Check(value)) { udt_StringBuffer temp; if (StringBuffer_FromBinary(&temp, value) < 0) return NULL; *size = temp.size; StringBuffer_Clear(&temp); return &vt_Binary; } if (PyBool_Check(value)) return &vt_Bit; if (PyInt_Check(value)) return &vt_Integer; if (PyLong_Check(value)) return &vt_BigInteger; if (PyFloat_Check(value)) return &vt_Double; if (Py_TYPE(value) == (PyTypeObject*) g_DecimalType) return &vt_Decimal; if (PyTime_Check(value)) return &vt_Time; if (PyDateTime_Check(value)) return &vt_Timestamp; if (PyDate_Check(value)) return &vt_Timestamp; PyErr_Format(g_NotSupportedErrorException, "Variable_TypeByValue(): unhandled data type %s", Py_TYPE(value)->tp_name); return NULL; }
/** * Return a string for the array type to check the map for. * @param object :: Python object to check if it's an array * @return :: A string as the array type. */ const std::string PropertyWithValueFactory::isArray(PyObject *const object) { if (PyList_Check(object) || PyTuple_Check(object)) { // If we are dealing with an empty list/tuple, then we cannot deduce the // ArrayType. We need to throw at this point. if (PySequence_Size(object) < 1) { throw std::runtime_error( "Cannot have a sequence type of length zero in a mapping type."); } PyObject *item = PySequence_Fast_GET_ITEM(object, 0); // Boolean can be cast to int, so check first. if (PyBool_Check(item)) { throw std::runtime_error( "Unable to support extracting arrays of booleans."); } if (PyLong_Check(item)) { return std::string("LongIntArray"); } #if PY_MAJOR_VERSION < 3 // In python 2 ints & longs are separate if (PyInt_Check(item)) { return std::string("IntArray"); } #endif if (PyFloat_Check(item)) { return std::string("FloatArray"); } #if PY_MAJOR_VERSION >= 3 if (PyUnicode_Check(item)) { return std::string("StringArray"); } #endif if (PyBytes_Check(item)) { return std::string("StringArray"); } // If we get here, we've found a sequence and we can't interpret the item // type. std::ostringstream os; os << "Cannot create PropertyWithValue from Python type " << object->ob_type->tp_name << " containing items of type " << item->ob_type << ". No converter registered in PropertyWithValueFactory."; throw std::invalid_argument(os.str()); } else { return std::string(""); } }
/* * PLyObject_ToJsonbValue(PyObject *obj) * * Transform python object to JsonbValue. */ static JsonbValue * PLyObject_ToJsonbValue(PyObject *obj, JsonbParseState **jsonb_state, bool is_elem) { JsonbValue buf; JsonbValue *out; if (!(PyString_Check(obj) || PyUnicode_Check(obj))) { if (PySequence_Check(obj)) return PLySequence_ToJsonbValue(obj, jsonb_state); else if (PyMapping_Check(obj)) return PLyMapping_ToJsonbValue(obj, jsonb_state); } /* Allocate JsonbValue in heap only if it is raw scalar value. */ if (*jsonb_state) out = &buf; else out = palloc(sizeof(JsonbValue)); if (obj == Py_None) out->type = jbvNull; else if (PyString_Check(obj) || PyUnicode_Check(obj)) PLyString_ToJsonbValue(obj, out); /* * PyNumber_Check() returns true for booleans, so boolean check should * come first. */ else if (PyBool_Check(obj)) { out = palloc(sizeof(JsonbValue)); out->type = jbvBool; out->val.boolean = (obj == Py_True); } else if (PyNumber_Check(obj)) out = PLyNumber_ToJsonbValue(obj, out); else ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), (errmsg("Python type \"%s\" cannot be transformed to jsonb", PLyObject_AsString((PyObject *) obj->ob_type))))); /* Push result into 'jsonb_state' unless it is raw scalar value. */ return (*jsonb_state ? pushJsonbValue(jsonb_state, is_elem ? WJB_ELEM : WJB_VALUE, out) : out); }
char __pycomps_dict_to_def_opts(PyObject* pobj, void *cobj) { PyObject *val; COMPS_DefaultsOptions ** options = (COMPS_DefaultsOptions**)cobj; int x; long tmp; const char *keys2[] = {"default_uservisible", "default_biarchonly", "default_default", NULL }; const char *keys1[] = {"default_pkgtype", NULL}; *options = malloc(sizeof(COMPS_DefaultsOptions)); bool *props2[] = {&(*options)->default_uservisible, &(*options)->default_biarchonly, &(*options)->default_default }; int *props1[] = {&(*options)->default_pkgtype}; **options = COMPS_DDefaultsOptions; if (!PyDict_Check(pobj)) { cobj = NULL; return 0; } else { for (x = 0; keys1[x] != NULL; x++) { val = PyDict_GetItemString(pobj, keys1[x]); if (val) { if (PyINT_CHECK(val)) { tmp = PyINT_ASLONG(val); } tmp = PyLong_AsLong(val); if (tmp == COMPS_PACKAGE_DEFAULT || tmp == COMPS_PACKAGE_OPTIONAL || tmp == COMPS_PACKAGE_CONDITIONAL || tmp == COMPS_PACKAGE_MANDATORY) { *props1[x] = tmp; } } } for (x = 0; keys2[x] != NULL; x++) { val = PyDict_GetItemString(pobj, keys2[x]); if (val && PyBool_Check(val)) { if (val == Py_True) *props2[x] = true; else *props2[x] = false; } } } return 1; }
char __pycomps_dict_to_xml_opts(PyObject* pobj, void *cobj) { PyObject *val; COMPS_XMLOptions ** options = (COMPS_XMLOptions**)cobj; int x; const char *keys[] = {"empty_groups", "empty_categories", "empty_environments", "empty_langpacks", "empty_blacklist", "empty_whiteout", "empty_packages", "empty_grouplist", "empty_optionlist", "uservisible_explicit", "biarchonly_explicit", "default_explicit", "gid_default_explicit", "bao_explicit", "arch_output", NULL }; *options = malloc(sizeof(COMPS_XMLOptions)); _Bool *props[] = {&(*options)->empty_groups, &(*options)->empty_categories, &(*options)->empty_environments, &(*options)->empty_langpacks, &(*options)->empty_blacklist, &(*options)->empty_whiteout, &(*options)->empty_packages, &(*options)->empty_grouplist, &(*options)->empty_optionlist, &(*options)->uservisible_explicit, &(*options)->biarchonly_explicit, &(*options)->default_explicit, &(*options)->gid_default_explicit, &(*options)->bao_explicit, &(*options)->arch_output }; **options = COMPS_XMLDefaultOptions; if (!PyDict_Check(pobj)) { cobj = NULL; return 0; } else { for (x = 0; keys[x] != NULL; x++) { val = PyDict_GetItemString(pobj, keys[x]); if (val && PyBool_Check(val)) { if (val && val == Py_True) *props[x] = true; else *props[x] = false; } } } return 1; }
static PyObject * range_count(rangeobject *r, PyObject *ob) { if (PyLong_CheckExact(ob) || PyBool_Check(ob)) { int result = range_contains_long(r, ob); if (result == -1) return NULL; return PyLong_FromLong(result); } else { Py_ssize_t count; count = _PySequence_IterSearch((PyObject*)r, ob, PY_ITERSEARCH_COUNT); if (count == -1) return NULL; return PyLong_FromSsize_t(count); } }
static int conv_pyobj_reg(PyObject *pyobj, unsigned long *reg) { #ifdef IS_PY3K if (PyLong_Check(pyobj)) { #else if (PyLong_Check(pyobj) || PyInt_Check(pyobj)) { #endif *reg = PyLong_AsUnsignedLong(pyobj); } else if (PyBool_Check(pyobj)) { *reg = (pyobj == Py_True) ? 1 : 0; } else if (PyBytes_Check(pyobj)) { *reg = (unsigned long)PyBytes_AsString(pyobj); } else { PyErr_SetString(PyExc_TypeError, "argument should be unsigned long, bool or bytes"); return 0; } if (PyErr_Occurred()) { return 0; } return 1; } static int build_regs(PyObject *args[NUM_REGS], regs_t *regs) { unsigned long *regarray[NUM_REGS] = {®s->rax, ®s->rbx, ®s->rcx, ®s->rdx, ®s->rsi, ®s->rdi}; memset(regs, 0, sizeof(*regs)); int i; for (i = 0; i < NUM_REGS; i++) { if (args[i] == NULL) { continue; } else if (!conv_pyobj_reg(args[i], regarray[i])) { return 0; } } return 1; }
const message::ptr messageW::get_message_ptr(const boost::python::object& obj){ boost::python::extract<bool> b(obj); if(PyBool_Check(obj.ptr())){ return bool_message::create(b()); } boost::python::extract<int64_t> i(obj); if (i.check()) { return int_message::create(i()); } boost::python::extract<double> d(obj); if (d.check()) { return double_message::create(d()); } boost::python::extract<std::string> s(obj); if (s.check()) { return string_message::create(s()); } boost::python::extract<boost::python::list> l(obj); if (l.check()) { boost::python::list list=l(); message::ptr ret=array_message::create(); int len = boost::python::len(list); for(int i=0; i<len; i++) { ret->get_vector().push_back(messageW::get_message_ptr(list[i])); } return ret; } boost::python::extract<boost::python::dict> m(obj); if (m.check()) { boost::python::dict dict=m(); message::ptr ret=object_message::create(); int len = boost::python::len(dict); boost::python::list keys = dict.keys(); for(int i=0; i<len; i++) { std::string k = boost::python::extract<std::string>(keys[i]); ret->get_map()[k]=messageW::get_message_ptr(dict[k]); } return ret; } if (obj.ptr() == Py_None){ return null_message::create(); } PyErr_SetString(PyExc_TypeError,"Incompatible type of message."); //std::cout<<"No type hit."<<std::endl; boost::python::throw_error_already_set(); return null_message::create(); }
int process_match_externals( PyObject* externals, YR_RULES* rules) { PyObject *key, *value; Py_ssize_t pos = 0; char* identifier = NULL; while (PyDict_Next(externals, &pos, &key, &value)) { identifier = PY_STRING_TO_C(key); if (PyBool_Check(value)) { yr_rules_define_boolean_variable( rules, identifier, PyObject_IsTrue(value)); } #if PY_MAJOR_VERSION >= 3 else if (PyLong_Check(value)) #else else if (PyLong_Check(value) || PyInt_Check(value)) #endif { yr_rules_define_integer_variable( rules, identifier, PyLong_AsLong(value)); } else if (PY_STRING_CHECK(value)) { yr_rules_define_string_variable( rules, identifier, PY_STRING_TO_C(value)); } else { return FALSE; } } return TRUE; }
int pycomps_group_boolattr_setter(PyObject *self, PyObject *val, void *closure) { long tmp; COMPS_Object *tmp_prop; if (!val) { PyErr_Format(PyExc_TypeError, "Can't delete %s", (char*)closure); return -1; } if (val && !PyBool_Check(val)) { PyErr_SetString(PyExc_TypeError, "Not bool object"); return -1; } tmp = (val == Py_True)?1:0; tmp_prop = (COMPS_Object*) comps_num(tmp); comps_objdict_set_x(((PyCOMPS_Group*)self)->group->properties, (char*)closure, tmp_prop); return 0; }
static int resizable_setter(SELF self, PyObject* value, void* closure) { if (!PyBool_Check(value)) { PyErr_SetString(PyExc_TypeError, "resizable must be a boolean value."); return -1; } // Note: Find out how to cast value (type PyObject*) to GValue, to reduce // to one single, pretty line // soy_widgets_window_set_resizable(self->g, TRUE/FALSE); if (value == Py_True) { soy_widgets_window_set_resizable(self->g, TRUE); } else { soy_widgets_window_set_resizable(self->g, FALSE); } return 0; }
static PyObject* mema_simple_exception(PyObject *self, PyObject* args) { PyObject* bool_value = NULL; if(!PyArg_ParseTuple(args, "O", &bool_value)) { return NULL; } if(!PyBool_Check(bool_value) && !PyInt_Check(bool_value)) { PyErr_SetString(PyExc_TypeError, "bool_value must be bool or integer"); return NULL; } Py_RETURN_NONE; }
Poco::SharedPtr<Poco::DynamicAny> RecordHelper::pythonObjectToAny(python::object obj) { if (PyBool_Check(obj.ptr())) { return new Poco::DynamicAny(python::extract<bool>(obj)()); } else if (PyInt_Check(obj.ptr())) { return new Poco::DynamicAny(python::extract<long>(obj)()); } else if (PyLong_Check(obj.ptr())) { return new Poco::DynamicAny(python::extract<long>(obj)()); } else if (PyFloat_Check(obj.ptr())) { return new Poco::DynamicAny(python::extract<double>(obj)()); } else if (PyString_Check(obj.ptr())) { return new Poco::DynamicAny(python::extract<std::string>(obj)()); } else if (PyUnicode_Check(obj.ptr())) { return new Poco::DynamicAny(python::extract<std::string>(python::str(obj))()); } else if (PyList_Check(obj.ptr()) || PyTuple_Check(obj.ptr())) { ssize_t max = python::len(obj); ssize_t i = 0; std::vector<Poco::DynamicAny> result; for (; i < max; ++i) { python::object item = obj[i]; result.push_back(*pythonObjectToAny(item)); } return new Poco::DynamicAny(result); } else { throw SmartCubeError("Unsupported Python object type."); } return NULL; }
/* a) Dictionary[name] = value == Dictionary.SetValue(name, value) b) Dictionary[name] = True == Dictionary.ShowSection(name) */ static int dict_ass_sub(Dictionary_Object* self, PyObject *name, PyObject *value) { if (value == NULL) { PyErr_Format(PyExc_AttributeError, "deletion of values not supported"); return -1; } const char* cname; if ((cname = PyString_AsString(name)) == NULL) { return -1; } Py_INCREF(value); if (PyBool_Check(value)) { int res; if ((res = PyObject_IsTrue(value)) == -1) { Py_DECREF(value); return -1; } if (res) { self->dict->ShowSection(ctemplate::TemplateString(cname)); } } else { char* cvalue; PyObject* strvalue; if ((strvalue = PyObject_Str(value)) == NULL) { Py_DECREF(value); return -1; } if ((cvalue = PyString_AsString(strvalue)) == NULL) { Py_DECREF(value); Py_DECREF(strvalue); return -1; } self->dict->SetValue(ctemplate::TemplateString(cname), ctemplate::TemplateString(cvalue)); } Py_DECREF(value); // XXX When strvalue is garbage collected, the internal char buffer // is freed, which invalidates the TemplateString buffer. // But then the strvalue ref is never decremented. // Py_DECREF(strvalue); return 0; }