static unsigned subs(char *p, char *q) {
	if (*q == '\0')
		return 1;
	if (*p == ',')
		return 0;
	if (*p == *q)
		return subs(p + 1, q + 1) + subs(p + 1, q);
	return subs(p + 1, q);
}
int subs(char *p, char *q) {
	if (*q == '\0')
		return 1;
	if (*p == ',')
		return 0;
	if (*p == *q)
		return subs(p + 1, q + 1) + subs(p + 1, q);
	return subs(p + 1, q);
}
示例#3
0
cv::Mat MxArray::toMat(int depth, bool transpose) const
{
    // Create cv::Mat object (of the specified depth), equivalent to mxArray
    std::vector<int> d(dims(), dims()+ndims());
    const mwSize ndims = (d.size()>2) ? d.size()-1 : d.size();
    const mwSize nchannels = (d.size()>2) ? d.back() : 1;
    depth = (depth == CV_USRTYPE1) ? DepthOf[classID()] : depth;
    std::swap(d[0], d[1]);
    cv::Mat mat(ndims, &d[0], CV_MAKETYPE(depth, nchannels));
    // Copy each channel from mxArray to Mat (converting to specified depth),
    // as in: channels[i] <- cast_to_mat_depth(p_(:,:,i))
    std::vector<cv::Mat> channels(nchannels);
    std::vector<mwSize> si(d.size(), 0);                 // subscript index
    const int type = CV_MAKETYPE(DepthOf[classID()], 1); // Source type
    for (mwIndex i = 0; i<nchannels; ++i) {
        si[si.size() - 1] = i;                   // last dim is a channel idx
        void *pd = reinterpret_cast<void*>(
            reinterpret_cast<size_t>(mxGetData(p_)) +
            mxGetElementSize(p_)*subs(si));      // ptr to i-th channel data
        const cv::Mat m(ndims, &d[0], type, pd); // only creates Mat headers
        // Read from mxArray through m, writing into channels[i]
        m.convertTo(channels[i], CV_MAKETYPE(depth, 1));
    }
    // Merge channels back into one cv::Mat array
    cv::merge(channels, mat);
    // transpose cv::Mat if needed
    if (mat.dims==2 && transpose)
        mat = mat.t();
    return mat;
}
示例#4
0
文件: theta2w.c 项目: rforge/ica4fts
/**Assumed that vector W is of a valid length such that # of elements = # of elements in Up-Trig portion of dxd matrix*/
SEXP theta2w(SEXP W){	
	
	int p;
	int *Wdims;
	double *Wptr;
	
	Wdims = getDims(W); //extract dimensions of W
	p = Wdims[0]; //number of entries
	PROTECT(W = coerceVector(W,REALSXP));
	Wptr = REAL(W);	
	
	int d = (sqrt(8*p+1) + 1)/2;	
		
	SEXP ans = identity(&d); //initialize
	SEXP interm; //intermediate matrix 
	int k = 0; //index for W
	
	for(int j=2;j<=d;j++){
		for(int i=j-1;i>=1;i--){			
			
			interm = subs(&d,&i,&j,&Wptr[k]);
			ans = matProd(interm,ans);			
	
			k++;
			
			}//end inner for		
		}//end outer for 	
		
		UNPROTECT(1);		
		return ans;
}//end function theta2w
int main(int argc, char *argv[]) {
	FILE *fp;
	unsigned i = 0, sbs = 32;
	char c;
	char *sb = malloc(sbs), *q = NULL;

	if (argc != 2) {
		printf("Usage: %s [FILE]\n", argv[0]);
		return 1;
	}
	fp = fopen(*++argv, "r");
	while ((c = getc(fp)) != EOF || i > 0) {
		if (c == '\n' || c == EOF) {
			sb[i] = '\0';
			printf("%u\n", subs(sb, q));
			i = 0;
		} else {
			if (i == sbs - 1) {
				sbs += sbs / 2;
				sb = realloc(sb, sbs);
			}
			sb[i++] = c;
			if (c == ',')
				q = sb + i;
		}
	}
	free(sb);
	return 0;
}
int main(int argc, char *argv[])
{
	FILE *fp;
	int i = 0, sbs = 32;
	char c;
	char *sb = malloc(sbs), *q;

	fp = fopen(*++argv, "r");
	while ((c = getc(fp)) != EOF || i > 0) {
		if (c == '\n' || c == EOF) {
			sb[i] = '\0';
			printf("%d\n", subs(sb, q));
			i = 0;
		} else {
			if (i == sbs - 1) {
				sbs += sbs / 2;
				sb = realloc(sb, sbs);
			}
			sb[i++] = c;
			if (c == ',')
				q = sb + i;
		}
	}
	free(sb);
	return 0;
}
示例#7
0
文件: re.cpp 项目: mogaal/cclive
bool subst(const std::string& re, std::string& src)
{
  std::string pat, sub, flags;

  static const char delims_b[] = "\\{\\<\\[\\(\\/";
  static const char delims_c[] = "\\}\\>\\]\\)\\/";

  boost::format fmt =
    boost::format("^s[%1%](.*)[%2%][%3%](.*)[%4%](.*)$")
    % delims_b % delims_c % delims_b % delims_c;

  pcrecpp::RE rx(fmt.str(), pcrecpp::UTF8());

  if (rx.PartialMatch(re, &pat, &sub, &flags))
    {
      if (src.empty()) // Verify regexp only.
        return true;

      pcrecpp::RE_Options opts = _init_re_opts(flags);
      pcrecpp::RE subs(pat, opts);
      _check_re_error(subs);

      (strstr(flags.c_str(), "g"))
      ? subs.GlobalReplace(sub, &src)
      : subs.Replace(sub, &src);

      return true;
    }
  return false;
}
示例#8
0
cv::Mat MxArray::toMat(int depth, bool transpose) const
{
    // Create cv::Mat object.
    std::vector<int> d(dims(), dims()+ndims());
    int ndims = (d.size()>2) ? d.size()-1 : d.size();
    int nchannels = (d.size()>2) ? *(d.end()-1) : 1;
    depth = (depth==CV_USRTYPE1) ? DepthOf[classID()] : depth;
    std::swap(d[0], d[1]);
    cv::Mat mat(ndims, &d[0], CV_MAKETYPE(depth, nchannels));
    // Copy each channel.
    std::vector<cv::Mat> channels(nchannels);
    std::vector<mwSize> si(d.size(), 0); // subscript index
    int type = CV_MAKETYPE(DepthOf[classID()], 1); // Source type
    for (int i = 0; i<nchannels; ++i)
    {
        si[d.size()-1] = i;
        void *pd = reinterpret_cast<void*>(
                reinterpret_cast<size_t>(mxGetData(p_))+
                mxGetElementSize(p_)*subs(si));
        cv::Mat m(ndims, &d[0], type, pd);
        // Read from mxArray through m
        m.convertTo(channels[i], CV_MAKETYPE(depth, 1));
    }
    cv::merge(channels, mat);
    return (mat.dims==2 && transpose) ? cv::Mat(mat.t()) : mat;
}
示例#9
0
 void execute(AsyncSession& session, bool isRetry)
 {
     if (isRetry) QPID_LOG(info, "Retrying...");
     session.txSelect();
     SubscriptionManager subs(session);
     transfer.subscribeToControl(subs);
     subs.run();
     session.txCommit();//commit accept of control messages
 }
