示例#1
0
文件: log.cpp 项目: JGRennison/retcon
static void dump_tweet_line(LOGT logflags, const std::string &indent, const std::string &indentstep, const tweet *t) {
	LogMsgFormat(logflags, "%sTweet with operations pending ready state: %s", cstr(indent), cstr(tweet_log_line(t)));
	for (auto &jt : t->pending_ops) {
		LogMsgFormat(logflags, "%s%s%s", cstr(indent), cstr(indentstep), cstr(jt->dump()));
	}
}
示例#2
0
	/** Handles deserialization from both myanimelist and search results.
	 * Search results are      <anime><entry></entry><entry></entry></anime>
	 * myanimelist results are <entry><anime></anime><anime></anime></entry>
	 */
	std::list<std::shared_ptr<Anime> > AnimeSerializer::deserialize(const std::string& xml) const {
		std::list<std::shared_ptr<Anime> > res;
		std::unique_ptr<char[]> cstr(new char[xml.size()]);
		std::memcpy(cstr.get(), xml.c_str(), xml.size());
		std::unique_ptr<xmlTextReader, xmlTextReaderDeleter> reader(xmlReaderForMemory(
			         cstr.get(), xml.size(), "", "UTF-8", XML_PARSE_RECOVER | XML_PARSE_NOENT ));

		if (!reader) {
			std::cerr << "Error: Couldn't create XML reader" << std::endl;
            std::cerr << "XML follows: " << xml << std::endl;
			return res;
		}

		Anime anime;
		int ret                = 1;
		FIELDS field           = FIELDNONE;
		FIELDS prev_field      = FIELDNONE;
		bool entry_after_anime = false;
		bool seen_anime        = false;
		bool seen_entry        = false;

		for( ret = xmlTextReaderRead(reader.get()); ret == 1;
		     ret = xmlTextReaderRead(reader.get()) ) {
			const std::string name  = xmlchar_to_str(xmlTextReaderConstName (reader.get()));
			std::string value = xmlchar_to_str(xmlTextReaderConstValue(reader.get()));
            m_text_util->parse_html_entities(value);

			if (name.size() > 0) {
				auto field_iter = field_map.find(name);
				if (field_iter != field_map.end()) {
					prev_field = field;
					field = field_iter->second;
				} else {
					std::cerr << "Unexpected field " << name << std::endl;
				}

				switch (xmlTextReaderNodeType(reader.get())) {
				case XML_READER_TYPE_ELEMENT:
					entry_after_anime |= (field == ENTRY) && seen_anime && !seen_entry;
					seen_entry        |= field == ENTRY;
					seen_anime        |= field == ANIME;
					break;
				case XML_READER_TYPE_END_ELEMENT:
					if ( ( entry_after_anime && field == ENTRY) ||
					     (!entry_after_anime && field == ANIME)) {
						res.push_back(std::make_shared<Anime>(anime));
						anime = Anime();
					}
					field = FIELDNONE;
					break;
				case XML_READER_TYPE_TEXT:
					if( field != FIELDTEXT ) {
						std::cerr << "There's a problem!" << std::endl;
					}
					if (value.size() > 0) {
						auto member_iter = member_map.find(prev_field);
						if ( member_iter != member_map.end() ) {
							member_iter->second(anime, std::move(value));
						}
					} else {
						std::cerr << "Error: Unexpected " << name << " = " 
						          << value << std::endl;
					}
					break;
				case XML_READER_TYPE_SIGNIFICANT_WHITESPACE:
					break;
				default:
					std::cerr << "Warning: Unexpected node type "
					          << xmlTextReaderNodeType(reader.get())
					          << " : " << name << "=" << value << std::endl;
					break;
				}
			}
		}
		
		if ( ret != 0 ) {
			std::cerr << "Error: Failed to parse! ret = " << ret << std::endl;
            std::cerr << "The xml is:\n" << xml << std::endl;
		}

		return res;
	}
