Exemplo n.º 1
0
static PyObject*
default_factory( Member* member, PyObject* owner )
{
    PyTuplePtr args( PyTuple_New( 0 ) );
    if( !args )
        return 0;
    PyObjectPtr callable( newref( member->default_context ) );
    return callable( args ).release();
}
Exemplo n.º 2
0
static PyObject*
default_owner_method( Member* member, PyObject* owner )
{
    if( !PyString_Check( member->default_context ) )
        return py_type_fail( "default owner method name must be a string" );
    PyObjectPtr callable( PyObject_GetAttr( owner, member->default_context ) );
    if( !callable )
        return 0;
    PyTuplePtr args( PyTuple_New( 0 ) );
    if( !args )
        return 0;
    return callable( args ).release();
}
Exemplo n.º 3
0
static PyObject*
post_validate_owner_method( Member* member, PyObject* owner, PyObject* oldvalue, PyObject* newvalue )
{
    if( !PyString_Check( member->post_validate_context ) )
        return py_type_fail( "post validate owner method name must be a string" );
    PyObjectPtr callable( PyObject_GetAttr( owner, member->post_validate_context ) );
    if( !callable )
        return 0;
    PyTuplePtr args( PyTuple_New( 2 ) );
    if( !args )
        return 0;
    args.set_item( 0, newref( oldvalue ) );
    args.set_item( 1, newref( newvalue ) );
    return callable( args ).release();
}
Exemplo n.º 4
0
int get_code(unsigned* pycbuf, struct code_obj* pobj, int cur, int size)
{
    int func_idx = 0;
    int op_arg = 0;
    int num_obj = 1;
    int dealt = 0;
    int len = length(pycbuf, cur-5);
    int end = cur + len;
    while (cur < end-1 && !(cur >= size)) {
        if(!(callable(cur, pycbuf))) {
            field_add(&(pobj->code), pycbuf[cur]);
            if (have_arg(pycbuf[cur])) {
                op_arg = get_op_arg(pycbuf, cur);
                field_add(&(pobj->code), op_arg);
                cur += 3;
            } else {
                cur += 1; 
            }
        } else {
            //printf("****:dealing function\n");
            dealt = find_next_callable(pycbuf, cur, num_obj);
            struct code_obj* pnew_obj = malloc(sizeof(*pnew_obj));
            func_idx = get_fields(pycbuf, pnew_obj, dealt, size); /* get fields of the entire code object */
            objects[func_idx]->val.pobj =  pnew_obj;
            objects[func_idx]->type =  TYPE_CODE;
            num_obj++;
            cur += 9; 
        }
    }
    field_add(&(pobj->code), pycbuf[cur]);
    return cur+1; 
}
Exemplo n.º 5
0
		void operator() (types... args)
		{
			for (auto& callable : this->callables)
			{
				callable(args...);
			}
		}
Exemplo n.º 6
0
void every(const double delay, SharedPtr<Reactor> reactor,
        Callback<Error> &&callback, std::function<bool()> &&stop_predicate,
        Callback<> &&callable) {
    reactor->call_soon([
        =, callback = std::move(callback),
        stop_predicate = std::move(stop_predicate),
        callable = std::move(callable)
    ]() mutable {
        if (delay <= 0.0) {
            callback(ValueError());
            return;
        }
        if (stop_predicate()) {
            callback(NoError());
            return;
        }
        callable();
        reactor->call_later(delay, [
            =, callback = std::move(callback),
            stop_predicate = std::move(stop_predicate),
            callable = std::move(callable)
        ]() mutable {
            every(delay, reactor, std::move(callback),
                    std::move(stop_predicate), std::move(callable));
        });
    });
}
Exemplo n.º 7
0
 static typename std::enable_if<!ndt::has_traits<KernelType>::value, callable>::type
 make(const ndt::type &tp, StaticDataType &&static_data)
 {
   return callable(tp, detail::get_targets<KernelType>(), detail::get_ir<KernelType>(),
                   std::forward<StaticDataType>(static_data), &KernelType::alloc, &KernelType::data_init,
                   &KernelType::resolve_dst_type, &KernelType::instantiate);
 }