示例#10
0
void Receiver::execute(AsyncSession& session, bool /*isRetry*/)
{
    SubscriptionManager subs(session);
    subscription = subs.subscribe(*this, queue, settings);
    subs.run();
    if (settings.autoAck) {
        subscription.accept(subscription.getUnaccepted());
    }
}
示例#11
0
 void main()
  {
  nodetype *ha,*hb,*hc;
  ha=create();
  hb=create();
  hc=subs(ha,hb);
  printf("A与B集合相减的结果\n");
  disp(hc);
  }
示例#12
0
void Listener::execute(AsyncSession& session, bool isRetry) {
    if (verbosity > 0)
        cout << "resuming_receiver " << (isRetry ? "first " : "re-") << "connect." << endl;
    if (!done) {
        SubscriptionManager subs(session);
        subscription = subs.subscribe(*this, queueName);
        subs.run();
    }
}
示例#13
0
int main(int argc, char *argv[] )
{
	char this_c= 'e' ;	
	char that_c = 'X' ;
	char orgstr[] = "sir sid easily teases sea sick seals" ;
		
	subs( orgstr, this_c, that_c ) ;
	printf( "Changed string: %s\n", orgstr ) ;

	exit( 0 ) ;
}
示例#14
0
void AssExporter::Export(agi::fs::path const& filename, std::string const& charset, wxWindow *export_dialog) {
	AssFile subs(*c->ass);

	for (auto filter : filters) {
		filter->LoadSettings(is_default, c);
		filter->ProcessSubs(&subs, export_dialog);
	}

	const SubtitleFormat *writer = SubtitleFormat::GetWriter(filename);
	if (!writer)
		throw agi::InvalidInputException("Unknown file type.");

	writer->ExportFile(&subs, filename, c->project->Timecodes(), charset);
}
示例#15
0
void AssExporter::Export(agi::fs::path const& filename, std::string const& charset, wxWindow *export_dialog) {
	AssFile subs(*c->ass);

	for (auto filter : filters) {
		filter->LoadSettings(is_default, c);
		filter->ProcessSubs(&subs, export_dialog);
	}

	const SubtitleFormat *writer = SubtitleFormat::GetWriter(filename);
	if (!writer)
		throw "Unknown file type.";

	writer->WriteFile(&subs, filename, charset);
}
示例#16
0
MxArray::MxArray(const cv::Mat& mat, mxClassID classid, bool transpose)
{
    // handle special case of empty input Mat by creating an empty array
    classid = (classid == mxUNKNOWN_CLASS) ? ClassIDOf[mat.depth()] : classid;
    if (mat.empty()) {
        p_ = mxCreateNumericArray(0, 0, classid, mxREAL);
        if (!p_)
            mexErrMsgIdAndTxt("mexopencv:error", "Allocation error");
        return;
    }
    // transpose cv::Mat if needed
    cv::Mat input(mat);
    if (input.dims == 2 && transpose)
        input = input.t();
    // Create a new mxArray (of the specified classID) equivalent to cv::Mat
    const mwSize nchannels = input.channels();
    const int* dims_ = input.size;
    std::vector<mwSize> d(dims_, dims_ + input.dims);
    d.push_back(nchannels);
    std::swap(d[0], d[1]);
    if (classid == mxLOGICAL_CLASS) {
        // OpenCV's logical true is any nonzero, while MATLAB's true is 1.
        cv::compare(input, 0, input, cv::CMP_NE);
        input.setTo(1, input);
        p_ = mxCreateLogicalArray(d.size(), &d[0]);
    }
    else
        p_ = mxCreateNumericArray(d.size(), &d[0], classid, mxREAL);
    if (!p_)
        mexErrMsgIdAndTxt("mexopencv:error", "Allocation error");
    // split input cv::Mat into several single-channel arrays
    std::vector<cv::Mat> channels;
    channels.reserve(nchannels);
    cv::split(input, channels);
    // Copy each channel from Mat to mxArray (converting to specified classid),
    // as in: p_(:,:,i) <- cast_to_classid_type(channels[i])
    std::vector<mwSize> si(d.size(), 0);               // subscript index
    const int type = CV_MAKETYPE(DepthOf[classid], 1); // destination type
    for (mwIndex i = 0; i < nchannels; ++i) {
        si[si.size() - 1] = i;                   // last dim is a channel index
        void *ptr = reinterpret_cast<void*>(
            reinterpret_cast<size_t>(mxGetData(p_)) +
            mxGetElementSize(p_) * subs(si));    // ptr to i-th channel data
        cv::Mat m(input.dims, dims_, type, ptr); // only creates Mat header
        channels[i].convertTo(m, type);          // Write to mxArray through m
    }
}
示例#17
0
obj macro_exec(obj lt, obj rt) {
	assert(type(lt)==tSyntaxLam);
	list ll = ul(lt);
	obj vars = Assoc();
	int suc = bind_vars(&vars, first(ll), rt);
	if(! suc) {release(vars); error("no appropriate macro.");}

	push(env);
	env = nil;
	obj el =  subs(second(ll), &vars);
	//print(el);  scroll();
	env = pop(&is);
	release(vars);	// ÇøÇÂÇ¡Ç∆ïsà¿
	obj rr = exec(el);
	release(el);
	return rr;
}
示例#18
0
MxArray::MxArray(const cv::Mat& mat, mxClassID classid, bool transpose)
{
    if (mat.empty())
    {
        p_ = mxCreateNumericArray(0, 0, mxDOUBLE_CLASS, mxREAL);
        if (!p_)
            mexErrMsgIdAndTxt("mexopencv:error", "Allocation error");
        return;
    }
    cv::Mat input = (mat.dims == 2 && transpose) ? mat.t() : mat;
    // Create a new mxArray.
    const int nchannels = input.channels();
    const int* dims_ = input.size;
    std::vector<mwSize> d(dims_, dims_ + input.dims);
    d.push_back(nchannels);
    classid = (classid == mxUNKNOWN_CLASS)
        ? ClassIDOf[input.depth()] : classid;
    std::swap(d[0], d[1]);
    if (classid == mxLOGICAL_CLASS)
    {
        // OpenCV's logical true is any nonzero while matlab's true is 1.
        cv::compare(input, 0, input, cv::CMP_NE);
        input.setTo(1, input);
        p_ = mxCreateLogicalArray(d.size(), &d[0]);
    }
    else {
        p_ = mxCreateNumericArray(d.size(), &d[0], classid, mxREAL);
    }
    if (!p_)
        mexErrMsgIdAndTxt("mexopencv:error", "Allocation error");
    // Copy each channel.
    std::vector<cv::Mat> channels;
    split(input, channels);
    std::vector<mwSize> si(d.size(), 0); // subscript index.
    int type = CV_MAKETYPE(DepthOf[classid], 1); // destination type.
    for (int i = 0; i < nchannels; ++i)
    {
        si[si.size() - 1] = i; // last dim is a channel index.
        void *ptr = reinterpret_cast<void*>(
                reinterpret_cast<size_t>(mxGetData(p_)) +
                mxGetElementSize(p_) * subs(si));
        cv::Mat m(input.dims, dims_, type, ptr);
        channels[i].convertTo(m, type); // Write to mxArray through m.
    }
}
示例#19
0
// ==================================================================
action_result_t TActionError::exec(Tractor *tractor) const
// ==================================================================
{
	T_ASSERT(tractor);

	const unsigned long level(m_error ? TLOG_TRACTOR_ERROR :
	                                    TLOG_TRACTOR_WARNING);

	tractor->setError(m_error);

	if (m_message.size() && theLogger.testLevel(level) && tractor->openLog())
	{
		QString subs(tractor->substituteValues(m_message));

		theLogger.logTractor(tractor->getLog(), level,
		                     tractor->getIndex(),
	                             tractor->topStation()->getName(),
		                     subs);
	}

	return action_result_normal;
}
示例#20
0
int main()
{
		char a[102], b[102];
 		while(scanf("%s %s",a,b)==2)
 		{
        rev(a);
        rev(b);
 
        add(a,b);
        divide(a,2);
 
        rev(a);
        printf("%s\n",a);
 
        rev(a);
        subs(a,b);
 
        rev(a);
        printf("%s\n",a);
    }
    return 0;
}
示例#21
0
文件: checkedint.c 项目: Orvid/dmd
void unittest5()
{
    bool overflow = false;
    assert(subs(2, -3, overflow) == 5);
    assert(!overflow);
    assert(subs(1, -INT32_MAX + 1, overflow) == INT32_MAX);
    assert(!overflow);
    assert(subs(INT32_MIN + 1, 1, overflow) == INT32_MIN);
    assert(!overflow);
    assert(subs(INT32_MAX, -1, overflow) == INT32_MIN);
    assert(overflow);
    overflow = false;
    assert(subs(INT32_MIN, 1, overflow) == INT32_MAX);
    assert(overflow);
    assert(subs(0, 0, overflow) == 0);
    assert(overflow);                   // sticky
}
示例#22
0
文件: checkedint.c 项目: Orvid/dmd
void unittest6()
{
    bool overflow = false;
    assert(subs(2LL, -3LL, overflow) == 5);
    assert(!overflow);
    assert(subs(1LL, -INT64_MAX + 1LL, overflow) == INT64_MAX);
    assert(!overflow);
    assert(subs(INT64_MIN + 1LL, 1LL, overflow) == INT64_MIN);
    assert(!overflow);
    assert(subs(INT64_MAX, -1LL, overflow) == INT64_MIN);
    assert(overflow);
    overflow = false;
    assert(subs(INT64_MIN, 1LL, overflow) == INT64_MAX);
    assert(overflow);
    assert(subs(0LL, 0LL, overflow) == 0);
    assert(overflow);                   // sticky
}
示例#23
0
文件: re.cpp 项目: mogaal/cclive
static void tr_subst(const std::string& r, std::string& s)
{
  pcrecpp::RE rx("^s\\/(.*)\\/(.*)\\/(.*)$", pcrecpp::UTF8());
  std::string pat, sub, flags;

  if (!rx.PartialMatch(r, &pat, &sub, &flags))
    {
      std::stringstream b;
      b << "--tr: " << "no idea what to do with `" << r << "'";
      throw std::runtime_error(b.str());
    }

  if (s.empty()) // Validate regexp only.
    return;

  pcrecpp::RE_Options o = _init_re_opts(flags);
  pcrecpp::RE subs(pat, o);
  _check_re_error(subs);

  (strstr(flags.c_str(), "g"))
  ? subs.GlobalReplace(sub, &s)
  : subs.Replace(sub, &s);
}
示例#24
0
/* function invert */
static double invert(Matrix A,Vector x,double tol,int n,int *itr)
{
  static Matrix L;
  static Matrix U;
  static Vector y;
  static Vector s;
  double c, d, xmin,lambda;
  int m, i;

  ary2(L,n+1,n+1);
  ary2(U,n+1,n+1);
  ary1(y,n+1);
  ary1(s,n+1);

  lu(A,L,U,tol,n);           // AをLU分解する。結果はLとUに入れる
				  for (m=1; m<=itr[0]; m++){
    for (i=1; i<=n; i++)
       s[i]=x[i]; 
    subs(L,U,s,y,tol,n); // LUy = s の解yを求める処理。
    c=0; d=0;
    for (i=1; i<=n; i++){
      c+=y[i]*x[i];
      d+=y[i]*y[i];
    }
    lambda =c/d;
    itr[1]=m;
    if (fabs(xmin-lambda)<tol){
      return lambda;  /* 収束した */
    }
    xmin=lambda; 
    for (i=1; i<=n; i++)
        x[i]=y[i]/sqrt(d);  // xにyを正規化して代入
				 }
  itr[1]=m;
  return lambda;  //Itr回では収束しなかった
		      }