示例#3
0
// TODO: Wrap these two functions into a class
FString StringFromBinaryArray(const TArray<uint8>& BinaryArray)
{
	std::string cstr(reinterpret_cast<const char*>(BinaryArray.GetData()), BinaryArray.Num());
	return FString(cstr.c_str());
}
示例#4
0
void *QGLContext::tryVisual( const QGLFormat& f, int bufDepth )
{
    int spec[40];
    int i = 0;
    spec[i++] = GLX_LEVEL;
    spec[i++] = f.plane();

#if defined(GLX_VERSION_1_1) && defined(GLX_EXT_visual_info)
    static bool useTranspExt = FALSE;
    static bool useTranspExtChecked = FALSE;
    if ( f.plane() && !useTranspExtChecked && d->paintDevice ) {
	QCString estr( glXQueryExtensionsString( d->paintDevice->x11Display(),
						 d->paintDevice->x11Screen() ) );
	useTranspExt = estr.contains( "GLX_EXT_visual_info" );
	//# (A bit simplistic; that could theoretically be a substring)
	if ( useTranspExt ) {
	    QCString cstr( glXGetClientString( d->paintDevice->x11Display(),
					       GLX_VENDOR ) );
	    useTranspExt = !cstr.contains( "Xi Graphics" ); // bug workaround
	    if ( useTranspExt ) {
		// bug workaround - some systems (eg. FireGL) refuses to return an overlay
		// visual if the GLX_TRANSPARENT_TYPE_EXT attribute is specfied, even if
		// the implementation supports transparent overlays
		int tmpSpec[] = { GLX_LEVEL, f.plane(), GLX_TRANSPARENT_TYPE_EXT,
				  f.rgba() ? GLX_TRANSPARENT_RGB_EXT : GLX_TRANSPARENT_INDEX_EXT,
				  None };
		XVisualInfo * vinf = glXChooseVisual( d->paintDevice->x11Display(),
						      d->paintDevice->x11Screen(), tmpSpec );
		if ( !vinf ) {
		    useTranspExt = FALSE;
		}
	    }
	}

	useTranspExtChecked = TRUE;
    }
    if ( f.plane() && useTranspExt ) {
	// Required to avoid non-transparent overlay visual(!) on some systems
	spec[i++] = GLX_TRANSPARENT_TYPE_EXT;
	spec[i++] = f.rgba() ? GLX_TRANSPARENT_RGB_EXT : GLX_TRANSPARENT_INDEX_EXT;
    }
#endif

    if ( f.doubleBuffer() )
	spec[i++] = GLX_DOUBLEBUFFER;
    if ( f.depth() ) {
	spec[i++] = GLX_DEPTH_SIZE;
	spec[i++] = 1;
    }
    if ( f.stereo() ) {
	spec[i++] = GLX_STEREO;
    }
    if ( f.stencil() ) {
	spec[i++] = GLX_STENCIL_SIZE;
	spec[i++] = 1;
    }
    if ( f.rgba() ) {
	spec[i++] = GLX_RGBA;
	spec[i++] = GLX_RED_SIZE;
	spec[i++] = 1;
	spec[i++] = GLX_GREEN_SIZE;
	spec[i++] = 1;
	spec[i++] = GLX_BLUE_SIZE;
	spec[i++] = 1;
	if ( f.alpha() ) {
	    spec[i++] = GLX_ALPHA_SIZE;
	    spec[i++] = 1;
	}
	if ( f.accum() ) {
	    spec[i++] = GLX_ACCUM_RED_SIZE;
	    spec[i++] = 1;
	    spec[i++] = GLX_ACCUM_GREEN_SIZE;
	    spec[i++] = 1;
	    spec[i++] = GLX_ACCUM_BLUE_SIZE;
	    spec[i++] = 1;
	    if ( f.alpha() ) {
		spec[i++] = GLX_ACCUM_ALPHA_SIZE;
		spec[i++] = 1;
	    }
	}
    }
    else {
	spec[i++] = GLX_BUFFER_SIZE;
	spec[i++] = bufDepth;
    }

    spec[i] = None;
    return glXChooseVisual( d->paintDevice->x11Display(),
			    d->paintDevice->x11Screen(), spec );
}
void file_info(const sha256_t &h)
{
    if(a) a->add_value("sha256",h.hexdigest());
    if(t && !opt_body_file) fputs(cstr("sha256: " + h.hexdigest() + "\n"),t);
    if(x) x->xmlout("hashdigest",h.hexdigest(),"type='sha256'",false);
}
示例#6
0
// This determines the scrollbar size and position such that, where possible
// the item at the top of the visible screen is unmoved
void tpanelscrollbar::RepositionItems() {
	tpanelscrollpane *tsp = get_paired_ptr();
	if (!tsp) return;

	#if TPANEL_SCROLLING_COPIOUS_LOGGING
		LogMsgFormat(LOGT::TPANELTRACE, "TSCL: tpanelscrollbar::RepositionItems %s, START %d %d", cstr(GetThisName()),
				GetThumbPosition(), parent->GetCurrentDisp().size());
	#endif
	scroll_virtual_size = 0;
	int cumul_size = 0;
	bool have_scroll_offset = false;
	int scroll_offset = 0;

	for (auto &disp : parent->GetCurrentDisp()) {
		wxPoint p = disp.item->GetPosition();
		wxSize s = disp.item->GetSize();

		if (!disp.item->IsShown()) {
			s.y = 0;
		}

		scroll_virtual_size += s.y;

		if (p.x == 0 && p.y + s.y > 0 && p.y <= 0) {
			// This is an item which is visible at the top of the list
			// We should use the *last* matching item, this is as earlier items may grow in size to overlap the top of the screen

			// p.y is non-positive
			// The scroll offset should be increased as p.y increases in magnitude below 0
			scroll_offset = cumul_size - p.y;
			have_scroll_offset = true;
		}
		cumul_size += s.y;
	}

	if (parent->pimpl()->displayoffset == 0 && GetThumbPosition() == 0 &&
			have_scroll_offset && !scroll_always_freeze) {
		// We were at the very top, we would normally be scrolling down as something has been inserted above
		// Scroll back to the top instead
		// Don't do this if scroll_always_freeze is true
		scroll_offset = 0;
	}
	scroll_always_freeze = false;

	if (!have_scroll_offset) {
		scroll_offset = GetThumbPosition();
	}

	scroll_client_size = tsp->GetClientSize().y;
	SetScrollbar(scroll_offset, scroll_client_size, scroll_virtual_size, 1);

	ScrollItems();
	#if TPANEL_SCROLLING_COPIOUS_LOGGING
		LogMsgFormat(LOGT::TPANELTRACE, "TSCL: tpanelscrollbar::RepositionItems %s, END %d %d %d %d %d", cstr(GetThisName()),
				GetThumbPosition(), scroll_offset, have_scroll_offset, scroll_always_freeze, cumul_size);
	#endif
}
示例#7
0
std::string tpanelload_pending_op::dump() {
	std::shared_ptr<tpanel> tp=pushtpanel.lock();
	tpanelparentwin_nt *window=win.get();
	return string_format("Push tweet to tpanel: %s, window: %p, pushflags: 0x%X", (tp) ? cstr(wxstrstd(tp->dispname)) : "N/A", window, pushflags);
}
intptr_t CharQueue::get(_TUCHAR *dst, size_t n) {
  n = min(length(), n);
  MEMCPY(dst, cstr(), n);
  remove(0, (int)n);
  return n;
}
示例#9
0
bool TimeStamp::fromRFC2822( TimeStamp &target, const String &source )
{
    AutoCString cstr( source );
    return fromRFC2822( target, cstr.c_str() );
}
示例#10
0
//Rama's String From Binary Array
//This function requires #include <string>
FString CloudyWebAPIImpl::StringFromBinaryArray(const TArray<uint8>& BinaryArray)
{
    //Create a string from a byte array!
    std::string cstr(reinterpret_cast<const char*>(BinaryArray.GetData()), BinaryArray.Num());
    return FString(cstr.c_str());
}
示例#11
0
void *QGLContext::tryVisual( const QGLFormat& f, int bufDepth )
{
    int spec[40];
    int i = 0;
    spec[i++] = GLX_LEVEL;
    spec[i++] = f.plane();

#if defined(GLX_VERSION_1_1) && defined(GLX_EXT_visual_info)
    static bool useTranspExt = FALSE;
    static bool useTranspExtChecked = FALSE;
    if ( f.plane() && !useTranspExtChecked && paintDevice ) {
	QCString estr( glXQueryExtensionsString( paintDevice->x11Display(),
						 paintDevice->x11Screen() ) );
	useTranspExt = estr.contains( "GLX_EXT_visual_info" );
	//# (A bit simplistic; that could theoretically be a substring)
	if ( useTranspExt ) {
	    QCString cstr( glXGetClientString( paintDevice->x11Display(),
					       GLX_VENDOR ) );
	    useTranspExt = !cstr.contains( "Xi Graphics" ); // bug workaround
	}
	useTranspExtChecked = TRUE;
    }
    if ( f.plane() && useTranspExt ) {
	// Required to avoid non-transparent overlay visual(!) on some systems
	spec[i++] = GLX_TRANSPARENT_TYPE_EXT;
	spec[i++] = GLX_TRANSPARENT_INDEX_EXT; //# Depending on format, really
    }
#endif

    if ( f.doubleBuffer() )
	spec[i++] = GLX_DOUBLEBUFFER;
    if ( f.depth() ) {
	spec[i++] = GLX_DEPTH_SIZE;
	spec[i++] = 1;
    }
    if ( f.stereo() ) {
	spec[i++] = GLX_STEREO;
    }
    if ( f.stencil() ) {
	spec[i++] = GLX_STENCIL_SIZE;
	spec[i++] = 1;
    }
    if ( f.rgba() ) {
	spec[i++] = GLX_RGBA;
	spec[i++] = GLX_RED_SIZE;
	spec[i++] = 1;
	spec[i++] = GLX_GREEN_SIZE;
	spec[i++] = 1;
	spec[i++] = GLX_BLUE_SIZE;
	spec[i++] = 1;
 	if ( f.alpha() ) {
	    spec[i++] = GLX_ALPHA_SIZE;
	    spec[i++] = 1;
	}
	if ( f.accum() ) {
	    spec[i++] = GLX_ACCUM_RED_SIZE;
	    spec[i++] = 1;
	    spec[i++] = GLX_ACCUM_GREEN_SIZE;
	    spec[i++] = 1;
	    spec[i++] = GLX_ACCUM_BLUE_SIZE;
	    spec[i++] = 1;
	    if ( f.alpha() ) {
		spec[i++] = GLX_ACCUM_ALPHA_SIZE;
		spec[i++] = 1;
	    }
        }
    }
    else {
	spec[i++] = GLX_BUFFER_SIZE;
	spec[i++] = bufDepth;
    }
    spec[i] = None;
    return glXChooseVisual( paintDevice->x11Display(),
			    paintDevice->x11Screen(), spec );
}
示例#12
0
Stream *VFSFile::create( const URI& uri, const CParams &p, bool &bSuccess )
{
   DWORD omode = win_paramsToMode( p );
   DWORD oshare = win_paramsToShare( p );
   DWORD ocreate = p.isNoOvr() ? 0 : CREATE_ALWAYS;
   
   // turn the xxx bytes 
   DWORD oattribs = FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_ARCHIVE;
   if ( p.createMode()  )
   {
      // use the owner bits
      int obits = p.createMode() & 0700;

      // set read only if write bit is not set 
      if ( (obits & 0200) == 0 )
      {
         oattribs |= FILE_ATTRIBUTE_READONLY;
      }
      
      // set hidden if read bit is not set
      if ( (obits & 0400) == 0 )
      {
         oattribs |= FILE_ATTRIBUTE_HIDDEN; 
      }
   }

   String path = uri.path();
   Path::uriToWin( path );
   AutoWString wstr( path );

   HANDLE handle = CreateFileW( wstr.w_str(),
      omode,
      oshare,
      NULL,
      ocreate,
      oattribs,
      NULL );

	DWORD dwError = GetLastError();
   if ( handle == 0 || handle == INVALID_HANDLE_VALUE )
   {
      if ( dwError  == ERROR_CALL_NOT_IMPLEMENTED )
      {
         AutoCString cstr( path );
         handle = CreateFile( cstr.c_str(),
               omode,
               oshare,
               NULL,
               ocreate,
               oattribs,
               NULL );
      }
   }

   if ( handle == 0 || handle == INVALID_HANDLE_VALUE )
   {
      bSuccess = false;
      return 0;
   }

   bSuccess = true;
   // the caller may not really want to open the stream.
   if( p.isNoStream() )
   {
      CloseHandle( handle );
      return 0;
   }
      
   FileStream *fs = new FileStream( new WinFileSysData( handle, 0 ) );
   return new StreamBuffer( fs );
}
示例#13
0
文件: log.cpp 项目: JGRennison/retcon
void dump_id_stats(LOGT logflags, const std::string &indent, const std::string &indentstep) {
	auto line = [&](const char *name, size_t value) {
		LogMsgFormat(logflags, "%s%s: %zu", cstr(indent), cstr(name), value);
	};
	line("Loaded users", ad.userconts.size());
	line("Loaded tweets", ad.tweetobjs.size());
	line("DB unloaded users", ad.unloaded_db_user_ids.size());
	line("DB unloaded tweets", ad.unloaded_db_tweet_ids.size());
	line("DB loaded tweets", ad.loaded_db_tweet_ids.size());
	line("No acc pending users", ad.noacc_pending_userconts.size());
	line("No acc pending tweets", ad.noacc_pending_tweetobjs.size());

	struct count_item {
		size_t count = 0;
		size_t total = 0;

		void add(size_t value) {
			if (value) {
				total += value;
				count++;
			}
		}
	};

	auto dline = [&](const char *name, const count_item &value) {
		line(string_format("%s: count", name).c_str(), value.count);
		line(string_format("%s: total", name).c_str(), value.total);
	};

	auto dline_bytes = [&](const char *name, const count_item &value) {
		line(string_format("%s: count", name).c_str(), value.count);
		line(string_format("%s: total bytes", name).c_str(), value.total);
	};

	{
		count_item mentionindex;
		count_item pendingtweets;
		for (const auto &it : ad.userconts) {
			if (it.second) {
				mentionindex.add(it.second->mention_set.size());
				pendingtweets.add(it.second->pendingtweets.size());
			}
		}
		dline("Loaded users: mention index", mentionindex);
		dline("Loaded users: pending tweet IDs", pendingtweets);
	}

	{
		count_item pending_ops;
		for (const auto &it : ad.tweetobjs) {
			if (it.second) {
				pending_ops.add(it.second->pending_ops.size());
			}
		}
		dline("Loaded tweets: pending operations", pending_ops);
	}

	line("Loaded tpanels", ad.tpanels.size());
	size_t total_tpanel_ids = 0;
	for (const auto &it : ad.tpanels) {
		total_tpanel_ids += it.second->tweetlist.size();
	}
	line("Total tpanel tweet IDs", total_tpanel_ids);

	line("Loaded media entities", ad.media_list.size());
	line("Loaded media map URLs", ad.img_media_map.size());

	{
		count_item thumb;
		count_item full;
		for (const auto &it : ad.media_list) {
			if (it.second) {
				media_entity &me = *(it.second);
				if (me.thumbimg.IsOk()) {
					thumb.add(static_cast<size_t>(me.thumbimg.GetWidth() * me.thumbimg.GetHeight() * me.thumbimg.GetDepth() / 8));
				}
				full.add(me.fulldata.size());
			}
		}
		dline_bytes("Media thumbnails", thumb);
		dline_bytes("Media full images", full);
	}

	line("DM indexes", ad.user_dm_indexes.size());
	size_t total_dm_indexes = 0;
	for (const auto &it : ad.user_dm_indexes) {
		total_dm_indexes += it.second.ids.size();
	}
	line("DM indexes: total size", total_dm_indexes);

	LogMsgFormat(logflags, "%sCIDS:", cstr(indent));
	dump_cids_stats(ad.cids, logflags, indent + indentstep, indentstep);

	for (auto &it : alist) {
		LogMsgFormat(logflags, "%sAccount: %s (%s)", cstr(indent), cstr(it->name), cstr(it->dispname));
		dump_acc_id_stats(*it, logflags, indent + indentstep, indentstep);
	}
}
示例#14
0
文件: log.cpp 项目: JGRennison/retcon
void dump_acc_socket_flags(LOGT logflags, const std::string &indent, taccount *acc) {
	LogMsgFormat(logflags, "%sssl: %d, userstreams: %d, ta_flags: 0x%X, restinterval: %ds, enabled: %d, userenabled: %d, init: %d, "
			"active: %d, streaming_on: %d, stream_fail_count: %d, rest_on: %d, expire_tweets_days: %d",
			cstr(indent), acc->ssl, acc->userstreams, acc->ta_flags, acc->restinterval, acc->enabled, acc->userenabled, acc->init,
			acc->active, acc->streaming_on, acc->stream_fail_count, acc->rest_on, acc->expire_tweets_days);
}
示例#15
0
void tpanelscrollbar::mousewheelhandler(wxMouseEvent &event) {
	int pxdelta = -event.GetWheelRotation() * gc.mousewheelscrollspeed / event.GetWheelDelta();

	#if TPANEL_SCROLLING_COPIOUS_LOGGING
		LogMsgFormat(LOGT::TPANELTRACE, "TSCL: tpanelscrollbar::mousewheelhandler %s, %d %d %d", cstr(GetThisName()),
				GetScrollPos(wxVERTICAL), event.GetWheelRotation(), pxdelta);
	#endif

	int y = GetThumbPosition();
	SetThumbPosition(std::max(0, y + pxdelta));
	ScrollItems();

	// Use gc.mousewheelscrollspeed as the threshold, this is to try and make mousewheel scrolling smooth across pages
	OnScrollHandlerCommon(pxdelta < 0, pxdelta > 0, std::abs(gc.mousewheelscrollspeed), GetScrollPos(wxVERTICAL));
}
//This function requires
//		#include <string>
FString ATitanBotsPlayerController::StringFromBinaryArray(const TArray<uint8>& BinaryArray)
{
	//Create a string from a byte array!
	std::string cstr(reinterpret_cast<const char*>(BinaryArray.GetData()), BinaryArray.Num());
	return FString(cstr.c_str());
}
示例#17
0
void tpanelscrollbar::OnScrollHandlerCommon(bool upok, bool downok, int threshold, int current_position) {
	int y = current_position;
	int endpos = y + scroll_client_size;
	#if TPANEL_SCROLLING_COPIOUS_LOGGING
		LogMsgFormat(LOGT::TPANELTRACE, "TSCL: tpanelscrollbar::OnScrollHandlerCommon %s, %d %d %d %d", cstr(GetThisName()), y, scroll_virtual_size, scroll_client_size, endpos);
	#endif
	bool scrollup = (y <= threshold && upok);
	bool scrolldown = (endpos >= (scroll_virtual_size - threshold) && downok);
	if (scrollup && !scrolldown && !page_scroll_blocked) {
		wxCommandEvent evt(wxextTP_PAGEUP_EVENT);
		parent->GetEventHandler()->AddPendingEvent(evt);
		page_scroll_blocked = true;
	}
	if (!scrollup && scrolldown && !page_scroll_blocked) {
		wxCommandEvent evt(wxextTP_PAGEDOWN_EVENT);
		parent->GetEventHandler()->AddPendingEvent(evt);
		page_scroll_blocked = true;
	}
}
示例#18
0
std::string TS_Util::fixExpr(std::string expr)
{
	std::string result = expr;
	result = despace(result);
	result = replaceEx(result, "++", cstr(OP_INC));
	result = replaceEx(result, "--", cstr(OP_DEC));
	result = replaceEx(result, "+=", cstr(OP_ADD_SET));
	result = replaceEx(result, "-=", cstr(OP_SUB_SET));
	result = replaceEx(result, "*=", cstr(OP_MUL_SET));
	result = replaceEx(result, "/=", cstr(OP_DIV_SET));
	result = replaceEx(result, "^=", cstr(OP_POW_SET));
	result = replaceEx(result, ">=", cstr(OP_GE));
	result = replaceEx(result, "<=", cstr(OP_LE));
	result = replaceEx(result, "!=", cstr(OP_NEQ));
	result = replaceEx(result, "==", cstr(OP_EQ));
	result = replaceEx(result, "=", cstr(OP_SET));
	result = replaceEx(result, "&&", "&");
	result = replaceEx(result, "||", "|");
	result = replaceEx(result, "(xor)", "#");
	result = replaceEx(result, "(nand)", cstr(OP_NAND));
	result = replaceEx(result, "(nor)", cstr(OP_NOR));
	result = replaceEx(result, "(nxor)", cstr(OP_NXOR));
	result = replaceEx(result, "(band)", cstr(OP_BAND));
	result = replaceEx(result, "(bor)", cstr(OP_BOR));
	result = replaceEx(result, "<<", "\\");
	result = replaceEx(result, ">>", "\\-");
	result = replaceEx(result, "(max)", cstr(OP_MAX));
	result = replaceEx(result, "(min)", cstr(OP_MIN));
	result = replaceEx(result, "(imp)", cstr(OP_IMP));
	if (result != "(pi)")
		result = replaceEx(result, "(pi)", PI_STR);
	result = replaceEx(result, "(e)", "exp(1)");
	result = replaceEx(result, "()", "(0)");
	result = replaceEx(result, ")(", ")*(");
	return result;
}
示例#19
0
void tpanelscrollpane::resizehandler(wxSizeEvent &event) {
	#if TPANEL_SCROLLING_COPIOUS_LOGGING
		LogMsgFormat(LOGT::TPANELTRACE, "TSCL: tpanelscrollpane::resizehandler: %s, %d, %d", cstr(GetThisName()), event.GetSize().GetWidth(), event.GetSize().GetHeight());
	#endif

	for (auto &disp : parent->GetCurrentDisp()) {
		disp.item->NotifySizeChange();
	}
}
示例#20
0
float DexCalc::eval(std::string expr)
{
	int i;
	std::string result;
	std::string newExpr, token, prevToken;
	std::stack<std::string> opStack, elemStack, inStack;
	int depth;
	newExpr = "(" + expr + ")";
	if (!mTurbo)
		newExpr = TS_Util::fixExpr(newExpr);
	newExpr = replaceEx(newExpr, "E", "*10^");
	// STEP #1 (GROUP)
	// group tokens into operators and operands
	// (check for syntax errors)
	//
	// "(1 * 2 + 3)"
	//
	// [O]: ( * + )
	// [E]: 1 2 3
	// [I]:
	token = "";
	depth = 0;
	i = 0;
	while (i < newExpr.length())
	{
		prevToken = token;
		//==============================
		token = getNextTerm(newExpr, i);
		//==============================
		depth += (token == "(") ? 1 : 0;
		depth -= (token == ")") ? 1 : 0;
		if (depth < 0)
			throw Exception("expected end of statement");
		#ifndef TURBO_MODE
			if (TS_Util::rankOp(prevToken[0]) > 0 || prevToken == "(")
			{
				if (token == "+")
				{
					token = prevToken;
					continue;
				}
				if (token == "-") token = "neg";
				if (token == "!") token = "not";
				if (token == "~") token = "bnot";
				std::string prefix = left(token, 2);
				std::string value = lcase(right(token, token.length() - 2));
				if (prefix == "0x")
					token = changeBase(value, 16, 10);
				if (prefix == "0o")
					token = changeBase(value, 8, 10);
				if (prefix == "0b")
					token = changeBase(value, 2, 10);
			}
			if (
				TS_Util::rankOp(prevToken[0]) && (token[0] == OP_INC || token[0] == OP_DEC) ||
				(prevToken[0] == OP_INC || prevToken[0] == OP_DEC) && TS_Util::rankOp(token[0])
				)
				elemStack.push("0");
			else if (TS_Util::isFunc(prevToken) && token != "@" && token != ")")
				opStack.push("@");
			else
				TS_Util::checkSyntaxError(prevToken, token);
		#endif
		//=================================
		if (TS_Util::rankOp(token[0]))
			opStack.push(token);
		else
			elemStack.push(token);
		//=================================
	}
	if (depth > 0)
		throw Exception("expected close paren");
	// force operator into inStack
	// (start chain reaction)
	//
	// "(1 * 2 + 3)"
	//
	// [O]: ( * +
	// [E]: 1 2 3
	// [I]: )
	inStack.push(opStack.top());
	opStack.pop();
	while (!inStack.empty())
	{
		// STEP #2 (LOAD)
		// load inStack with opStack, elemStack elements
		// (stop at appropriate point)
		//
		// "(1 * 2 + 3)"
		//
		// [O]: (
		// [E]: 1
		// [I]: ) 3 + 2 *
		while
			(
				(opStack.top()[0] == OP_SET && TS_Util::rankOp(opStack.top()[0]) > TS_Util::rankOp(inStack.top()[0])) ||
				(opStack.top()[0] != OP_SET && TS_Util::rankOp(opStack.top()[0]) >= TS_Util::rankOp(inStack.top()[0])) ||
				opStack.top() == ")"
			)
		{
			// transfer close-parens to inStack
			// (if any)
			while (opStack.top() == ")")
			{
				inStack.push(opStack.top());
				opStack.pop();
			}
			// transfer operand to inStack
			inStack.push(elemStack.top());
			elemStack.pop();
			// force operator into inStack
			// (continue chain reaction)
			if (opStack.top() != "(")
			{
				inStack.push(opStack.top());
				opStack.pop();
			}
		}
		// STEP #3 (BIND)
		// bind elemStack, inStack operands with an opStack operator
		// (push result into elemStack)
		//
		// "(1 * 2 + 3)"
		//
		// [O]: ( *
		// [E]: 1
		// [I]: ) 3 + 2
		//
		// [O]: ( +
		// [E]: 2
		// [I]: ) 3
		//
		// [O]: (
		// [E]: 5
		// [I]: )
		//
		// [O]:
		// [E]: 5
		// [I]:
		while (TS_Util::rankOp(opStack.top()[0]) <= TS_Util::rankOp(inStack.top()[0]))
		{
			if (TS_Util::rankOp(inStack.top()[0]))
			{
				//======================================================
				opStack.push(inStack.top());
				inStack.pop();
				float temp =
					this->bind(
						elemStack.top(), opStack.top()[0], inStack.top()
						);
				result = (fabs(temp) == HUGE_VAL) ? "0" : cstr(temp);
				opStack.pop();
				elemStack.pop();
				//======================================================
			}
			else
				result = inStack.top();
			//============
			inStack.pop();
			//============
			while (!opStack.empty() && opStack.top() == "(" && inStack.top() == ")")
			{
				opStack.pop();
				inStack.pop();
			}
			if (inStack.empty())
			{
				if (isNumeric(result))
					return val(result);
				else
					return this->getVar(result);
			}
			else
				elemStack.push(result);
		}
	}
	throw Exception("unknown error");
}
void ClangWorkerThread::ProcessRequest(ThreadRequest* request)
{
    // Send start event
    PostEvent(wxEVT_CLANG_PCH_CACHE_STARTED, "");

    ClangThreadRequest* task = dynamic_cast<ClangThreadRequest*>(request);
    wxASSERT_MSG(task, "ClangWorkerThread: NULL task");

    {
        // A bit of optimization
        wxCriticalSectionLocker locker(m_criticalSection);
        if(task->GetContext() == CTX_CachePCH && m_cache.Contains(task->GetFileName())) {
            // Nothing to be done here
            PostEvent(wxEVT_CLANG_PCH_CACHE_ENDED, task->GetFileName());
            return;
        }
    }

    CL_DEBUG(wxT("==========> [ ClangPchMakerThread ] ProcessRequest started: %s"), task->GetFileName().c_str());
    CL_DEBUG(wxT("ClangWorkerThread:: processing request %d"), (int)task->GetContext());

    ClangCacheEntry cacheEntry = findEntry(task->GetFileName());
    CXTranslationUnit TU = cacheEntry.TU;
    CL_DEBUG(wxT("ClangWorkerThread:: found cached TU: %p"), (void*)TU);

    bool reparseRequired = true;
    if(!TU) {

        // First time creating the TU
        TU = DoCreateTU(task->GetIndex(), task, true);
        reparseRequired = false;
        cacheEntry.lastReparse = time(NULL);
        cacheEntry.TU = TU;
        cacheEntry.sourceFile = task->GetFileName();
    }

    if(!TU) {
        CL_DEBUG(wxT("Failed to parse Translation UNIT..."));
        PostEvent(wxEVT_CLANG_TU_CREATE_ERROR, task->GetFileName());
        return;
    }

    if(reparseRequired && task->GetContext() == ::CTX_ReparseTU) {
        DoSetStatusMsg(wxString::Format(wxT("clang: re-parsing file %s..."), task->GetFileName().c_str()));

        // We need to reparse the TU
        CL_DEBUG(wxT("Calling clang_reparseTranslationUnit... [CTX_ReparseTU]"));
        if(clang_reparseTranslationUnit(TU, 0, NULL, clang_defaultReparseOptions(TU)) == 0) {
            CL_DEBUG(wxT("Calling clang_reparseTranslationUnit... done [CTX_ReparseTU]"));
            cacheEntry.lastReparse = time(NULL);

        } else {

            CL_DEBUG(wxT("An error occured during reparsing of the TU for file %s. TU: %p"),
                     task->GetFileName().c_str(),
                     (void*)TU);

            // The only thing that left to be done here, is to dispose the TU
            clang_disposeTranslationUnit(TU);
            PostEvent(wxEVT_CLANG_TU_CREATE_ERROR, task->GetFileName());

            return;
        }
    }

    // Construct a cache-returner class
    // which makes sure that the TU is cached
    // when we leave the current scope
    CacheReturner cr(this, cacheEntry);

    // Prepare the 'End' event
    wxCommandEvent eEnd(wxEVT_CLANG_PCH_CACHE_ENDED);
    ClangThreadReply* reply = new ClangThreadReply;
    reply->context = task->GetContext();
    reply->filterWord = task->GetFilterWord();
    reply->filename = task->GetFileName().c_str();
    reply->results = NULL;

    wxFileName realFileName(reply->filename);
    if(realFileName.GetFullName().StartsWith(CODELITE_CLANG_FILE_PREFIX)) {
        realFileName.SetFullName(realFileName.GetFullName().Mid(strlen(CODELITE_CLANG_FILE_PREFIX)));
    }
    reply->filename = realFileName.GetFullPath();

    if(task->GetContext() == CTX_CodeCompletion || task->GetContext() == CTX_WordCompletion ||
       task->GetContext() == CTX_Calltip) {
        CL_DEBUG(wxT("Calling clang_codeCompleteAt..."));

        ClangThreadRequest::List_t usList = task->GetModifiedBuffers();
        usList.push_back(std::make_pair(task->GetFileName(), task->GetDirtyBuffer()));
        ClangUnsavedFiles usf(usList);

        CL_DEBUG(wxT("Location: %s:%u:%u"), task->GetFileName().c_str(), task->GetLine(), task->GetColumn());
        reply->results = clang_codeCompleteAt(TU,
                                              cstr(task->GetFileName()),
                                              task->GetLine(),
                                              task->GetColumn(),
                                              usf.GetUnsavedFiles(),
                                              usf.GetCount(),
                                              clang_defaultCodeCompleteOptions()
#if HAS_LIBCLANG_BRIEFCOMMENTS
                                                  |
                                                  CXCodeComplete_IncludeBriefComments
#endif
                                              );

        cacheEntry.lastReparse = time(NULL);

        CL_DEBUG(wxT("Calling clang_codeCompleteAt... done"));
        wxString displayTip;
        bool hasErrors(false);
        if(reply->results) {
            unsigned maxErrorToDisplay = 10;
            std::set<wxString> errorMessages;
            unsigned errorCount = clang_codeCompleteGetNumDiagnostics(reply->results);
            // Collect all errors / fatal errors and report them back to user
            for(unsigned i = 0; i < errorCount; i++) {
                CXDiagnostic diag = clang_codeCompleteGetDiagnostic(reply->results, i);
                CXDiagnosticSeverity severity = clang_getDiagnosticSeverity(diag);
                if(!hasErrors) {
                    hasErrors = (severity == CXDiagnostic_Error || severity == CXDiagnostic_Fatal);
                }

                if(severity == CXDiagnostic_Error || severity == CXDiagnostic_Fatal || severity == CXDiagnostic_Note) {
                    CXString diagStr = clang_getDiagnosticSpelling(diag);
                    wxString wxDiagString = wxString(clang_getCString(diagStr), wxConvUTF8);

                    // Collect up to 10 error messages
                    // and dont collect the same error twice
                    if(errorMessages.find(wxDiagString) == errorMessages.end() &&
                       errorMessages.size() <= maxErrorToDisplay) {
                        errorMessages.insert(wxDiagString);
                        displayTip << wxDiagString.c_str() << wxT("\n");
                    }

                    clang_disposeString(diagStr);
                }
                clang_disposeDiagnostic(diag);
            }

            CL_DEBUG(wxT("Found %u matches"), reply->results->NumResults);
            ClangUtils::printCompletionDiagnostics(reply->results);
        }

        if(!displayTip.IsEmpty() && hasErrors) {
            // Send back the error messages
            reply->errorMessage << "clang: " << displayTip;
            reply->errorMessage.RemoveLast();
            
            // Free the results
            clang_disposeCodeCompleteResults(reply->results);
            reply->results = NULL;
        }

        // Send the event
        eEnd.SetClientData(reply);
        EventNotifier::Get()->AddPendingEvent(eEnd);

    } else if(task->GetContext() == CTX_GotoDecl || task->GetContext() == CTX_GotoImpl) {

        // Check to see if the file was modified since it was last reparsed
        // If it does, we need to re-parse it again
        wxFileName fnSource(cacheEntry.sourceFile);
        time_t fileModificationTime = fnSource.GetModificationTime().GetTicks();
        time_t lastReparseTime = cacheEntry.lastReparse;

        if(fileModificationTime > lastReparseTime) {

            // The file needs to be re-parsed
            DoSetStatusMsg(wxString::Format(wxT("clang: re-parsing file %s...\n"), cacheEntry.sourceFile));

            // Try reparsing the TU
            ClangThreadRequest::List_t usList = task->GetModifiedBuffers();
            usList.push_back(std::make_pair(task->GetFileName(), task->GetDirtyBuffer()));
            ClangUnsavedFiles usf(usList);

            if(clang_reparseTranslationUnit(
                   TU, usf.GetCount(), usf.GetUnsavedFiles(), clang_defaultReparseOptions(TU)) != 0) {
                // Failed to reparse
                cr.SetCancelled(true); // cancel the re-caching of the TU

                DoSetStatusMsg(
                    wxString::Format("clang: clang_reparseTranslationUnit '%s' failed\n", cacheEntry.sourceFile));

                clang_disposeTranslationUnit(TU);
                wxDELETE(reply);
                PostEvent(wxEVT_CLANG_TU_CREATE_ERROR, task->GetFileName());
                return;
            }

            DoSetStatusMsg(
                wxString::Format("clang: clang_reparseTranslationUnit '%s' - done\n", cacheEntry.sourceFile));
            // Update the 'lastReparse' field
            cacheEntry.lastReparse = time(NULL);
        }

        bool success = DoGotoDefinition(TU, task, reply);
        if(success) {
            eEnd.SetClientData(reply);
            EventNotifier::Get()->AddPendingEvent(eEnd);

        } else {
            DoSetStatusMsg(wxT("clang: no matches were found"));
            CL_DEBUG(wxT("Clang Goto Decl/Impl: could not find a cursor matching for position %s:%d:%d"),
                     task->GetFileName().c_str(),
                     (int)task->GetLine(),
                     (int)task->GetColumn());

            // Failed, delete the 'reply' allocatd earlier
            wxDELETE(reply);
            PostEvent(wxEVT_CLANG_TU_CREATE_ERROR, task->GetFileName());
        }
    } else {

        wxDELETE(reply);
        PostEvent(wxEVT_CLANG_PCH_CACHE_ENDED, task->GetFileName());
    }
}
示例#22
0
#include "bandit_base.h"
#include "cargseq.h"