Exemplo n.º 8
0
 callable multidispatch(const ndt::type &self_tp,
                        const std::initializer_list<callable> &children,
                        const callable &default_child = callable())
 {
   return multidispatch<N>(self_tp, children.begin(), children.end(),
                           default_child);
 }
Exemplo n.º 9
0
v8::Handle<v8::Value> Session::sendNativePdu(const v8::Arguments& args) {
    UNWRAP(Session, wrap, args.This());
    SwapScope scope(wrap, args);
    if(0 == wrap->session_) {
        return ThrowError("Session hasn't opened.");
    }

    if(2 != args.Length()) {
        return ThrowError("Must pass pdu and cb arguments to sendNativePdu.");
    }

    v8::Handle<v8::Object> cb = args[1]->ToObject();
    if (!cb->IsCallable()) {
        return ThrowError("Must pass pdu and cb arguments to sendNativePdu.");
    }

    UNWRAP(Pdu, pdu, args[0]->ToObject());

	std::auto_ptr<netsnmp_pdu> copy(pdu->is_owner()? pdu->release() : snmp_clone_pdu(pdu->native()));
    std::auto_ptr<Callable> callable(new Callable(cb, args[0], copy.get()));
    if(0 == snmp_sess_async_send(wrap->session_, copy.get(),
                                 Callable::OnEvent, callable.get())) {
        return ThrowError(snmp_api_errstring(wrap->arguments_.s_snmp_errno));
    }
    callable.release();
    copy.release();

    if(scope.hasException()) {
        return scope.getException();
    }
    return v8::Undefined();
}
 RT operator( )( )
 {
     PyGILState_STATE gstate = PyGILState_Ensure();
     RT result = boost::python::extract<RT>( callable( ) );
     PyGILState_Release( gstate );
     return result;
 }
Exemplo n.º 11
0
 inline
 int
 main_with_catch(
   int argc,
   char const* argv[],
   void (*callable)(int argc, char const* argv[]))
 {
   user_plus_system_time();
   if (!check_fem_utils_int_types()) {
     return 255;
   }
   try {
     callable(argc, argv);
   }
   catch (fem::stop_info const& info) {
     std::fflush(stdout);
     std::fprintf(stderr, "%s\n", info.what());
     std::fflush(stderr);
   }
   catch (std::exception const& e) {
     std::fflush(stdout);
     char const* what = e.what();
     if (what == 0) what = "null";
     std::fprintf(stderr, "std::exception what(): %s\n", what);
     std::fflush(stderr);
     return 1;
   }
   catch (...) {
     std::fflush(stdout);
     std::fprintf(stderr, "Terminated by unknown C++ exception.\n");
     std::fflush(stderr);
     return 2;
   }
   return 0;
 }
void test_thread_callable_object_no_arguments()
{
    callable_no_args func;
    boost::thread callable(func);
    callable.join();
    BOOST_CHECK(callable_no_args::called);
}
void test_thread_callable_object_one_argument()
{
    callable_one_arg func;
    boost::thread callable(func,42);
    callable.join();
    BOOST_CHECK(callable_one_arg::called);
    BOOST_CHECK_EQUAL(callable_one_arg::called_arg,42);
}
Exemplo n.º 14
0
variant candidate_action_with_filters::do_filtering(ai::formula_ai* ai, variant& input, game_logic::const_formula_ptr formula)
{
	game_logic::map_formula_callable callable(static_cast<const formula_callable*>(ai));
	callable.add("input", input);

	return formula::evaluate(formula, callable);

}
Exemplo n.º 15
0
Thread::Thread(EventLoop& loop)
: _state(Thread::Ready)
, _detach(false)
, _impl(0)
{
    _impl = new ThreadImpl();
    _impl->init( callable(loop, &EventLoop::run) );
}
Exemplo n.º 16
0
 static inline
 R
 apply(const F& callable,
       const msgpack::object * /* packed */,
       Args&&... args)
 {
     return callable(std::forward<Args>(args)...);
 }