示例#25
0
static void cmd_flush_subscriptions(
    struct watchman_client* clientbase,
    const json_ref& args) {
  auto client = (watchman_user_client*)clientbase;

  int sync_timeout;
  json_ref subs(nullptr);

  if (json_array_size(args) == 3) {
    auto& sync_timeout_obj = args.at(2).get("sync_timeout");
    subs = args.at(2).get_default("subscriptions", nullptr);
    if (!json_is_integer(sync_timeout_obj)) {
      send_error_response(client, "'sync_timeout' must be an integer");
      return;
    }
    sync_timeout = json_integer_value(sync_timeout_obj);
  } else {
    send_error_response(
        client, "wrong number of arguments to 'flush-subscriptions'");
    return;
  }

  auto root = resolve_root_or_err(client, args, 1, false);
  if (!root) {
    return;
  }

  std::vector<w_string> subs_to_sync;
  if (subs) {
    if (!json_is_array(subs)) {
      send_error_response(
          client,
          "expected 'subscriptions' to be an array of subscription names");
      return;
    }

    for (auto& sub_name : subs.array()) {
      if (!json_is_string(sub_name)) {
        send_error_response(
            client,
            "expected 'subscriptions' to be an array of subscription names");
        return;
      }

      auto& sub_name_str = json_to_w_string(sub_name);
      auto sub_iter = client->subscriptions.find(sub_name_str);
      if (sub_iter == client->subscriptions.end()) {
        send_error_response(
            client,
            "this client does not have a subscription named '%s'",
            sub_name_str.c_str());
        return;
      }
      auto& sub = sub_iter->second;
      if (sub->root != root) {
        send_error_response(
            client,
            "subscription '%s' is on root '%s' different from command root "
            "'%s'",
            sub_name_str.c_str(),
            sub->root->root_path.c_str(),
            root->root_path.c_str());
        return;
      }

      subs_to_sync.push_back(sub_name_str);
    }
  } else {
    // Look for all subscriptions matching this root.
    for (auto& sub_iter : client->subscriptions) {
      if (sub_iter.second->root == root) {
        subs_to_sync.push_back(sub_iter.first);
      }
    }
  }

  if (!root->syncToNow(std::chrono::milliseconds(sync_timeout))) {
    send_error_response(client, "sync_timeout expired");
    return;
  }

  auto resp = make_response();
  auto synced = json_array();
  auto no_sync_needed = json_array();
  auto dropped = json_array();

  for (auto& sub_name_str : subs_to_sync) {
    auto sub_iter = client->subscriptions.find(sub_name_str);
    auto& sub = sub_iter->second;

    sub_action action;
    w_string policy_name;
    std::tie(action, policy_name) = get_subscription_action(sub.get(), root);

    if (action == sub_action::drop) {
      auto position = root->view()->getMostRecentRootNumberAndTickValue();
      sub->last_sub_tick = position.ticks;
      sub->query->since_spec = watchman::make_unique<ClockSpec>(position);
      watchman::log(
          watchman::DBG,
          "(flush-subscriptions) dropping subscription notifications for ",
          sub->name,
          " until state ",
          policy_name,
          " is vacated. Advanced ticks to ",
          sub->last_sub_tick,
          "\n");
      json_array_append(dropped, w_string_to_json(sub_name_str));
    } else {
      // flush-subscriptions means that we _should NOT defer_ notifications. So
      // ignore defer and defer_vcs.
      ClockSpec out_position;
      watchman::log(
          watchman::DBG,
          "(flush-subscriptions) executing subscription ",
          sub->name,
          "\n");
      auto sub_result = sub->buildSubscriptionResults(root, out_position);
      if (sub_result) {
        send_and_dispose_response(client, std::move(sub_result));
        json_array_append(synced, w_string_to_json(sub_name_str));
      } else {
        json_array_append(no_sync_needed, w_string_to_json(sub_name_str));
      }
    }
  }

  resp.set({{"synced", std::move(synced)},
            {"no_sync_needed", std::move(no_sync_needed)},
            {"dropped", std::move(dropped)}});
  add_root_warnings_to_response(resp, root);
  send_and_dispose_response(client, std::move(resp));
}
示例#26
0
void main() {
	char name[50] = "Some name is a some name.\n";
	subs(name, 24);
}
示例#27
0
文件: print.c 项目: doniexun/OrangeC
int Print(HWND win)
{
    BOOL rv = TRUE;
    int start, end;
    PRINTDLG pd;
    HWND hDlgCancel = 0;
    memset(&pd, 0, sizeof(pd));
    pd.lStructSize = sizeof(pd);
    pd.hwndOwner = hwndFrame;
    pd.Flags = PD_NOPAGENUMS | PD_RETURNDC | PD_COLLATE ;
    pd.hInstance = hInstance;
    SendDlgItemMessage(win, ID_EDITCHILD, EM_GETSEL, (WPARAM) &start, (LPARAM)
        &end);
    tabSetting = PropGetInt(NULL, "TAB_INDENT");
    leftmargin = PropGetInt(NULL, "PRINTER_LEFT");
    rightmargin = PropGetInt(NULL, "PRINTER_RIGHT");
    topmargin = PropGetInt(NULL, "PRINTER_TOP");
    bottommargin = PropGetInt(NULL, "PRINTER_BOTTOM");
    PropGetString(NULL, "PRINTER_HEADER", printHeader, sizeof(printHeader));
    PropGetString(NULL, "PRINTER_FOOTER", printFooter, sizeof(printFooter));
    if (tabSetting <= 0)
        tabSetting = 4;
    if (end != start)
        pd.Flags |= PD_SELECTION;
    if (PrintDlg(&pd))
    {
        DOCINFO di;
        HWND child;
        char *buf,  *pos,  *savepos1;
        if (pd.Flags &PD_SELECTION)
        {
            if (end <= start)
                return TRUE ;
        }
        child = GetDlgItem(win, ID_EDITCHILD);
        buf = GetEditData(child);
        if (!buf)
            return TRUE ;
        if (pd.Flags &PD_SELECTION)
        {
            savepos1 = pos = buf + start;
            buf[end] = 0;
        }
        else
            savepos1 = pos = buf;
        printing = TRUE;
        memset(&di, 0, sizeof(di));
        di.cbSize = sizeof(di);
        di.lpszDocName = (char*)SendMessage(win, WM_FILETITLE, 0, 0);
        if (pd.Flags &PD_PRINTTOFILE)
            di.lpszOutput = "FILE:";
        SetAbortProc(pd.hDC, &AbortProc);

        if (StartDoc(pd.hDC, &di) > 0)
        {
            int pelsx, pelsy;
            int width, height, rows, cols;
            int done = FALSE;
            char headerLeft[256],headerRight[256],headerCenter[256];
            char FooterLeft[256],FooterRight[256],FooterCenter[256];
            SIZE strsize ;
            HFONT hFont, oldhFont;

            pelsx = GetDeviceCaps(pd.hDC, LOGPIXELSX);
            pelsy = GetDeviceCaps(pd.hDC, LOGPIXELSY);

            fontdata.lfHeight =  - MulDiv(11, pelsx, 72);
            hFont = CreateFontIndirect(&fontdata);
            oldhFont = SelectObject(pd.hDC, hFont);
            GetTextExtentPoint32(pd.hDC, "A", 1, &strsize);

            width = GetDeviceCaps(pd.hDC, HORZRES);
            height = GetDeviceCaps(pd.hDC, VERTRES);
//            buf = GetEditData(win);

            rows = (height - (topmargin + bottommargin) *pelsy * 10 / 254) /
                strsize.cy ;
            cols = (width - (leftmargin + rightmargin) *pelsx * 10 / 254) /
                strsize.cx;

            if (rows <= 0 || cols <= 0)
            {
                AbortDoc(pd.hDC);
                free(buf);
                DeleteObject(hFont);
                if (pd.hDC != NULL)
                    DeleteDC(pd.hDC);
                if (pd.hDevMode != NULL)
                    GlobalFree(pd.hDevMode);
                if (pd.hDevNames != NULL)
                    GlobalFree(pd.hDevNames);
                return FALSE;
            }
            SelectObject(pd.hDC, oldhFont);
            if (printHeader[0])
                rows -= 2;
            if (printFooter[0])
                rows -= 2;
            total_pages = countPages(savepos1, rows, cols);
            setTimeFormats();
            split(printHeader, headerLeft, headerRight, headerCenter);
            split(printFooter, FooterLeft, FooterRight, FooterCenter);
            hDlgCancel = CreateDialog(hInstance, "PRINTABORTDLG", 0, (DLGPROC)
                CancelProc);
            EnableWindow(hwndFrame, FALSE);
            do
            {
                int colcount = pd.nCopies;
                int pagenum = 1;
                pos = savepos1;
                while (printing &&  *pos && StartPage(pd.hDC) > 0)
                {
                    int i, j, k;
                    int hdrlines = 0;
                    char line[512];
                    char *savepos2 = pos;
                    oldhFont = SelectObject(pd.hDC, hFont);
                    if (printHeader[0])
                    {
                        char buf[256];
                        int cx ;
                        int cy = topmargin * pelsy * 10/ 254;
                        cx = subs(pd.hDC, buf, headerLeft, di.lpszDocName, pagenum);
                        cx = leftmargin * pelsx * 10 / 254;
                        TextOut(pd.hDC, cx, cy, buf, strlen(buf));
                        cx = subs(pd.hDC, buf, headerCenter, di.lpszDocName, pagenum);
                        cx = (width - cx)/2 ;
                        TextOut(pd.hDC, cx, cy, buf, strlen(buf));
                        cx = subs(pd.hDC, buf, headerRight, di.lpszDocName, pagenum);
                        cx = width - cx - rightmargin * pelsx * 10 / 254;
                        TextOut(pd.hDC, cx, cy, buf, strlen(buf));
                        hdrlines = 2;
                    }
                    for (i = 0; i < rows; i++)
                    {
                        int count = 0;
                        if (*pos == '\n')
                        {
                            pos++;
                        }
                        else if (*pos == '\f')
                        {
                            pos += 2;
                            break;
                        }
                        else
                        {
                            for (j = 0; j < cols; j++)
                            {
                                if (*pos == '\t')
                                {
                                    int n = tabSetting - j % tabSetting;
                                    pos++;
                                    for (k = 0; k < n; k++)
                                        line[count++] = ' ';
                                    j += n - 1;
                                } 
                                else
                                {
                                    if (*pos < 32 ||  *pos > 126)
                                    {
                                        if (*pos == '\n')
                                            pos++;
                                        break;
                                    }
                                    line[count++] =  *pos++;
                                }
                            }
                            TextOut(pd.hDC, leftmargin *pelsx * 10 / 254, (i + hdrlines)
                                *strsize.cy + topmargin * pelsy * 10 / 254, line, count);
                        }
                        if (! *pos)
                            break;
                    }
                    if (printFooter[0])
                    {
                        char buf[256];
                        int cx ;
                        int cy = height - strsize.cy - bottommargin * pelsy * 10 / 254;
                        cx = subs(pd.hDC, buf, FooterLeft, di.lpszDocName, pagenum);
                        cx = leftmargin * pelsx * 10 / 254;
                        TextOut(pd.hDC, cx, cy, buf, strlen(buf));
                        cx = subs(pd.hDC, buf, FooterCenter, di.lpszDocName, pagenum);
                        cx = (width - cx) / 2;
                        TextOut(pd.hDC, cx, cy, buf, strlen(buf));
                        cx = subs(pd.hDC, buf, FooterRight, di.lpszDocName, pagenum);
                        cx = width - cx - rightmargin * pelsx * 10 / 254;
                        TextOut(pd.hDC, cx, cy, buf, strlen(buf));
                    }
                    SelectObject(pd.hDC, oldhFont);
                    if (printing)
                        if (EndPage(pd.hDC) <= 0)
                            goto doneprinting;
                    if (!(pd.Flags &PD_COLLATE))
                    {
                        if (--colcount)
                        {
                            pos = savepos2;
                        }
                        else
                        {
                            colcount = pd.nCopies;
                            pagenum++;
                        }
                    }
                    else
                    {
                        pagenum++;
                    }
                        
                }
            }
            while (printing && (pd.Flags &PD_COLLATE) && --pd.nCopies)
                ;
            if (!printing)
                AbortDoc(pd.hDC);
            doneprinting: if (printing)
                EndDoc(pd.hDC);
            EnableWindow(hwndFrame, TRUE);
            if (hDlgCancel)
                DestroyWindow(hDlgCancel);
            DeleteObject(hFont);
        }
        FreeEditData(buf);

    }
    if (pd.hDC != NULL)
        DeleteDC(pd.hDC);
    if (pd.hDevMode != NULL)
        GlobalFree(pd.hDevMode);
    if (pd.hDevNames != NULL)
        GlobalFree(pd.hDevNames);
    return rv;
}
示例#28
0
void MacroAssembler::atomic_cas_bool(Register oldval, Register newval, Register base, int offset, Register tmpreg) {
  if (VM_Version::supports_ldrex()) {
    Register tmp_reg;
    if (tmpreg == noreg) {
      push(LR);
      tmp_reg = LR;
    } else {
      tmp_reg = tmpreg;
    }
    assert_different_registers(tmp_reg, oldval, newval, base);
    Label loop;
    bind(loop);
    ldrex(tmp_reg, Address(base, offset));
    subs(tmp_reg, tmp_reg, oldval);
    strex(tmp_reg, newval, Address(base, offset), eq);
    cmp(tmp_reg, 1, eq);
    b(loop, eq);
    cmp(tmp_reg, 0);
    if (tmpreg == noreg) {
      pop(tmp_reg);
    }
  } else if (VM_Version::supports_kuser_cmpxchg32()) {
    // On armv5 platforms we must use the Linux kernel helper
    // function for atomic cas operations since ldrex/strex is
    // not supported.
    //
    // This is a special routine at a fixed address 0xffff0fc0 with
    // with these arguments and results
    //
    // input:
    //  r0 = oldval, r1 = newval, r2 = ptr, lr = return adress
    // output:
    //  r0 = 0 carry set on success
    //  r0 != 0 carry clear on failure
    //
    // r3, ip and flags are clobbered
    //

    Label loop;

    push(RegisterSet(R0, R3) | RegisterSet(R12) | RegisterSet(LR));

    Register tmp_reg = LR; // ignore the argument

    assert_different_registers(tmp_reg, oldval, newval, base);

    // Shuffle registers for kernel call
    if (oldval != R0) {
      if (newval == R0) {
        mov(tmp_reg, newval);
        newval = tmp_reg;
      }
      if (base == R0) {
        mov(tmp_reg, base);
        base = tmp_reg;
      }
      mov(R0, oldval);
    }
    if(newval != R1) {
      if(base == R1) {
        if(newval == R2) {
          mov(tmp_reg, base);
          base = tmp_reg;
        }
        else {
          mov(R2, base);
          base = R2;
        }
      }
      mov(R1, newval);
    }
    if (base != R2)
      mov(R2, base);

    if (offset != 0)
      add(R2, R2, offset);

    mvn(R3, 0xf000);
    mov(LR, PC);
    sub(PC, R3, 0x3f);
    cmp (R0, 0);

    pop(RegisterSet(R0, R3) | RegisterSet(R12) | RegisterSet(LR));
  } else {
    // Should never run on a platform so old that it does not have kernel helper
    stop("Atomic cmpxchg32 unsupported on this platform");
  }
}
示例#29
0
    bool ModuloSchedulerDriverPass::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
      
        subscripts subs(IncomingLoop);

        if (!loop_is_ms_able(IncomingLoop) ) return false; 

        // The header before the parallelized loop will be placed here
        BasicBlock* preheader = IncomingLoop->getLoopPreheader();
        assert(preheader && "Unable to get a hold of the preheader");

        // Balance all BasicBlocks in this loop
        for (Loop::block_iterator it=IncomingLoop->block_begin(); it!=IncomingLoop->block_end();++it) {
            duplicateValuesWithMultipleUses(*it,subs.getInductionVar());
        }

        // For each BB in loop
        for (Loop::block_iterator it=IncomingLoop->block_begin(); it!=IncomingLoop->block_end();++it) {
            instructionPriority  ip(*it);
            (*it)->setName("PipelinedLoop");
            
            // ++++++++ Preheader part +++++++++
            // Make a copy of the body for each instruction. Place a pointer to the 
            // parallel cloned instruction in the map below. Later on we will replace it 
            // with a PHINode.
            DenseMap<const Value *, Value *>  InstToPreheader;

            // For each Instruction in body of the loop, clone, store, etc.
            for (BasicBlock::iterator ib = (*it)->begin(), eb = (*it)->end(); ib!=eb; ++ib) {
                // If this is NOT a phi node
                if (!dyn_cast<PHINode>(ib)) {
                    // Get the priority of the instruction
                    unsigned int p = ip.getPriority(ib);
                    // This is the header version of each variable that goes into a PHI node.
                    // The other edge needs to come from the 'prev' iteration
                    // We subtract -1 because this is one iteration before 
                    // Store the result into the map of the cloned
                    InstToPreheader[ib] = copyLoopBodyToHeader(ib, subs.getInductionVar(), preheader, p-1);
                }
            }

            // ++++++++ Loop body part +++++++++
            // For each of the cloned increment the indexs if needed and place the PHINode.
            for (BasicBlock::iterator ib = (*it)->begin(), eb = (*it)->end(); ib!=eb; ++ib) {
                // If this is NOT a phi node
                if (!dyn_cast<PHINode>(ib)) {
                    unsigned int p = ip.getPriority(ib);

                    // If this variable is not dependent on i (not i:=i+1)
                    // then we need to replace each i to i+5 ...
                    // We also do not need to create a PHI node, etc.
                    if (!subs.isUsedByInductionVariable(ib)) {
                        
                        incrementInductionVarIfUsed(ib,subs.getInductionVar(),p);

                        // Create the new PHI Node to replace the node
                        if (!dyn_cast<StoreInst>(ib) && !ib->isTerminator()) {
                            std::string newname = "glue" + (*it)->getName();

                            //PHINode* np = PHINode::Create(ib->getType(), "glue", *it);
                            PHINode* np = PHINode::Create(ib->getType(), newname, *it);
                            ib->replaceAllUsesWith(np);
                            np->reserveOperandSpace(2);
                            np->addIncoming(InstToPreheader[ib], preheader);
                            np->addIncoming(ib, *it);
                            np->moveBefore((*it)->begin());
                        }

                    }// end of if this is not an IV node (i:=i+1) 
                }
            }
        }

        eliminateDuplicatedLoads(preheader);
        for (Loop::block_iterator it=IncomingLoop->block_begin(); it!=IncomingLoop->block_end();++it) {
            eliminateDuplicatedLoads(*it);
            for (BasicBlock::iterator in = (*it)->begin(); in != (*it)->end(); ++in) {
                foldAddInstructions(in);
            }
        }
        return true;
    }
示例#30
0
obj qquote(obj rt){
	return subs(rt, nil);
}