go_bandit([]() {
    describe("pos_of_nth_arg", []()
    {
        it("null case", []() {
            static_assert(pos_of_nth_arg(cstr(""), 0) == -1, "");

        });
        it("4 args simple case", []() {
            static_assert(pos_of_nth_arg(cstr("%f%f%f%f"), 0) == 0, "");
            static_assert(pos_of_nth_arg(cstr("%f%f%f%f"), 3) == 6, "");
            static_assert(pos_of_nth_arg(cstr("%f%f%f%f"), 4) == std::size_t(-1), "");
        });
        it("4 args with %% case", []() {
            static_assert(pos_of_nth_arg(cstr(" %s %% %d %f"), 0) == 1, "");
            static_assert(pos_of_nth_arg(cstr(" %s %% %d %f"), 1) == 4, "");
            static_assert(pos_of_nth_arg(cstr(" %s %% %d %f"), 2) == 7, "");
            static_assert(pos_of_nth_arg(cstr(" %s %% %d %f"), 3) == 10, "");
        });
    });

    describe("arg_type_at_bit", [&]() {
        #define SEQ1 bit_at(0,1,2)
        #define SEQ2 bit_at(0,1,2,3,4,5)
        #define SEQ3 bit_at(0,1,2,3,4,5,6,7,8)

        it("test bit0", [&]() {
            static_assert('1' == arg_type_at_bit(0, SEQ1, '1', SEQ2, '2', SEQ3, '3'),
                "all have bit0, but SEQ1 is tested first.");
/* Process a string value */
void file_info(const string &name,const string &value)
{
    if(a) a->add_value(name,value); 
    if(t && !opt_body_file) fputs(cstr(name + ": " + value + "\n"),t); 
    if(x) x->xmlout(name,value,std::string(),true); // escape the XML
}
示例#24
0
文件: px.c 项目: adrian17/jsource
A jteval(J jt,C*s){R parse(tokens(cstr(s)));}
int main(int argc, char * const *argv1)
{
    int ch;
    const char *arff_fn = 0;
    const char *text_fn = 0;
    string *xml_fn = 0;
    const char *audit_file = 0;
    bool opt_x = false;
    string command_line = xml::make_command_line(argc,argv1);
    bool opt_zap = false;
    u_int sector_size=512;			// defaults to 512; may be changed by AFF

    struct timeval tv0;
    struct timeval tv1;
    gettimeofday(&tv0,0);

    TSK_TCHAR * const *argv;

#ifdef TSK_WIN32
	char *opt_arg = NULL;
	char *argv_0 = NULL;


	argv = CommandLineToArgvW(GetCommandLineW(), &argc);
	if (argv == NULL) {
		fprintf(stderr,"Error getting wide arguments\n");
		exit(1);
	}
#else
	argv = (TSK_TCHAR * const*) argv1;
#endif
	
    while ((ch = GETOPT(argc, argv, _TSK_T("A:a:C:dfG:gmv1IMX:S:T:VZn:c:b:xOzh?"))) > 0 ) { // s: removed
	switch (ch) {
	case _TSK_T('1'): opt_sha1 = true;break;
	case _TSK_T('m'):
	    opt_body_file = 1;
	    opt_sha1 = 0;
	    opt_md5  = 1;
	    t = stdout;
	    break;
	case _TSK_T('A'):
#ifdef TSK_WIN32
		convert(OPTARG, &opt_arg);
		arff_fn = opt_arg;
#else
		arff_fn = OPTARG;
#endif
		break;
	case _TSK_T('C'): file_count_max = TATOI(OPTARG);break;
	case _TSK_T('d'): opt_debug++; break;
	case _TSK_T('f'): opt_magic = true;break;
	case _TSK_T('g'): opt_no_data = true; break;
  case _TSK_T('b'): opt_get_fragments = false; break;
	case _TSK_T('G'): opt_maxgig = TATOI(OPTARG);break;
	case _TSK_T('h'): usage(); break;
	case _TSK_T('I'): opt_ignore_ntfs_system_files=true;break;
	case _TSK_T('M'): opt_md5 = true;
	case _TSK_T('O'): opt_allocated_only=true; break;
	case _TSK_T('S'):
            opt_sector_hash = true;
            sectorhash_size = TATOI(OPTARG); break;
	case _TSK_T('T'):
#ifdef TSK_WIN32
		convert(OPTARG, &opt_arg);
		text_fn = opt_arg;
#else
		text_fn = OPTARG;
#endif
		break;
	case _TSK_T('V'): print_version();exit(0);
	case _TSK_T('X'): 
#ifdef TSK_WIN32
		convert(OPTARG, &opt_arg);
		xml_fn = new string(opt_arg);
#else
		xml_fn = new string(OPTARG);
#endif
		break;
	case _TSK_T('x'): opt_x = true;break;
	case _TSK_T('Z'): opt_zap = true;break;
	case _TSK_T('a'): 
#ifdef TSK_WIN32
		convert(OPTARG, &opt_arg);
		audit_file = opt_arg;
#else
		audit_file = OPTARG;
#endif
		break;
	case _TSK_T('c'): 
#ifdef TSK_WIN32
		convert(OPTARG, &opt_arg);
		config_file = opt_arg;
#else
		config_file = OPTARG;
#endif		
		break;
	case _TSK_T('n'):
		
#ifdef TSK_WIN32
		convert(OPTARG, &opt_arg);
		namelist.push_back(opt_arg);
#else
		namelist.push_back(OPTARG);
#endif
		break;
	    //case 's': save_outdir = optarg; opt_save = true; break;
	case _TSK_T('v'): tsk_verbose++; break; 			// sleuthkit option
	case _TSK_T('z'): opt_sha1=false;opt_md5=false;break;
	case _TSK_T('?'): usage();break;
	default:
	    fprintf(stderr, "Invalid argument: %s\n", argv[OPTIND]);
	    usage();
	}
    }

    if (OPTIND >= argc) usage();
    argc -= OPTIND;
	argv += OPTIND;
	argv1 += OPTIND;

#ifdef TSK_WIN32
		convert(argv[0],&argv_0);
		const char *filename = argv_0;
#else
	const char *filename = argv[0];
#endif
    opt_parent_tracking = true;

    if(!filename){
	errx(1,"must provide filename");
    }
    if(opt_no_data && (opt_md5 || opt_sha1 || opt_save || opt_magic)) {
      errx(1, "-g conflicts with options requiring data access (-z may be needed)");
    }

    if(opt_save){
	if(access(save_outdir.c_str(),F_OK)){
	    #ifdef WIN32
	    if(mkdir(save_outdir.c_str())) {
	    #else
	    if(mkdir(save_outdir.c_str(),0777)){
	    #endif
		err(1,"Cannot make directory: %s",save_outdir.c_str());
	    }
	}
	if(access(save_outdir.c_str(),R_OK)){
	    err(1,"Cannot access directory: %s",save_outdir.c_str());
	}
    }

    if(text_fn){
	if(access(text_fn,F_OK)==0) errx(1,"%s: file exists",text_fn);
	t = fopen(text_fn,"w");
	if(!t) err(1,"%s",text_fn);
    }

    if(arff_fn){
	if(access(arff_fn,F_OK)==0) errx(1,"%s: file exists",arff_fn);
	a = new arff("fiwalk");		// the ARFF output object
	a->set_outfile(arff_fn);
    }

    /* XML initialization */

    if(opt_x){
	x = new xml();			// default to stdout
    }
    if(xml_fn){
	if(*xml_fn == "0"){
	    string newfn = filename;
	    *xml_fn = newfn.substr(0,newfn.rfind(".")) + ".xml";
	}
	if(x) errx(1,"Cannot write XML to stdout and file at same time\n");
	if(access(xml_fn->c_str(),F_OK)==0){
	    if(opt_zap){
		if(unlink(xml_fn->c_str())){
		    err(1,"%s: file exists and cannot unlink",xml_fn->c_str());
		}
	    }
	    else{
		errx(1,"%s: file exists",xml_fn->c_str());
	    }
	}
	x = new xml(*xml_fn,true);	// we will make DTD going to a file
    }
	
    /* If no output file has been specified, output text to stdout */
    if(a==0 && x==0 && t==0){
	t = stdout;
    }

    if(strstr(filename,".aff") || strstr(filename,".afd") || strstr(filename,".afm")){
#ifndef HAVE_LIBAFFLIB
	fprintf(stderr,"ERROR: fiwalk was compiled without AFF support.\n");
	exit(0);
#else
#endif
    }

    /* If we are outputing ARFF, create the ARFF object and set the file types for the file system metadata */
    if(a){
	a->add_attribute("id",arff::NUMERIC);
	a->add_attribute("partition",arff::NUMERIC);
	a->add_attribute("filesize",arff::NUMERIC);
	a->add_attribute("mtime",arff::DATE);
	a->add_attribute("ctime",arff::DATE);
	a->add_attribute("atime",arff::DATE);
	a->add_attribute("fragments",arff::NUMERIC);
	a->add_attribute("frag1startsector",arff::NUMERIC);
	a->add_attribute("frag2startsector",arff::NUMERIC);
	a->add_attribute("filename",arff::STRING);
	if(opt_md5) a->add_attribute("md5",arff::STRING);
	if(opt_sha1) a->add_attribute("sha1",arff::STRING);
    }

    /* output per-run metadata for XML output */
    if(x){
	/* Output Dublin Core information */
	x->push("dfxml",
		"\n  xmlns='http://www.forensicswiki.org/wiki/Category:Digital_Forensics_XML'"
		"\n  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"
		"\n  xmlns:dc='http://purl.org/dc/elements/1.1/'"
		"\n  version='1.0'" );
	x->push("metadata", "");
	x->xmlout("dc:type","Disk Image",fw_empty,false);
	x->pop();
	    
	/* Output carver information per photorec standard */
	x->add_DFXML_creator("fiwalk",tsk_version_get_str(),command_line);
    }

    /* Can't use comment until after here... */
    if(config_file){
	comment("Reading configuration file %s",config_file);
	config_read(config_file);    /* Read the configuration file */
    }

    /* Check that we have a valid file format */
    if(x) x->push("source");
    partition_info("image_filename",filename);

    if(!x){
	partition_info("fiwalk_version",tsk_version_get_str());
	partition_info("start_time",mytime());
	partition_info("tsk_version",tsk_version_get_str());
    }
    if(x) x->pop();

    if (opt_debug) printf("calling tsk_img_open(%s)\n",filename);

#ifdef SIGINFO
    signal(SIGINFO,sig_info);
#endif

#ifdef TSK_WIN32
    int count = process_image_file(argc,argv1,audit_file,sector_size);
    if(count<=0 || sector_size!=512){
	comment("Retrying with 512 byte sector size.");
	count = process_image_file(argc,argv1,audit_file,512);
    }
#else
    int count = process_image_file(argc,argv,audit_file,sector_size);
    if(count<=0 || sector_size!=512){
	comment("Retrying with 512 byte sector size.");
	count = process_image_file(argc,argv,audit_file,512);
    }
#endif

    /* Calculate time elapsed (reported as a comment and with rusage) */
    struct timeval tv;
    char tvbuf[64];
    gettimeofday(&tv1,0);
    tv.tv_sec = tv1.tv_sec - tv0.tv_sec;
    if(tv1.tv_usec > tv0.tv_usec){
        tv.tv_usec = tv1.tv_usec - tv0.tv_usec;
    } else {
        tv.tv_sec--;
        tv.tv_usec = (tv1.tv_usec+1000000) - tv0.tv_usec;
    }
    sprintf(tvbuf, "%d.%06d",(int)tv.tv_sec, (int)tv.tv_usec);

    comment("clock: %s",tvbuf);

#ifdef HAVE_SYS_RESOURCE_H
#ifdef HAVE_GETRUSAGE
    /* Print usage information */
    struct rusage ru;
    memset(&ru,0,sizeof(ru));
    if(getrusage(RUSAGE_SELF,&ru)==0){
	if(x) x->push("rusage");
	partition_info("utime",ru.ru_utime);
	partition_info("stime",ru.ru_stime);
	partition_info("maxrss",ru.ru_maxrss);
	partition_info("minflt",ru.ru_minflt);
	partition_info("majflt",ru.ru_majflt);
	partition_info("nswap",ru.ru_nswap);
	partition_info("inblock",ru.ru_inblock);
	partition_info("oublock",ru.ru_oublock);
	partition_info("clocktime",tv);
	comment("stop_time: %s",cstr(mytime()));
	if(x) x->pop();
    }
#endif
#endif

    // *** Added <finished time="(time_t)" duration="<seconds>" />

    if(a){
	a->write();
	delete a;
    }

    if(t) comment("=EOF=");
    if(x) {
	x->pop();			// <dfxml>
	x->close();
	delete(x);
    }
    exit(0);
}
示例#26
0
文件: px.c 项目: adrian17/jsource
A jteva(J jt,    A w,C*s){R df1(  w,colon(one,   cstr(s)));}
示例#27
0
    /** Parse the 'detailed' Anime fields from HTML
     *
     * 
     */
    std::shared_ptr<Anime> AnimeSerializer::deserialize_details(const std::string& xml) const
    {
        typedef std::unique_ptr<xmlChar, XmlCharDeleter> xmlStringUPtr;
        auto res = std::make_shared<Anime>();
		std::unique_ptr<char[]> cstr(new char[xml.size()]);
		std::memcpy(cstr.get(), xml.c_str(), xml.size());
        std::unique_ptr<xmlDoc, XmlDocDeleter> doc(htmlReadMemory(cstr.get(), xml.size(), "http://myanimelist.net/",
                                                                   nullptr, HTML_PARSE_RECOVER
                                                                   | HTML_PARSE_NOERROR 
                                                                   | HTML_PARSE_NOWARNING
                                                                   | HTML_PARSE_NONET));
		std::unique_ptr<xmlTextReader, xmlTextReaderDeleter> reader(xmlReaderWalker(doc.get()));
		if (!reader) {
			std::cerr << "Error: Couldn't create XML reader" << std::endl;
            std::cerr << "XML follows: " << xml << std::endl;
			return nullptr;
		}
        
        enum { PRIORITY, STORAGE, REWATCHVALUE, DISCUSS, SELECTOR_NONE } selector = SELECTOR_NONE;
        enum { TAGS, COMMENTS, NONE } textarea = NONE;
        std::string textbuf;
        int ret = 1;
		for( ret = xmlTextReaderRead(reader.get()); ret == 1;
		     ret = xmlTextReaderRead(reader.get()) ) {
			const std::string name  = xmlchar_to_str(xmlTextReaderConstName (reader.get()));

            if (name == "input") {
                xmlStringUPtr type(xmlTextReaderGetAttribute(reader.get(), "type"_xml));
                xmlStringUPtr attr_name(xmlTextReaderGetAttribute(reader.get(), "name"_xml));
                xmlStringUPtr attr_value(xmlTextReaderGetAttribute(reader.get(), "value"_xml));
                if (type) {
                    if (xmlStrEqual(type.get(), "text"_xml) || xmlStrEqual(type.get(), "checkbox"_xml)) {
                        if (xmlStrEqual(attr_name.get(), "fansub_group"_xml))
                            res->set_fansub_group(xmlchar_to_str(attr_value.get()));
                        else if (xmlStrEqual(attr_name.get(), "list_downloaded_eps"_xml))
                            res->set_downloaded_items(xmlchar_to_str(attr_value.get()));
                        else if (xmlStrEqual(attr_name.get(), "list_times_watched"_xml))
                            res->set_times_consumed(xmlchar_to_str(attr_value.get()));
                        else if (xmlStrEqual(attr_name.get(), "storageVal"_xml))
                            res->set_storage_value(xmlchar_to_str(attr_value.get()));
                    }
                }
            } else if (name == "textarea" && xmlTextReaderNodeType(reader.get()) == XML_READER_TYPE_ELEMENT) {
                xmlStringUPtr attr_name(xmlTextReaderGetAttribute(reader.get(), "name"_xml));
                if (xmlStrEqual(attr_name.get(), "tags"_xml)) textarea = TAGS;
                else if (xmlStrEqual(attr_name.get(), "list_comments"_xml)) textarea = COMMENTS;
                else textarea = NONE;
                textbuf.clear();
            } else if (name == "textarea" && xmlTextReaderNodeType(reader.get()) == XML_READER_TYPE_END_ELEMENT) {
                if (textarea != NONE) {
                    switch (textarea) {
                        case TAGS:
                            /* Not a 'detailed' field */
                            break;
                        case COMMENTS:
                            res->set_comments(std::string(textbuf));
                            break;
                        case NONE:
                        default:
                            break;
                    }
                    textarea = NONE;
                }
            } else if (name == "#text" && textarea != NONE) {
                textbuf.append(xmlchar_to_str(xmlTextReaderConstValue(reader.get())));
            } else if (name == "select" && xmlTextReaderNodeType(reader.get()) == XML_READER_TYPE_ELEMENT) {
                xmlStringUPtr attr_name(xmlTextReaderGetAttribute(reader.get(), "name"_xml));
                if (xmlStrEqual(attr_name.get(), "priority"_xml)) selector = PRIORITY;
                if (xmlStrEqual(attr_name.get(), "storage"_xml)) selector = STORAGE;
                if (xmlStrEqual(attr_name.get(), "list_rewatch_value"_xml)) selector = REWATCHVALUE;
                if (xmlStrEqual(attr_name.get(), "discuss"_xml)) selector = DISCUSS;                
            } else if (name == "select" && xmlTextReaderNodeType(reader.get()) == XML_READER_TYPE_END_ELEMENT)  {
                selector = SELECTOR_NONE;
            } else if (name == "option" && xmlTextReaderNodeType(reader.get()) == XML_READER_TYPE_ELEMENT) {
                xmlStringUPtr value(xmlTextReaderGetAttribute(reader.get(), "value"_xml));
                if (xmlTextReaderMoveToAttribute(reader.get(), "selected"_xml) == 1) {
                    switch (selector) {
                        case PRIORITY:
                            res->set_priority(xmlchar_to_str(value.get()));
                            break;
                        case STORAGE:
                            res->set_storage_value(xmlchar_to_str(value.get()));
                            break;
                        case REWATCHVALUE:
                            res->set_reconsume_value(xmlchar_to_str(value.get()));
                            break;
                        case DISCUSS:
                            res->set_enable_discussion(xmlchar_to_str(value.get()));
                            break;
                        case SELECTOR_NONE:
                        default:
                            break;
                    }
                }
            }
        }

        if (ret != 0) return nullptr; // Some sort of parsing error
        
        return res;
    }
示例#28
0
文件: px.c 项目: adrian17/jsource
A jtevc(J jt,A a,A w,C*s){R df2(a,w,colon(num[2],cstr(s)));}
示例#29
0
文件: main.cpp 项目: shobhit6993/dash
void initialize_dash_dirs() {
    mkdir(cstr(PATH), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
    mkdir(cstr(GENOME_PATH), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
    mkdir(cstr(DB_PATH), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
示例#30
0
文件: log.cpp 项目: JGRennison/retcon
void dump_pending_acc(LOGT logflags, const std::string &indent, const std::string &indentstep, taccount *acc) {
	LogMsgFormat(logflags, "%sAccount: %s (%s)", cstr(indent), cstr(acc->name), cstr(acc->dispname));
	for (auto &it : acc->pendingusers) {
		dump_pending_user(logflags, indent + indentstep, indentstep, it.second.get());
	}
}