Exemplo n.º 17
0
int citizen::would_accept_job(const_job_ptr j, const money_market& m, const hex::tile& t, int rank) const
{
	if(!wages_wanted_formula) {
		return -1;
	}

	job_callable callable(*this, j, m, t, rank);
	return wages_wanted_formula->execute(callable).as_int();
}
Exemplo n.º 18
0
int citizen::would_change_occupation(const occupation& o, const money_market& m, const hex::tile& t, int rank) const
{
	if(!wages_wanted_formula) {
		return -1;
	}

	job_callable callable(*this, const_job_ptr(), m, t, rank);
	return wages_wanted_formula->execute(callable).as_int();
}
Exemplo n.º 19
0
  SEXP pycall__callable(SEXP Rfun, SEXP Rargv_list, SEXP Rargv_dict) {
#ifdef REMBEDPY_DEBUG
  	Rprintf("callable\n");
#endif
  	Rcpp::S4 fun(Rfun);
  	PyObjPtr pcallable(Rcpp::wrap(fun.slot("ptr")));
  	boost::python::object& callable(*pcallable);
  	boost::python::list argv_list(RembedPy::extract_argv_list(Rargv_list));
    boost::python::dict argv_dict(RembedPy::extract_argv_dict(Rargv_dict));
  	return RembedPy::pycall(callable, argv_list, argv_dict);
  }
Exemplo n.º 20
0
void level_runner::video_resize_event(const SDL_Event &event)
{
    const SDL_ResizeEvent* resize = reinterpret_cast<const SDL_ResizeEvent*>(&event);
    int width = resize->w;
    int height = resize->h;

	static const int WindowResizeEventID = get_object_event_id("window_resize");
	game_logic::map_formula_callable_ptr callable(new game_logic::map_formula_callable);
	callable->add("width", variant(width));
	callable->add("height", variant(height));
	lvl_->player()->get_entity().handle_event(WindowResizeEventID, callable.get());
}
Exemplo n.º 21
0
  SEXP pycall__funname(SEXP Rmodule_name, SEXP Rfun_name, SEXP Rargv_list, SEXP Rargv_dict) {
#ifdef REMBEDPY_DEBUG
    Rprintf("funname\n");
#endif
    std::string 
  		fun_name(Rcpp::as<std::string>(Rfun_name)),
  		module_name(Rcpp::as<std::string>(Rmodule_name));
    boost::python::object callable(RembedPy::extract_pyobj(fun_name, module_name));
    boost::python::list argv_list(RembedPy::extract_argv_list(Rargv_list));
    boost::python::dict argv_dict(RembedPy::extract_argv_dict(Rargv_dict));
    return RembedPy::pycall(callable, argv_list, argv_dict);
  }
Exemplo n.º 22
0
//-------------------------------------------------------------------------------------------------
Value Function::call(const UserObject& object, const Args& args) const
{
    // Check if the function is callable
    if (!callable(object))
        CAMP_ERROR(ForbiddenCall(name()));

    // Check the number of arguments
    if (args.count() < m_argTypes.size())
        CAMP_ERROR(NotEnoughArguments(name(), args.count(), m_argTypes.size()));

    // Execute the function
    return execute(object, args);
}
Exemplo n.º 23
0
 callable multidispatch(const ndt::type &self_tp, const IteratorType &begin,
                        const IteratorType &end,
                        const callable &default_child = callable())
 {
   switch (self_tp.extended<ndt::callable_type>()->get_npos()) {
   case 1:
     return multidispatch<1>(self_tp, begin, end, default_child);
   case 2:
     return multidispatch<2>(self_tp, begin, end, default_child);
   default:
     throw std::runtime_error("error");
   }
 }
nsresult
DOMEventTargetHelper::SetEventHandler(nsIAtom* aType,
                                      JSContext* aCx,
                                      const JS::Value& aValue)
{
  RefPtr<EventHandlerNonNull> handler;
  JS::Rooted<JSObject*> callable(aCx);
  if (aValue.isObject() && JS::IsCallable(callable = &aValue.toObject())) {
    handler = new EventHandlerNonNull(aCx, callable, dom::GetIncumbentGlobal());
  }
  SetEventHandler(aType, EmptyString(), handler);
  return NS_OK;
}
Exemplo n.º 25
0
    callable multidispatch(const ndt::type &self_tp, T &&children,
                           const callable &default_child,
                           const std::vector<intptr_t> &permutation)
    {
      using base_static_data =
          detail::multidispatch_base_static_data<N, T, ArraySubscript>;

      struct static_data : base_static_data {
        size_t data_size_max;
        intptr_t permutation[N];

        static_data(T &&children, const callable &default_child,
                    size_t data_size_max, const intptr_t *permutation)
            : base_static_data(std::forward<T>(children), default_child),
              data_size_max(data_size_max)
        {
          std::memcpy(this->permutation, permutation,
                      sizeof(this->permutation));
        }

        const callable &operator()(const ndt::type &dst_tp, intptr_t nsrc,
                                   const ndt::type *src_tp)
        {
          std::vector<ndt::type> tp;
          tp.push_back(dst_tp);
          for (int j = 0; j < nsrc; ++j) {
            tp.push_back(src_tp[j]);
          }
          ndt::type *new_src_tp = tp.data() + 1;

          std::array<type_id_t, N> key;
          for (int i = 0; i < N; ++i) {
            key[i] = (new_src_tp + permutation[i])->get_type_id();
          }

          return base_static_data::operator()(key);
        }
      };

      detail::multidispatch_match<N, (ArraySubscript ? 1 : N)>(
          self_tp, children, default_child);
      return callable::make<multidispatch_kernel<static_data>>(
          self_tp,
          std::make_shared<static_data>(std::forward<T>(children),
                                        default_child, 0, permutation.data()),
          0);
    }
Exemplo n.º 26
0
void citizen::place_orders(money_market& m)
{
	money_market_callable callable(*this, m);
	for(buy_sell_mapping::const_iterator i = buy_quantity_formula_map.begin();
	    i != buy_quantity_formula_map.end(); ++i) {
		const int quantity = i->second->execute(callable).as_int();
		if(quantity > 0) {
			buy_sell_mapping::const_iterator j = buy_formula_map.find(i->first);
			if(j != buy_formula_map.end()) {
				const int price = j->second->execute(callable).as_int();
				if(price > 0) {
					money_market::offer offer;
					offer.type = item_type::get(i->first);
					if(offer.type) {
						offer.quantity = quantity;
						offer.price = price;
						offer.trader = this;
						m.add_buy(offer);
					}
				}
			}
		}
	}

	for(buy_sell_mapping::const_iterator i = sell_quantity_formula_map.begin();
	    i != sell_quantity_formula_map.end(); ++i) {
		const int quantity = i->second->execute(callable).as_int();
		if(quantity > 0) {
			buy_sell_mapping::const_iterator j = sell_formula_map.find(i->first);
			if(j != sell_formula_map.end()) {
				const int price = j->second->execute(callable).as_int();
				if(price > 0) {
					money_market::offer offer;
					offer.type = item_type::get(i->first);
					if(offer.type) {
						offer.quantity = quantity;
						offer.price = price;
						offer.trader = this;
						m.add_sell(offer);
					}
				}
			}
		}
	}

}
Exemplo n.º 27
0
    void ThreadPoolImpl::start()
    {
        if (_state != Stopped)
            throw std::logic_error("invalid state");

        _state = Starting;

        while (_threads.size() < _size)
            _threads.push_back(new AttachedThread(callable(*this, &ThreadPoolImpl::threadFunc)));

        _state = Running;

        for (ThreadsType::iterator it = _threads.begin(); it != _threads.end(); ++it)
        {
            log_debug("start thread " << static_cast<void*>(*it));
            (*it)->start();
        }
    }
bool stage_side_formulas::do_play_stage()
{
	game_logic::map_formula_callable callable(&fai_);
	callable.add_ref();
	try {
		if (move_formula_) {
			while( !fai_.make_action(move_formula_,callable).is_empty() ) { }
		} else {
			WRN_AI << "Side formula skipped, maybe it's empty or incorrect" << std::endl;
		}
	}
	catch(game_logic::formula_error& e) {
		if(e.filename == "formula") {
			e.line = 0;
		}
		fai_.handle_exception( e, "Formula error");
	}
	return false;
}
Exemplo n.º 29
0
void move_candidate_action::evaluate(ai::formula_ai* ai, unit_map& units)
{
	score_ = 0;

	candidate_action_filters::const_iterator me_filter = filter_map_.find("me");

	std::vector<variant> unit_vector;

	for(unit_map::unit_iterator i = units.begin() ; i != units.end() ; ++i)
	{
		if (i->side() == ai->get_side() && i->movement_left() > 0) {
			unit_vector.push_back(variant(new unit_callable(*i)));
		}
	}

	variant my_units(&unit_vector);

	variant filtered_units;
	try {
		if(me_filter != filter_map_.end() )
			filtered_units = do_filtering(ai, my_units, me_filter->second);
		else
			filtered_units=my_units;
	}
	catch(formula_error& e) {
		ai->handle_exception(e, "Error while executing filter formula for '" + get_name() + "' Candidate Action");
		return;
	}

	for(variant_iterator i = filtered_units.begin() ; i != filtered_units.end() ; ++i)
	{
			game_logic::map_formula_callable callable(static_cast<const formula_callable*>(ai));
			callable.add("me", *i);

			int res = execute_formula(eval_, callable, ai);

			if(res > score_) {
				score_ = res;
				my_unit_ = *i;
			}
	}
}
Exemplo n.º 30
0
void bot::process(const boost::system::error_code& error)
{
	if(error == boost::asio::error::operation_aborted) {
		std::cerr << "tbs::bot::process cancelled" << std::endl;
		return;
	}
	if(on_create_) {
		execute_command(on_create_->execute(*this));
		on_create_.reset();
	}

	if(((!client_ && !preferences::internal_tbs_server()) || (!internal_client_ && preferences::internal_tbs_server()))
		&& response_.size() < script_.size()) {
		variant script = script_[response_.size()];
		variant send = script["send"];
		if(send.is_string()) {
			send = game_logic::formula(send).execute(*this);
		}

		int session_id = -1;
		if(script.has_key("session_id")) {
			session_id = script["session_id"].as_int();
		}

		std::cerr << "BOT SEND REQUEST\n";

		ASSERT_LOG(send.is_map(), "NO REQUEST TO SEND: " << send.write_json() << " IN " << script.write_json());
		game_logic::map_formula_callable_ptr callable(new game_logic::map_formula_callable(this));
		if(preferences::internal_tbs_server()) {
			internal_client_.reset(new internal_client(session_id));
			internal_client_->send_request(send, session_id, callable, boost::bind(&bot::handle_response, this, _1, callable));
		} else {
			client_.reset(new client(host_, port_, session_id, &service_));
			client_->send_request(send.write_json(), callable, boost::bind(&bot::handle_response, this, _1, callable));
		}
	}

	timer_.expires_from_now(boost::posix_time::milliseconds(100));
	timer_.async_wait(boost::bind(&bot::process, this, boost::asio::placeholders::error));
}