Beispiel #1
0
/* reverse a string in place, return str */
static void reverse(string &str) {
  string stemp(str);
  str.clear();
  for(int i=stemp.size()-1;i>=0;i--) str.push_back(stemp[i]);
}
/// Retrieves the specified document; NULL if error.
Document *NeonDownloader::retrieveUrl(const DocumentInfo &docInfo)
{
	Document *pDocument = NULL;
	string url = Url::escapeUrl(docInfo.getLocation());
	char *pContent = NULL;
	size_t contentLen = 0;
	int statusCode = 200;
	unsigned int redirectionsCount = 0;

	if (url.empty() == true)
	{
#ifdef DEBUG
		cerr << "NeonDownloader::retrieveUrl: no URL specified !" << endl;
#endif
		return NULL;
	}
	Url urlObj(url);
	string protocol = urlObj.getProtocol();
	string hostName = urlObj.getHost();
	string location = urlObj.getLocation();
	string file = urlObj.getFile();
	string parameters = urlObj.getParameters();

	if (pthread_mutex_lock(&g_accessLock) != 0)
	{
		return NULL;
	}

	// Create a session
	ne_session *pSession = ne_session_create(protocol.c_str(), hostName.c_str(), 80); // urlObj.getPort());
	if (pSession == NULL)
	{
#ifdef DEBUG
		cerr << "NeonDownloader::retrieveUrl: couldn't create session !" << endl;
#endif
		pthread_mutex_unlock(&g_accessLock);
		return NULL;
	}
	// Set the user agent
	ne_set_useragent(pSession, m_userAgent.c_str());
	// ...and the timeout
	ne_set_read_timeout(pSession, (int)m_timeout);

	string fullLocation = "/";
	if (location.empty() == false)
	{
		fullLocation += location;
	}
	if (file.empty() == false)
	{
		if (location.empty() == false)
		{
			fullLocation += "/";
		}
		fullLocation += file;
	}
	if (parameters.empty() == false)
	{
		fullLocation += "?";
		fullLocation += parameters;
	}

	// Create a request for this URL
	ne_request *pRequest = ne_request_create(pSession, "GET", fullLocation.c_str());
	pthread_mutex_unlock(&g_accessLock);
	if (pRequest == NULL)
	{
#ifdef DEBUG
		cerr << "NeonDownloader::retrieveUrl: couldn't create request !" << endl;
#endif
		ne_session_destroy(pSession);
		return NULL;
	}
#ifdef DEBUG
	cout << "NeonDownloader::retrieveUrl: request for " << fullLocation << " on " << hostName << endl;
#endif

	int requestStatus = NE_RETRY;
	while (requestStatus == NE_RETRY)
	{
		// FIXME: this is apparently the only way to get the value of an HTTP header
		g_locationHeaderValue.clear();
		ne_add_response_header_handler(pRequest, "Location", headerHandler, (void*)1);
		ne_add_response_header_handler(pRequest, "Content-Type", headerHandler, (void*)2);

		// Begin the request
		requestStatus = ne_begin_request(pRequest);
#ifdef DEBUG
		cout << "NeonDownloader::retrieveUrl: request begun with status " << requestStatus << endl;
#endif
		if (requestStatus == NE_OK)
		{
			ssize_t bytesRead = 0;
			char buffer[1024];

			// Get the status
			const ne_status *pStatus = ne_get_status(pRequest);
			if (pStatus != NULL)
			{
				statusCode = pStatus->code;
#ifdef DEBUG
				cout << "NeonDownloader::retrieveUrl: status is " << statusCode << endl;
#endif
			}
			else
			{
				// Assume all is well
				statusCode = 200;
			}

			// Read the content
			while ((bytesRead = ne_read_response_block(pRequest, buffer, 1024)) > 0)
			{
				pContent = (char*)realloc(pContent, contentLen + bytesRead);
				memcpy((void*)(pContent + contentLen), (const void*)buffer, bytesRead);
				contentLen += bytesRead;
			}

			// Redirection ?
			if ((statusCode >= 300) &&
				(statusCode < 400) &&
				(redirectionsCount < 10))
			{
				ne_end_request(pRequest);
				ne_request_destroy(pRequest);
				pRequest = NULL;

				string documentUrl = handleRedirection(pContent, contentLen);
				if (documentUrl.empty() == true)
				{
					// Did we find a Location header ?
					if (g_locationHeaderValue.empty() == true)
					{
						// Fail
						free(pContent);
						pContent = NULL;
						contentLen = 0;
						break;
					}
					documentUrl = g_locationHeaderValue;
				}

#ifdef DEBUG
				cout << "NeonDownloader::retrieveUrl: redirected to " << documentUrl << endl;
#endif
				urlObj = Url(documentUrl);
				location = urlObj.getLocation();
				file = urlObj.getFile();

				// Is this on the same host ?
				if (hostName != urlObj.getHost())
				{
					// No, it isn't
					hostName = urlObj.getHost();

					// Create a new session
					ne_session_destroy(pSession);
					pSession = ne_session_create(protocol.c_str(), hostName.c_str(), 80); // urlObj.getPort());
					if (pSession == NULL)
					{
#ifdef DEBUG
						cerr << "NeonDownloader::retrieveUrl: couldn't create session !" << endl;
#endif
						return NULL;
					}
					ne_set_useragent(pSession, m_userAgent.c_str());
					ne_set_read_timeout(pSession, (int)m_timeout);
				}

				// Try again
				fullLocation = "/";
				if (location.empty() == false)
				{
					fullLocation += location;
					fullLocation += "/";
				}
				if (file.empty() == false)
				{
					fullLocation += file;
				}
#ifdef DEBUG
				cout << "NeonDownloader::retrieveUrl: redirected to " << fullLocation << " on " << hostName << endl;
#endif

				// Create a new request for this URL
				pRequest = ne_request_create(pSession, "GET", fullLocation.c_str());
				if (pRequest == NULL)
				{
#ifdef DEBUG
					cerr << "NeonDownloader::retrieveUrl: couldn't create request !" << endl;
#endif
					ne_session_destroy(pSession);
					return NULL;
				}
				redirectionsCount++;
				requestStatus = NE_RETRY;

				// Discard whatever content we have already got
				free(pContent);
				pContent = NULL;
				contentLen = 0;
				continue;
			}
		}

		// End the request
		requestStatus = ne_end_request(pRequest);
	}

	if ((pContent != NULL) &&
		(contentLen > 0))
	{
		if (statusCode < 400)
		{
			// Is it an HTML type ?
			if (g_contentTypeHeaderValue.find("html") != string::npos)
			{
				pDocument = new HtmlDocument(docInfo.getTitle(), url,
					g_contentTypeHeaderValue, docInfo.getLanguage());
			}
			else
			{
				pDocument = new Document(docInfo.getTitle(), url,
					g_contentTypeHeaderValue, docInfo.getLanguage());
			}
			// ...and copy the content into it
			pDocument->setData(pContent, contentLen);
#ifdef DEBUG
			cout << "NeonDownloader::retrieveUrl: document size is " << contentLen << endl;
#endif
		}
		free(pContent);
	}

	// Cleanup
	ne_request_destroy(pRequest);
	ne_session_destroy(pSession);

	return pDocument;
}
bool XML_MacroParser::Start()
{
	input.clear();
	output.clear();
	return true;
}
Beispiel #4
0
string getComment() {
	string temp = sComment;
	sComment.clear();
	return temp;
}
Beispiel #5
0
void readToken(string& token) {	//should handle comments
	token.clear();
	char c = clearWhitespace();
	while(sStream->good()) {
#if 1
		while(c == '/') {  //check for comments, C/C++-style
			char d = getCharOnLine();
			if(d == '/') {  //C++style
				char e = getCharOnLine();
				bool doDoxygen = e == '/';
				if(doDoxygen)
					sComment += "///";
				do {
					c = getCharOnLine();
					if(doDoxygen)
						sComment += c;
				} while(c != '\n');
				c = clearWhitespace();
			} else if(d == '*') { //C-style or Doxygen
				char e = getCharOnLine();
				bool doDoxygen = e == '*';
				if(doDoxygen)
					sComment += "/**";
				while(true) {
					e = getCharOnLine();
					if(doDoxygen && e != '\t')
						sComment += e;
					if(e == '*') {
						e = getCharOnLine();
						if(doDoxygen)
							sComment += e;
						if(e == '/') {
							if(doDoxygen) {
								sComment += '\n';
								//printf("doEOL\n");
							}
							break;
						}	//if(e == '/')
					}	//if(e == '*')
				}	//while(true)
				c = clearWhitespace();
			} else {
				if(d == '\n')
					sLine--;
				sStream->unget();
			}	//if(d == '/')
		}	//while(c == '/')
#endif
		if(isspace(c) || isDelimiter(c)) {
			if(!token.size())
				token += c;
			break;
		}
		token += c;
		c = getCharOnLine();
	}
	if(!isDelimiter(token))
		sStream->unget();
	//printf("Token: \"%s\"\n", token.c_str());
	//if(token.size() == 0)
		//tokenError(token);
}
Beispiel #6
0
 void clear ()
 {
     _negated = false;
     _chars.clear ();
 }
/* Mangle the type name that's represented by the vector size and list of tokens.
 * The mangling will be returned in full form in 'mangling'.  'compressedMangling'
 * will have the compressed equivalent.  This is built using the 'previousManglings'
 * list.  false is returned if an error is encountered.
 *
 * This function is recursive because compression is possible at each level of the definition.
 * See http://mentorembedded.github.io/cxx-abi/abi.html#mangle.type for a description
 * of the Itanium mangling used by llvm.
 *
 * This function mangles correctly the types currently used by RenderScript.  It does
 * not currently mangle more complicated types like function pointers, namespaces,
 * or other C++ types.  In particular, we don't deal correctly with parenthesis.
 */
static bool mangleType(string vectorSize, list<string>* tokens, vector<string>* previousManglings,
                       string* mangling, string* compressedMangling) {
    string delta;                 // The part of the mangling we're generating for this recursion.
    bool isTerminal = false;      // True if this iteration parses a terminal node in the production.
    bool canBeCompressed = true;  // Will be false for manglings of builtins.

    if (tokens->back() == "*") {
        delta = "P";
        tokens->pop_back();
    } else if (eatFront(tokens, "const")) {
        delta = "K";
    } else if (eatFront(tokens, "volatile")) {
        delta = "V";
    } else if (vectorSize != "1" && vectorSize != "") {
        // For vector, prefix with the abbreviation for a vector, including the size.
        delta = "Dv" + vectorSize + "_";
        vectorSize.clear();  // Reset to mark the size as consumed.
    } else if (eatFront(tokens, "struct")) {
        // For a structure, we just use the structure name
        if (tokens->size() == 0) {
            cerr << "Expected a name after struct\n";
            return false;
        }
        delta = mangleLongName(tokens->front());
        isTerminal = true;
        tokens->pop_front();
    } else {
        const char* c = findManglingOfBuiltInType(tokens);
        if (c) {
            // It's a basic type.  We don't use those directly for compression.
            delta = c;
            isTerminal = true;
            canBeCompressed = false;
        } else if (tokens->size() > 0) {
            // It's a complex type name.
            delta = mangleLongName(tokens->front());
            isTerminal = true;
            tokens->pop_front();
        }
    }

    if (isTerminal) {
        // If we're the terminal node, there should be nothing left to mangle.
        if (tokens->size() > 0) {
            cerr << "Expected nothing else but found";
            for (const auto& t : *tokens) {
                cerr << " " << t;
            }
            cerr << "\n";
            return false;
        }
        *mangling = delta;
        *compressedMangling = delta;
    } else {
        // We're not terminal.  Recurse and prefix what we've translated this pass.
        if (tokens->size() == 0) {
            cerr << "Expected a more complete type\n";
            return false;
        }
        string rest, compressedRest;
        if (!mangleType(vectorSize, tokens, previousManglings, &rest, &compressedRest)) {
            return false;
        }
        *mangling = delta + rest;
        *compressedMangling = delta + compressedRest;
    }

    /* If it's a built-in type, we don't look at previously emitted ones and we
     * don't keep track of it.
     */
    if (!canBeCompressed) {
        return true;
    }

    // See if we've encountered this mangling before.
    for (size_t i = 0; i < previousManglings->size(); ++i) {
        if ((*previousManglings)[i] == *mangling) {
            // We have a match, construct an index reference to that previously emitted mangling.
            ostringstream stream2;
            stream2 << 'S';
            if (i > 0) {
                stream2 << (char)('0' + i - 1);
            }
            stream2 << '_';
            *compressedMangling = stream2.str();
            return true;
        }
    }

    // We have not encountered this before.  Add it to the list.
    previousManglings->push_back(*mangling);
    return true;
}
// default implementation based on numProps/getDescriptorByIndex
// Derived classes with array-like container may directly override this method for more efficient access
PropertyDescriptorPtr PropertyContainer::getDescriptorByName(string aPropMatch, int &aStartIndex, int aDomain, PropertyDescriptorPtr aParentDescriptor)
{
  int n = numProps(aDomain, aParentDescriptor);
  if (aStartIndex<n && aStartIndex!=PROPINDEX_NONE) {
    // aPropMatch syntax
    // - simple name to match a specific property
    // - empty name or only "*" to match all properties. At this level, there's no difference, but empty causes deep traversal, * does not
    // - name part with a trailing asterisk: wildcard.
    // - #n to access n-th property
    PropertyDescriptorPtr propDesc;
    bool wildcard = false; // assume no wildcard
    if (aPropMatch.empty()) {
      wildcard = true; // implicit wildcard, empty name counts like "*"
    }
    else if (aPropMatch[aPropMatch.size()-1]=='*') {
      wildcard = true; // explicit wildcard at end of string
      aPropMatch.erase(aPropMatch.size()-1); // remove the wildcard char
    }
    else if (aPropMatch[0]=='#') {
      // special case 2 for reading: #n to access n-th subproperty
      int newIndex = n; // set out of range by default
      if (sscanf(aPropMatch.c_str()+1, "%d", &newIndex)==1) {
        // name does not matter, pick item at newIndex unless below current start
        wildcard = true;
        aPropMatch.clear();
        if(newIndex>=aStartIndex)
          aStartIndex = newIndex; // not yet passed this index in iteration -> use it
        else
          aStartIndex = n; // already passed -> make out of range
      }
    }
    while (aStartIndex<n) {
      propDesc = getDescriptorByIndex(aStartIndex, aDomain, aParentDescriptor);
      // check for match
      if (wildcard && aPropMatch.size()==0)
        break; // shortcut for "match all" case
      // match beginning
      if (
        (!wildcard && aPropMatch==propDesc->name()) || // complete match
        (wildcard && (strncmp(aPropMatch.c_str(),propDesc->name(),aPropMatch.size())==0)) // match of name's beginning
      ) {
        break; // this entry matches
      }
      // next
      aStartIndex++;
    }
    if (aStartIndex<n) {
      // found a descriptor
      // - determine next index
      aStartIndex++;
      if (aStartIndex>=n)
        aStartIndex=PROPINDEX_NONE;
      // - return the descriptor
      return propDesc;
    }
  }
  // failure
  // no more descriptors
  aStartIndex=PROPINDEX_NONE;
  return PropertyDescriptorPtr(); // no descriptor
}
    void run(Mat& image, string& output, vector<Rect>* component_rects=NULL,
             vector<string>* component_texts=NULL, vector<float>* component_confidences=NULL,
             int component_level=0)
    {

        CV_Assert( (image.type() == CV_8UC1) || (image.type() == CV_8UC3) );

#ifdef HAVE_TESSERACT

        if (component_texts != 0)
            component_texts->clear();
        if (component_rects != 0)
            component_rects->clear();
        if (component_confidences != 0)
            component_confidences->clear();

        tess.SetImage((uchar*)image.data, image.size().width, image.size().height, image.channels(), image.step1());
        tess.Recognize(0);
        char *outText;
        outText = tess.GetUTF8Text();
        output = string(outText);
        delete [] outText;

        if ( (component_rects != NULL) || (component_texts != NULL) || (component_confidences != NULL) )
        {
            tesseract::ResultIterator* ri = tess.GetIterator();
            tesseract::PageIteratorLevel level = tesseract::RIL_WORD;
            if (component_level == OCR_LEVEL_TEXTLINE)
                level = tesseract::RIL_TEXTLINE;

            if (ri != 0) {
                do {
                    const char* word = ri->GetUTF8Text(level);
                    if (word == NULL)
                        continue;
                    float conf = ri->Confidence(level);
                    int x1, y1, x2, y2;
                    ri->BoundingBox(level, &x1, &y1, &x2, &y2);

                    if (component_texts != 0)
                        component_texts->push_back(string(word));
                    if (component_rects != 0)
                        component_rects->push_back(Rect(x1,y1,x2-x1,y2-y1));
                    if (component_confidences != 0)
                        component_confidences->push_back(conf);

                    delete[] word;
                } while (ri->Next(level));
            }
            delete ri;
        }

        tess.Clear();

#else

        cout << "OCRTesseract(" << component_level << image.type() <<"): Tesseract not found." << endl;
        output.clear();
        if(component_rects)
            component_rects->clear();
        if(component_texts)
            component_texts->clear();
        if(component_confidences)
            component_confidences->clear();
#endif
    }
void dirERROR(string &line, RawSource *) {
  skipblanks(line);
  error(line,ERRPASS1);
  line.clear();
}
Beispiel #11
0
void ProcessController::ConvertToGCode(string &GcodeTxt, const string &GcodeStart, const string &GcodeLayer, const string &GcodeEnd)
{
	if(gui)
	{gui->ProgressBar->value(0);
		gui->ProgressBar->label("Converting");
		gui->ProgressBar->maximum(Max.z);
	}

	// Make Layers
	uint LayerNr = 0;
	printOffset = PrintMargin;

	float z=Min.z+LayerThickness*0.5f;				// Offset it a bit in Z, z=0 gives a empty slice because no triangles crosses this Z value

	gcode.commands.clear();

	float destinationZ=PrintMargin.z;

	if(RaftEnable)
		{
		printOffset += Vector3f(RaftSize, RaftSize, 0);
		MakeRaft(destinationZ);
		}
	float E=0.0f;
	while(z<Max.z+LayerThickness*0.5f)
	{
		if(gui)
		{
			gui->ProgressBar->value(z);
			gui->ProgressBar->redraw();
			Fl::check();
		}
		for(uint o=0;o<rfo.Objects.size();o++)
			for(uint f=0;f<rfo.Objects[o].files.size();f++)
				{
				STL* stl = &rfo.Objects[o].files[f].stl;	// Get a pointer to the object
				Matrix4f T = GetSTLTransformationMatrix(o,f);
				Vector3f t = T.getTranslation();
				t+= Vector3f(PrintMargin.x+RaftSize*RaftEnable, PrintMargin.y+RaftSize*RaftEnable, 0);
				T.setTranslation(t);
				CuttingPlane plane;
				stl->CalcCuttingPlane(z, plane, T);	// output is alot of un-connected line segments with individual vertices, describing the outline

				float hackedZ = z;
				while(plane.LinkSegments(hackedZ, ExtrudedMaterialWidth*0.5f, DisplayCuttingPlane, m_ShrinkQuality, ShellCount) == false)	// If segment linking fails, re-calc a new layer close to this one, and use that.
					{										// This happens when there's triangles missing in the input STL
					hackedZ+= 0.1f;
					plane.polygons.clear();
					stl->CalcCuttingPlane(hackedZ, plane, T);	// output is alot of un-connected line segments with individual vertices, describing the outline
					}

				// inFill
				vector<Vector2f> infill;

				CuttingPlane infillCuttingPlane = plane;
				infillCuttingPlane.polygons = infillCuttingPlane.offsetPolygons;
				infillCuttingPlane.vertices = infillCuttingPlane.offsetVertices;
				infillCuttingPlane.offsetPolygons.clear();
				infillCuttingPlane.offsetVertices.clear();
				if(ShellOnly == false)
					{
					if(m_ShrinkQuality == SHRINK_FAST)
						infillCuttingPlane.ShrinkFast(ExtrudedMaterialWidth*0.5f, z, DisplayCuttingPlane, false, ShellCount);
					else
						infillCuttingPlane.ShrinkNice(ExtrudedMaterialWidth*0.5f, z, DisplayCuttingPlane, false, ShellCount);
					infillCuttingPlane.CalcInFill(infill, LayerNr, destinationZ, InfillDistance, InfillRotation, InfillRotationPrLayer, DisplayDebuginFill);
					}
				// Make the GCode from the plane and the infill
				plane.MakeGcode(infill, gcode, E, destinationZ, MinPrintSpeedXY, MaxPrintSpeedXY, MinPrintSpeedZ, MaxPrintSpeedZ, DistanceToReachFullSpeed, extrusionFactor, UseIncrementalEcode, Use3DGcode, EnableAcceleration);
				}
	LayerNr++;
	destinationZ += LayerThickness;
	z+=LayerThickness;
	}

	GcodeTxt.clear();
	gcode.MakeText(GcodeTxt, GcodeStart, GcodeLayer, GcodeEnd, UseIncrementalEcode, Use3DGcode);
	gui->ProgressBar->label("Done");
}
static void parseCommandLine( int argc, char* argv[], bool& isColorizeDisp, bool& isFixedMaxDisp, int& imageMode, bool retrievedImageFlags[],
                       string& filename, bool& isFileReading )
{
    // set defaut values
    isColorizeDisp = true;
    isFixedMaxDisp = false;
    imageMode = 0;

    retrievedImageFlags[0] = false;
    retrievedImageFlags[1] = true;
    retrievedImageFlags[2] = false;
    retrievedImageFlags[3] = true;
    retrievedImageFlags[4] = false;

    filename.clear();
    isFileReading = false;

    if( argc == 1 )
    {
        help();
    }
    else
    {
        for( int i = 1; i < argc; i++ )
        {
            if( !strcmp( argv[i], "--help" ) || !strcmp( argv[i], "-h" ) )
            {
                printCommandLineParams();
                exit(0);
            }
            else if( !strcmp( argv[i], "-cd" ) )
            {
                isColorizeDisp = atoi(argv[++i]) == 0 ? false : true;
            }
            else if( !strcmp( argv[i], "-fmd" ) )
            {
                isFixedMaxDisp = atoi(argv[++i]) == 0 ? false : true;
            }
            else if( !strcmp( argv[i], "-mode" ) )
            {
                imageMode = atoi(argv[++i]);
            }
            else if( !strcmp( argv[i], "-m" ) )
            {
                string mask( argv[++i] );
                if( mask.size() != 5)
                    CV_Error( CV_StsBadArg, "Incorrect length of -m argument string" );
                int val = atoi(mask.c_str());

                int l = 100000, r = 10000, sum = 0;
                for( int j = 0; j < 5; j++ )
                {
                    retrievedImageFlags[j] = ((val % l) / r ) == 0 ? false : true;
                    l /= 10; r /= 10;
                    if( retrievedImageFlags[j] ) sum++;
                }

                if( sum == 0 )
                {
                    cout << "No one output image is selected." << endl;
                    exit(0);
                }
            }
            else if( !strcmp( argv[i], "-r" ) )
            {
                filename = argv[++i];
                isFileReading = true;
            }
            else
            {
                cout << "Unsupported command line argument: " << argv[i] << "." << endl;
                exit(-1);
            }
        }
    }
}
Beispiel #13
0
int http_client::read_response_body(string& out, bool clean,
	int* real_size)
{
	if (real_size)
		*real_size = 0;
	if (body_finish_)
		return (last_ret_);

	if (stream_ == NULL)
	{
		logger_error("connect null");
		disconnected_ = true;
		return -1;
	}
	ACL_VSTREAM* vstream = stream_->get_vstream();
	if (vstream == NULL)
	{
		logger_error("connect stream null");
		disconnected_ = true;
		return -1;
	}

	if (hdr_res_ == NULL)
	{
		logger_error("response header not get yet");
		disconnected_ = true;
		return -1;
	}
	if (res_ == NULL)
		res_ = http_res_new(hdr_res_);

	if (clean)
		out.clear();

	int   saved_count = (int) out.length();
	char  buf[8192];

SKIP_GZIP_HEAD_AGAIN:  // 对于有 GZIP 头数据,可能需要重复读

	int ret = (int) http_res_body_get_sync(res_, vstream, buf, sizeof(buf));

	if (zstream_ == NULL)
	{
		if (ret > 0)
		{
			out.append(buf, ret);
			if (real_size)
				*real_size = ret;
		}
		else
		{
			body_finish_ = true; // 表示数据已经读完
			if (ret < 0)
				disconnected_ = true;
			last_ret_ = ret;
		}
		return ret;
	}

	if (ret <= 0)
	{
		if (zstream_->unzip_finish(&out) == false)
		{
			logger_error("unzip_finish error");
			return -1;
		}

		last_ret_ = ret; // 记录返回值
		body_finish_ = true; // 表示数据已经读完且解压缩完毕
		if (ret < 0)
			disconnected_ = true;
		return (int) out.length() - saved_count;
	}

	if (real_size)
		(*real_size) += ret;

	// 需要先跳过 gzip 头

	if (gzip_header_left_ >= ret)
	{
		gzip_header_left_ -= ret;
		goto SKIP_GZIP_HEAD_AGAIN;
	}

	int  n;
	if (gzip_header_left_ > 0)
	{
		n = gzip_header_left_;
		gzip_header_left_ = 0;
	}
	else
		n = 0;
	if (zstream_->unzip_update(buf + n, ret - n, &out) == false)
	{
		logger_error("unzip_update error");
		return -1;
	}
	return (int) out.length() - saved_count;
}
Beispiel #14
0
// Execute the vbox manage application and copy the output to the buffer.
//
int VBOX_VM::vbm_popen_raw(string& arguments, string& output) {
    char buf[256];
    string command;
    int retval = 0;

    // Initialize command line
    command = "VBoxManage -q " + arguments;

    // Reset output buffer
    output.clear();

#ifdef _WIN32

    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    SECURITY_ATTRIBUTES sa;
    SECURITY_DESCRIPTOR sd;
    HANDLE hReadPipe = NULL, hWritePipe = NULL;
    void* pBuf = NULL;
    DWORD dwCount = 0;
    unsigned long ulExitCode = 0;
    unsigned long ulExitTimeout = 0;
    size_t errcode_start;
    size_t errcode_end;
    string errcode;

    memset(&si, 0, sizeof(si));
    memset(&pi, 0, sizeof(pi));
    memset(&sa, 0, sizeof(sa));
    memset(&sd, 0, sizeof(sd));

    InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
    SetSecurityDescriptorDacl(&sd, true, NULL, false);

    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.bInheritHandle = TRUE;
    sa.lpSecurityDescriptor = &sd;

    if (!CreatePipe(&hReadPipe, &hWritePipe, &sa, NULL)) {
        fprintf(
            stderr,
            "%s CreatePipe failed! (%d).\n",
            boinc_msg_prefix(buf, sizeof(buf)),
            GetLastError()
        );
        goto CLEANUP;
    }
    SetHandleInformation(hReadPipe, HANDLE_FLAG_INHERIT, 0);

    si.cb = sizeof(STARTUPINFO);
    si.dwFlags |= STARTF_FORCEOFFFEEDBACK | STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
    si.wShowWindow = SW_HIDE;
    si.hStdOutput = hWritePipe;
    si.hStdError = hWritePipe;
    si.hStdInput = NULL;

    // Execute command
    if (!CreateProcess(
                NULL,
                (LPTSTR)command.c_str(),
                NULL,
                NULL,
                TRUE,
                CREATE_NO_WINDOW, NULL,
                NULL,
                &si,
                &pi
            )) {
        fprintf(
            stderr,
            "%s CreateProcess failed! (%d).\n",
            boinc_msg_prefix(buf, sizeof(buf)),
            GetLastError()
        );
        goto CLEANUP;
    }

    // Wait until process has completed
    while(1) {
        GetExitCodeProcess(pi.hProcess, &ulExitCode);

        // Copy stdout/stderr to output buffer, handle in the loop so that we can
        // copy the pipe as it is populated and prevent the child process from blocking
        // in case the output is bigger than pipe buffer.
        PeekNamedPipe(hReadPipe, NULL, NULL, NULL, &dwCount, NULL);
        if (dwCount) {
            pBuf = malloc(dwCount+1);
            memset(pBuf, 0, dwCount+1);

            if (ReadFile(hReadPipe, pBuf, dwCount, &dwCount, NULL)) {
                output += (char*)pBuf;
            }

            free(pBuf);
        }

        if (ulExitCode != STILL_ACTIVE) break;

        // Timeout?
        if (ulExitTimeout >= 60000) {
            fprintf(
                stderr,
                "%s Process Timeout!.\n",
                boinc_msg_prefix(buf, sizeof(buf))
            );

            TerminateProcess(pi.hProcess, EXIT_FAILURE);
            Sleep(1000);
        }

        Sleep(250);
        ulExitTimeout += 250;
    }

CLEANUP:
    if (pi.hThread) CloseHandle(pi.hThread);
    if (pi.hProcess) CloseHandle(pi.hProcess);
    if (hReadPipe) CloseHandle(hReadPipe);
    if (hWritePipe) CloseHandle(hWritePipe);

    if ((ulExitCode != 0) || (!pi.hProcess)) {

        // Determine the real error code by parsing the output
        errcode_start = output.find("(0x");
        if (errcode_start) {
            errcode_start += 1;
            errcode_end = output.find(")", errcode_start);
            errcode = output.substr(errcode_start, errcode_end - errcode_start);

            sscanf(errcode.c_str(), "%x", &retval);
        }

        // If something couldn't be found, just return ERR_FOPEN
        if (!retval) retval = ERR_FOPEN;
    }

#else

    FILE* fp;

    // redirect stderr to stdout for the child process so we can trap it with popen.
    string modified_command = command + " 2>&1";

    // Execute command
    fp = popen(modified_command.c_str(), "r");
    if (fp == NULL) {
        fprintf(
            stderr,
            "%s vbm_popen popen failed! errno = %d\n",
            boinc_msg_prefix(buf, sizeof(buf)),
            errno
        );
        retval = ERR_FOPEN;
    } else {
        // Copy output to buffer
        while (fgets(buf, 256, fp)) {
            output += buf;
        }

        // Close stream
        pclose(fp);
        retval = 0;
    }

#endif

    return retval;
}
void Options::GUIEventCallback_OnEvent(std::string name,GUIObject* obj,int eventType){
	//Check what type of event it was.
	if(eventType==GUIEventClick){
		if(name=="cmdBack"){
			//TODO: Reset the key changes.
			
			//And goto the main menu.
			setNextState(STATE_MENU);
		}else if(name=="cmdSave"){
			//Save is pressed thus save 
			getSettings()->setValue("sound",sound?"1":"0");
			getSettings()->setValue("music",music?"1":"0");
			getMusicManager()->setEnabled(music);
			getSettings()->setValue("fullscreen",fullscreen?"1":"0");
			getSettings()->setValue("leveltheme",leveltheme?"1":"0");
			getSettings()->setValue("internet",internet?"1":"0");
			getSettings()->setValue("theme",themeName);
			if(!useProxy)
				internetProxy.clear();
			getSettings()->setValue("internet-proxy",internetProxy);
			
			//Save the key configuration.
			inputMgr.saveConfig();
			
			//Save the settings.
			saveSettings();
			
			//Before we return show a restart message, if needed.
			if(restartFlag)
				msgBox("Restart needed before the changes have effect.",MsgBoxOKOnly,"Restart needed");
			
			//Now return to the main menu.
			setNextState(STATE_MENU);
		}else if(name=="cmdKeys"){
			inputMgr.showConfig();
		}else if(name=="cmdReset"){
			if(msgBox("Do you really want to reset level progress?",MsgBoxYesNo,"Warning")==MsgBoxYes){
				//We delete the progress folder.
#ifdef WIN32
				removeDirectory((getUserPath()+"progress").c_str());
				createDirectory((getUserPath()+"progress").c_str());
#else
				removeDirectory((getUserPath(USER_DATA)+"/progress").c_str());
				createDirectory((getUserPath(USER_DATA)+"/progress").c_str());
#endif
			}
			return;
		}else if(name=="chkMusic"){
			music=obj->value?true:false;
		}else if(name=="chkSound"){
			sound=obj->value?true:false;
		}else if(name=="chkFullscreen"){
			fullscreen=obj->value?true:false;
			
			//Check if fullscreen changed.
			if(fullscreen==getSettings()->getBoolValue("fullscreen")){
				//We disable the restart message flag.
				restartFlag=false;
			}else{
				//We set the restart message flag.
				restartFlag=true;
			}
			  
		}else if(name=="chkLeveltheme"){
			leveltheme=obj->value?true:false;
		}else if(name=="chkInternet"){
			internet=obj->value?true:false;
		}else if(name=="chkProxy"){
			useProxy=obj->value?true:false;
		}
	}
	if(name=="lstTheme"){
		if(theme!=NULL && theme->value>=0 && theme->value<(int)theme->item.size()){
			//Check if the theme is installed in the data path.
			if(themeLocations[theme->item[theme->value]].find(getDataPath())!=string::npos){
				themeName="%DATA%/themes/"+fileNameFromPath(themeLocations[theme->item[theme->value]]);
			}else if(themeLocations[theme->item[theme->value]].find(getUserPath(USER_DATA))!=string::npos){
				themeName="%USER%/themes/"+fileNameFromPath(themeLocations[theme->item[theme->value]]);
			}else{
				themeName=themeLocations[theme->item[theme->value]];
			}
		}
	}else if(name=="txtProxy"){
		internetProxy=obj->caption;
		
		//Check if the internetProxy field is empty.
		useProxy=!internetProxy.empty();
	}
}
Beispiel #16
0
// Main function
int main(){
  img.load(filename.c_str());
  // Variable for the menu options
  int menu = 0;
  string aux;
  do{
      printMenu();
      cin >> menu;
      cin.clear();

      switch(menu){
          // Change the name of the file to load
      case 1:
          cout << "Input the name of the new file to load: " << endl;
          filename.clear();
          filename.append("Images/");
          cin >> aux;
          filename.append(aux);
          filename.append(".bmp");
          try{
            img.load(filename.c_str());
          }
          catch(...){
          }
          break;
          // Change the k for the algortihm
      case 2:
          cout << "Input the new K: " << endl;
          cin >> k;
          break;
          // Change the point type
      case 3:
          cout << "Input the new Point type: " << endl;
          cout << "0- " << "DPoint with eucledian distance and RGB Defacto Colors" << endl;
          cout << "1- " << "CIELABPoint with eucledian distance and LAB Defacto Colors" << endl;
          cout << "2- " << "CIELABPoint with eucledian distance and LAB Experimental Colors" << endl;
          cout << "3- " << "CIELABPoint with euclidian distance and fuzzy color naming" << endl;
          cout << "7- " << "RGBPoint with eucledian distance and RGB Experimental Colors" << endl;
          cout << "8- " << "RGBPoint with eucledian distance and fuzzy color naming" << endl;
          cin >> PointType;
          break;
          // Call the algorithm with diferent params
      case 4:
          imageAnalysis(false, false);
          break;
      case 5:
          imageAnalysis(true, false);
          break;
      case 6:
          imageAnalysis(false, false);
          break;
      case 7:
          imageAnalysis(true, true);
          break;
          // Function to get all the files from the directory with the name Image0
      case 8:
          int numImg = -1;
          stringstream ss;
          vector<string> output;
          cout << "Start entire image folder - Caution! May be slower -" << endl;
          cout << "Insert the number of images" << endl;
          cin >> numImg;
          cout << "Insert type of image analysis" << endl;
          cout << "1- " << "Start color identification " << endl;
          cout << "2- " << "Start color identification with verbose mode " << endl;
          cout << "3- " << "Start color identification without color repetitions" << endl;
          cout << "4- " << "Start color identification with verbose mode without color repetitions " << endl;
          int mode;
          cin >> mode;
          bool Rep, Verbose;
          switch (mode){
          case 1:
              Rep = true;
              Verbose = false;
              break;
          case 2:
              Rep = true;
              Verbose = true;
              break;
          case 3:
              Rep = false;
              Verbose = false;
              break;
          case 4:
              Rep = false;
              Verbose = true;
              break;
          }
          ofstream file;
          try{
            ss.str("");
            ss << k;
            aux.append("k" + ss.str() + "-");
            ss.str("");
            ss << mode;
            aux.append("op" + ss.str() + "-");
            ss.str("");
            ss << PointType;
            aux.append("p" + ss.str());
            aux.append(".txt");
            file.open(aux.c_str());
	    aux = "";
            //file.open("output.txt");
            file << "/*****************************************************/" << "\n";
            file << "Operation mode" << "\n";
            file << "K value: " << k << "\t" << "Point type: " << PointType << "\n";
            file << "Repetitions: " << Rep << "\t" << "Verbose: " << Verbose << "\n";
            file << "/*****************************************************/" << "\n\n";
            for (int i=0; i < numImg; i++){
                cout << endl << i << endl;
                filename.clear();
                if (i < 10)
                    filename.append("Images/Image00");
                else
                    filename.append("Images/Image0");
                ss.str("");
                ss << i;
                filename.append(ss.str());
                filename.append(".bmp");
                try{
                  img.load(filename.c_str());
                  output = imageAnalysis(Rep,Verbose);
                  for (int j = 0; j < output.size(); j++){
                    file << output[j];
                    file << "\t";
                  }
                  file << "\n";
                  output.clear();
                }catch(...){
                }
            }
            file.close();
          }catch(...){
            cout << "Error creating file output.txt" << endl;
          }
          break;
      }
  }while(menu != 9);

  return 0;
}
Beispiel #17
0
int _MakePath1(DWORD Key, string &strPathName, const wchar_t *Param2,int ShortNameAsIs)
{
	int RetCode=FALSE;
	int NeedRealName=FALSE;
	strPathName.clear();

	switch (Key)
	{
		case KEY_CTRLALTBRACKET:       // Вставить сетевое (UNC) путь из левой панели
		case KEY_RCTRLRALTBRACKET:
		case KEY_CTRLRALTBRACKET:
		case KEY_RCTRLALTBRACKET:
		case KEY_CTRLALTBACKBRACKET:   // Вставить сетевое (UNC) путь из правой панели
		case KEY_RCTRLRALTBACKBRACKET:
		case KEY_CTRLRALTBACKBRACKET:
		case KEY_RCTRLALTBACKBRACKET:
		case KEY_ALTSHIFTBRACKET:      // Вставить сетевое (UNC) путь из активной панели
		case KEY_RALTSHIFTBRACKET:
		case KEY_ALTSHIFTBACKBRACKET:  // Вставить сетевое (UNC) путь из пассивной панели
		case KEY_RALTSHIFTBACKBRACKET:
			NeedRealName=TRUE;
		case KEY_CTRLBRACKET:          // Вставить путь из левой панели
		case KEY_RCTRLBRACKET:
		case KEY_CTRLBACKBRACKET:      // Вставить путь из правой панели
		case KEY_RCTRLBACKBRACKET:
		case KEY_CTRLSHIFTBRACKET:     // Вставить путь из активной панели
		case KEY_RCTRLSHIFTBRACKET:
		case KEY_CTRLSHIFTBACKBRACKET: // Вставить путь из пассивной панели
		case KEY_RCTRLSHIFTBACKBRACKET:
		case KEY_CTRLSHIFTNUMENTER:    // Текущий файл с пасс.панели
		case KEY_RCTRLSHIFTNUMENTER:
		case KEY_SHIFTNUMENTER:        // Текущий файл с актив.панели
		case KEY_CTRLSHIFTENTER:       // Текущий файл с пасс.панели
		case KEY_RCTRLSHIFTENTER:
		case KEY_SHIFTENTER:           // Текущий файл с актив.панели
		{
			Panel *SrcPanel=nullptr;
			FilePanels *Cp=Global->CtrlObject->Cp();

			switch (Key)
			{
				case KEY_CTRLALTBRACKET:
				case KEY_RCTRLRALTBRACKET:
				case KEY_CTRLRALTBRACKET:
				case KEY_RCTRLALTBRACKET:
				case KEY_CTRLBRACKET:
				case KEY_RCTRLBRACKET:
					SrcPanel=Cp->LeftPanel;
					break;
				case KEY_CTRLALTBACKBRACKET:
				case KEY_RCTRLRALTBACKBRACKET:
				case KEY_CTRLRALTBACKBRACKET:
				case KEY_RCTRLALTBACKBRACKET:
				case KEY_CTRLBACKBRACKET:
				case KEY_RCTRLBACKBRACKET:
					SrcPanel=Cp->RightPanel;
					break;
				case KEY_SHIFTNUMENTER:
				case KEY_SHIFTENTER:
				case KEY_ALTSHIFTBRACKET:
				case KEY_RALTSHIFTBRACKET:
				case KEY_CTRLSHIFTBRACKET:
				case KEY_RCTRLSHIFTBRACKET:
					SrcPanel=Cp->ActivePanel();
					break;
				case KEY_CTRLSHIFTNUMENTER:
				case KEY_RCTRLSHIFTNUMENTER:
				case KEY_CTRLSHIFTENTER:
				case KEY_RCTRLSHIFTENTER:
				case KEY_ALTSHIFTBACKBRACKET:
				case KEY_RALTSHIFTBACKBRACKET:
				case KEY_CTRLSHIFTBACKBRACKET:
				case KEY_RCTRLSHIFTBACKBRACKET:
					SrcPanel=Cp->PassivePanel();
					break;
			}

			if (SrcPanel)
			{
				if (Key == KEY_SHIFTENTER || Key == KEY_CTRLSHIFTENTER || Key == KEY_RCTRLSHIFTENTER || Key == KEY_SHIFTNUMENTER || Key == KEY_CTRLSHIFTNUMENTER || Key == KEY_RCTRLSHIFTNUMENTER)
				{
					string strShortFileName;
					SrcPanel->GetCurName(strPathName,strShortFileName);

					if (SrcPanel->GetShowShortNamesMode()) // учтем короткость имен :-)
						strPathName = strShortFileName;
				}
				else
				{
					if (!(SrcPanel->GetType()==FILE_PANEL || SrcPanel->GetType()==TREE_PANEL))
						return FALSE;

					strPathName = SrcPanel->GetCurDir();

					if (SrcPanel->GetMode()!=PLUGIN_PANEL)
					{
						if (NeedRealName)
							SrcPanel->CreateFullPathName(strPathName, strPathName, FILE_ATTRIBUTE_DIRECTORY, strPathName, TRUE, ShortNameAsIs);

						if (SrcPanel->GetShowShortNamesMode() && ShortNameAsIs)
							ConvertNameToShort(strPathName,strPathName);
					}
					else
					{
						FileList *SrcFilePanel=(FileList *)SrcPanel;
						OpenPanelInfo Info;
						Global->CtrlObject->Plugins->GetOpenPanelInfo(SrcFilePanel->GetPluginHandle(),&Info);
						FileList::AddPluginPrefix(SrcFilePanel,strPathName);
						if (Info.HostFile && *Info.HostFile)
						{
							strPathName += Info.HostFile;
							strPathName += L"/";
						}
						strPathName += NullToEmpty(Info.CurDir);
					}

					AddEndSlash(strPathName);
				}

				if (Global->Opt->QuotedName&QUOTEDNAME_INSERT)
					QuoteSpace(strPathName);

				if (Param2)
					strPathName += Param2;

				RetCode=TRUE;
			}
		}
		break;
	}

	return RetCode;
}
Beispiel #18
0
void Landscape::buildStructure(int T, string & numbuf)
/* fills the key vector */
{
	string configuration;
	bool choices[13] = {0}; 
	string binaryConfig;
	int choices_counter = 0, i = 0, L = 0, numbufLength = 0, decision = 0, X = 0, Z = 0, cc = 0, jj = 0, kk = 0, ii = 0, random_choice = 0;
	float randomTemp;
	while (decision < n){
		cc = 0;
		while (cc < 14)
			{
			choices[cc] = 0;
			cc++;
			}
		ii = 0; kk = 0; L = 0; choices_counter = 0; X = 0; Z = 0;  numbufLength = 0; binaryConfig.clear(); numbuf.clear();
		while (choices_counter < k) // this loop selects k random decisions
			{

			choices[decision] = 1;
			random_choice = rand() % (n); // random integer from 0 to n-1 as index
			if (choices[random_choice] != 1)
				{
				choices[random_choice] = 1;
				binaryConfig.push_back('0');
				choices_counter++;
				}
			}
		if ( k == 0 )
			{
			choices[decision] = 1;
			}
		// now that there is an array showing which choices matter, we need keys for each of the 2^(k+1) choices for those values
		key.resize(decision+1);
		key[decision].resize(1);
		while ( (ii < T) ) // loops across all T possible combinations C_i(d_i, d_!i) -- removed k > 0
			{
				numbuf.clear();
				configuration.clear();
				kk = 0;
				Z = 0;
				binary(X, numbuf);
				numbufLength = numbuf.length();
				binaryConfig.replace((k-numbufLength+1),numbufLength,numbuf);
				while (kk < n)
				{
				// this loop adds k chars to string key, 0 means not considered, 1 means not chosen, 2 means chosen
					if (choices[kk] == 1)
						{
							if (binaryConfig[Z] == '1'){ configuration.push_back('2'); Z++;}
							else { configuration.push_back('1'); Z++;}
						}
					else
						{
							configuration.push_back('0');
						}
					kk++;
				}
				key[decision].push_back(configuration);
				ii++;
				X++;
			}	
		decision++;
	}
}
Beispiel #19
0
	void clear()			{ val_type = T_NUM; num_val = 0; str_val.clear(); }
Beispiel #20
0
bool NBest::ParseLine(ifstream &inpf, const int n)
{
    static string line; // used internally to buffer an input line
    static int prev_id=-1; // used to detect a change of the n-best ID
    int id;
    vector<float> f;
    float s;
    int pos=0, epos;
    vector<string> blocks;


    if (line.empty()) {
        getline(inpf,line);
        if (inpf.eof()) return false;
    }

    // split line into blocks
    //cerr << "PARSE line: " << line << endl;
    while ((epos=line.find(NBEST_DELIM,pos))!=string::npos) {
        blocks.push_back(line.substr(pos,epos-pos));
        // cerr << " block: " << blocks.back() << endl;
        pos=epos+strlen(NBEST_DELIM);
    }
    blocks.push_back(line.substr(pos,line.size()));
    // cerr << " block: " << blocks.back() << endl;

    if (blocks.size()<4) {
        cerr << line << endl;
        Error("can't parse the above line");
    }

    // parse ID
    id=Scan<int>(blocks[0]);
    if (prev_id>=0 && id!=prev_id) {
        prev_id=id;  // new nbest list has started
        return false;
    }
    prev_id=id;
    //cerr << "same ID " << id << endl;

    if (n>0 && nbest.size() >= n) {
        //cerr << "skipped" << endl;
        line.clear();
        return true; // skip parsing of unused hypos
    }

    // parse feature function scores
    //cerr << "PARSE features: '" << blocks[2] << "' size: " << blocks[2].size() << endl;
    pos=blocks[2].find_first_not_of(' ');
    while (pos<blocks[2].size() && (epos=blocks[2].find(" ",pos))!=string::npos) {
        string feat=blocks[2].substr(pos,epos-pos);
        //cerr << " feat: '" << feat << "', pos: " << pos << ", " << epos << endl;
        if (feat.find(":",0)!=string::npos) {
            //cerr << "  name: " << feat << endl;
        } else {
            f.push_back(Scan<float>(feat));
            //cerr << "  value: " << f.back() << endl;
        }
        pos=epos+1;
    }

    // eventually parse segmentation
    if (blocks.size()>4) {
        Error("parsing segmentation not yet supported");
    }

    nbest.push_back(Hypo(id, blocks[1], f, Scan<float>(blocks[3])));

    line.clear(); // force read of new line

    return true;
}
Beispiel #21
0
static int read_text_arg(const char **pp, string &res)
{
  res.clear();
  while (white_space(**pp))
    *pp += 1;
  if (**pp == '\0') {
    error("missing argument");
    return 0;
  }
  if (**pp != '(') {
    for (; **pp != '\0' && !white_space(**pp); *pp += 1)
      res += **pp;
    return 1;
  }
  *pp += 1;
  res.clear();
  int level = 0;
  for (;;) {
    if (**pp == '\0' || **pp == '\r' || **pp == '\n') {
      error("missing ')'");
      return 0;
    }
    if (**pp == ')') {
      if (level == 0) {
	*pp += 1;
	break;
      }
      res += **pp;
      level--;
    }
    else if (**pp == '(') {
      level++;
      res += **pp;
    }
    else if (**pp == '\\') {
      *pp += 1;
      switch (**pp) {
      case 'n':
	res += '\n';
	break;
      case 'r':
	res += '\n';
	break;
      case 't':
	res += '\t';
	break;
      case 'b':
	res += '\b';
	break;
      case 'f':
	res += '\f';
	break;
      case '0':
      case '1':
      case '2':
      case '3':
      case '4':
      case '5':
      case '6':
      case '7':
	{
	  int val = **pp - '0';
	  if ((*pp)[1] >= '0' && (*pp)[1] <= '7') {
	    *pp += 1;
	    val = val*8 + (**pp - '0');
	    if ((*pp)[1] >= '0' && (*pp)[1] <= '7') {
	      *pp += 1;
	      val = val*8 + (**pp - '0');
	    }
	  }
	}
	break;
      default:
	res += **pp;
	break;
      }
    }
    else
      res += **pp;
    *pp += 1;
  }
  return 1;
}
Beispiel #22
0
int main(int argc, char **argv) { 
	int pin_in = 2;
	int read = 0;
	int one = 0;
	int zero = 0;
	int opt = 0;
	//int noCalc = 0;
	
	if(wiringPiSetup() == -1)
		return 0;
	piHiPri(99);
	pinMode(pin_in, INPUT);
	printf("Start\n");
	
	while((opt = getopt(argc, argv, "s:dc")) != -1) {
		switch(opt) {
			case 's':
				speed = atoi(optarg);
				//noCalc = 1;
			break;
			case 'd':
				debug = 1;
			break;
			case 'c':
				noendl = 1;
			break;
			default:
				exit(EXIT_FAILURE);
		}
	}

	while(1) {
		usleep(speed);
		if(digitalRead(pin_in) == 1) {
			one++;
			 if(read == 1 && zero > 0) {
					code.append(itos(zero));
					code.append(";");
			}
			zero=0;
		}
		if(digitalRead(pin_in) == 0) {
			zero++;
			if(read == 1 && one > 0) {
					code.append(itos(one));
					code.append(";");
			}
			one=0;
		}
		if((zero >= (start-marge)) && (zero <= (start+marge)) && read == 0) {
			read = 1;			
			zero = 0;
			one = 0;
		}
		
		if(read == 1 && zero >= end) {
			read=0;
			
			acode = explode(";",code);
			if(debug == 1) {
				cout << "Code length:\t" << acode.size() << endl;
				cout << "Code length:\t" << code << endl;
			}
			
			switch((int)acode.size()) {
				case 133:
					type = 1;
				break;
				case 149:
					type = 2;
				break;
				case 51:
					type = 3;
					bit = 3;
				break;
				default:
					type = 0;
				break;
			}
			
			if(type > 0) {
				
				if(type == 1)
					x = 7;
				if(type == 2)
					x = 11;
				createBinaryString(0);
				if(debug == 1) {
					cout << "Binary length:\t" << binary.length() << endl;
					cout << "Binary:\t" << binary << endl;
				}
				switch((int)binary.length()) {
					case 34:
						type = 1;
					break;
					case 38:
						type = 2;
					break;
					case 13:
						type = 3;
					break;
					default:
						type = 0;
					break;
				}
				binary.clear();
				if(type == 1 || type == 2) {
					createBinaryString(1);
				} else if(type == 3) {
					createBinaryString(0);
				}
				
				if((int)binary.length() >= x) {
				
					if(debug == 1) {
						showBinaryString();
						//cout << code << endl;
						//cout << code.length() << endl;
					}
					
					if(type == 1 || type == 2) {
						if(noendl == 0)
							printf("Klik Aan Klik Uit\n");
						getUniqueId();
						getAllOrSingle();
							if(type == 1)
							getOnOff();
						getUnitId();
						if(type == 2)
							getDimLevel();
						if(noendl == 1)
							cout << endl;
						usleep(5000);
					} else if(type == 3) {
						printf("Elro\n");
						binary = string(binary.rbegin(), binary.rend());
						cout << "ID:\t\t" << (int)getBinary(3,8) << endl;
						cout << "House:\t\t" << (int)getBinary(8,13) << endl;
						if((int)getBinary(1,3) == 1)
							cout << "On/Off:\t\tOn" << endl;
						else if((int)getBinary(1,3) == 2)
							cout << "On/Off:\t\tOff" << endl;
						usleep(5000);
					}
				}	
			}/*else if(debug == 1) {
				acode = explode(code,';');
				x=0;
				if((int)acode.size() > 8) {
					showBinaryString();
					cout << code << endl;
				}
				cout << code.length() << endl;
				code.clear();
			}*/
			type = 0;
			binary.clear();
			code.clear();
			acode.clear();							
			one=0;
			zero=0;
			x=0;
		}
	}
}
Beispiel #23
0
void setTokenStream(istream* is) {
	sStream = is;
	sLine = 1;
	sComment.clear();
}
void lock_file::disconnect()
{
	path.clear();
}
Beispiel #25
0
// expresie ↦ forma postfixă
bool yyexfp(void)
{
	char yylstr[200];
	int opc;			// operatorul citit (sau paranteză)
	int ops;			// operatorul din vârful stivei
	bool err = false;		// cel puțin o eroare
	bool gasit;			// găsit pereche ()
	FILE *fasm;			// codul „assembler” generat
	char nasm[20];

	sprintf(nasm, "exp%d.asm", nrlin);
	fasm = fopen(nasm, "w+");
	if (NULL == fasm) {
		fprintf(stderr, "%s: eroare: fișierul «%s» nu a putut fi deschis pentru scriere\n", nume, nasm);
		return errno;
	}

	nrcol = 0;
	nrterm = 0;
	sirexp.clear();			// eliberează memoria ocupată

	// construiesc expresia în forma postfixă
	do {
		opc = yylex();		// analiza lexicală
#ifndef NDEBUG
		//printf("~ yylex -> %d\n", opc);
#endif
		switch (opc) {
		case 0:
#ifndef NDEBUG
			printf("~ adaug %lg la expresia postfixă\n", yylval.val);
#endif
			snr.push(yylval);
			sprintf(yylstr, " %lg", yylval.val);
			sirexp += yylstr;
#ifndef NINFO
			printf("::%s\n", sirexp.c_str());
#endif
			break;
		case '(':
#ifndef NDEBUG
			printf("~ adaug %c în stivă\n", (char)opc);
#endif
			sop.push(opc);
			break;
		case '+':
		case '-':
		case '*':
		case '/':
			while (!sop.empty()) {
				ops = sop.top();
#ifndef NDEBUG
				printf("~ compar opc%c cu ops%c\n", (char)opc, (char)ops);
#endif
				if (prop(opc) > prop(ops))
					break;
				sop.pop();
				sirexp += " ";
				sirexp += ops;		// banda de ieșire
#ifndef NDEBUG
				printf("~ mutat %c din stivă la expresia postfixă\n", (char)ops);
#endif
				if (!err && yycalc(ops, fasm))
					err = true;		// eroare sintactică
			}
#ifndef NDEBUG
			printf("~ adaug %c în stivă\n", (char)opc);
#endif
			sop.push(opc);
			break;
		case ')':
			gasit = false;
			while (!sop.empty()) {
				ops = sop.top();
				sop.pop();
				if ('(' == ops) {
#ifndef NDEBUG
					printf("~ eliminat pereche paranteze ()\n");
#endif
					gasit = true;
					break;
				} else {
					sirexp += " ";
					sirexp += ops;		// banda de ieșire
#ifndef NDEBUG
					printf("~ mutat %c din stivă la expresia postfixă\n", (char)ops);
#endif
					if (!err && yycalc(ops, fasm))
						err = true;		// eroare sintactică
				}
			}
			if (!gasit) {
				err = true;		// eroare sintactică
				yyerror("')' fără pereche");
			}
			break;
		case EOF:
		case '\n':
			// am terminat de prelucrat banda de intrare
			while (!sop.empty()) {
				ops = sop.top();
				sop.pop();
				if ('(' == ops) {
					err = true;		// eroare sintactică
					yyerror("'(' fără pereche");
				} else {
					sirexp += " ";
					sirexp += ops;		// banda de ieșire
#ifndef NDEBUG
					printf("~ mutat %c din stivă la expresia postfixă\n", (char)ops);
#endif
					if (!err && yycalc(ops, fasm))
						err = true;		// eroare sintactică
				}
			}
			break;
		default:
			err = true;		// eroare semantică
			yyerror("operand sau operator invalid");
		}
	} while (('\n' != opc) && (EOF != opc));

	if (!sirexp.empty() && (snr.size() != 1)) {
		err = true;		// eroare sintactică
		yyerror("lipsește cel puțin un operand");
	}
	fclose(fasm);			// închide fișierul ASM
	return !err;
}
Beispiel #26
0
 void reset() {
     message.clear();
     errcode = 0;
 }
Beispiel #27
0
// pynpp - Console Window Callback
BOOL CALLBACK
pynpp_ConsoleProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch (message)
	{
		case WM_NOTIFY:
		{
			NMHDR* pnmh = (NMHDR*) lParam;
			if (pnmh->hwndFrom == nppData._nppHandle)
			{
				switch( LOWORD(pnmh->code) )
				{
				case DMN_CLOSE: // closing dialog
					SendNpp(NPPM_SETMENUITEMCHECK, funcItems[0]._cmdID, FALSE);
					execData.ConsoleOpen = FALSE;
					break;
				case DMN_FLOAT: // floating dialog
					break;
				case DMN_DOCK:  // docking dialog
					break;
				}
			}
			else if (pnmh->hwndFrom == execData.hConsoleScintilla)
			{
				switch( pnmh->code )
				{
					case SCN_CHARADDED:
						scNotification = (SCNotification*) lParam;
						int cPos;
						cPos = (int) SendSci(SCI_GETCURRENTPOS, 0,0);

						// New input line in console
						if (scNotification->ch == 10)
						{
							if ( SendSci(SCI_GETCURRENTPOS, 0, 0) < sciIN )
								SendSci(SCI_GOTOPOS, sciINEND, 0);

							// (Sort of) Prevent erasing of precedent text
							if (cPos <= sciIN || !multiline && cPos == sciIN+1)
							{
								PromptPy();
								break;
							}

							TextRange tr;
							char *code;
							int size;
							tr.chrg.cpMin = sciIN;
							tr.chrg.cpMax = cPos;
							size = cPos - sciIN + 1;
							code = (char*) malloc(size);
							tr.lpstrText = code;
							SendSci(SCI_GETTEXTRANGE, 0, (LPARAM) &tr);
							sciIN = cPos + 1;

							if (!multiline)
							{
								if (code[size-3] == ':')
								{
									indent.append("\t");
									command.append(code);
									multiline = TRUE;
								}
								else
								{
									PyObject* pyRet;
									pyRet = PyRun_String(code,
										Py_single_input, globals, globals);
									if (PyErr_Occurred()) PyErr_Print();
									Py_XDECREF(pyRet);
								}
							}
							else
							{
								BOOL endmultiline = TRUE;
								for (int i = 0; i < size-2; i++)
									if (code[i] != ' ' && code[i] != '\t')
									{
										endmultiline = FALSE;
										break;
									}

								if (endmultiline)
								{
									PyObject* pyRet;
									pyRet = PyRun_String(command.c_str(),
										Py_single_input, globals, globals);
									if (PyErr_Occurred()) PyErr_Print();
									Py_XDECREF(pyRet);

									indent.clear();
									command.clear();
									multiline = FALSE;
								}
								else
								{
									command.append(code);
									if (code[size-3] == ':')
										indent.append("\t");
								}
							}

							free(code);
							PromptPy(indent.c_str(), indent.size());
						}
						else
							sciINEND++;
						break;
					case SCN_UPDATEUI:
						/*if ( SendSci(SCI_GETCURRENTPOS, 0, 0) < sciIN )
							SendSci(SCI_GOTOPOS, sciINEND, 0);*/
					break;
				}
			}
		}
		break;
        case WM_COMMAND:
            switch (LOWORD(wParam))
            {
				case IDCANCEL:
				break;
            }
		break;
		//case WM_MOVE:
		case WM_SIZE:
			GetClientRect(execData.hConsole, &execData.rcConsole);
			SetWindowPos(execData.hConsoleScintilla, NULL, 0, 0,
			execData.rcConsole.right, execData.rcConsole.bottom, SWP_NOZORDER);
		break;
    }
    return FALSE;
}
Beispiel #28
0
	//• --------------------------------------------------------------------------
	//•	Return the number of replaces that took place.
	//•	eg find "^foo([a-z]+)" against "foobar woobar" using substitute "\1 is bar" ==> "bar is bar"
	size_t Regex::replace(const string &pattern,const string &substitute,string &scope,bool do_all) {
		size_t count = 0;
		if ( ! scope.empty() ) {
			int* ov = nullptr;		// size must be a multiple of 3.
			int ovc = 90;   	// size of ovector
			ov = new int[ovc];
			memset((int *) ov, 0, sizeof(ov));
			size_t lastend = string::npos;
			string basis = scope;
			size_t start = 0;
			size_t base_len = basis.length();
			//			size_t sub_len = substitute.length();
			scope.clear();		
			while (start <= base_len) {
				size_t matches = matcher(pattern, basis, (int)start, ov, ovc);
				if (matches <= 0) {
					if (start == 0) scope=basis; //nothing changed at all.
					break;	//we are finished - either with nothing, or all done.
				}
				size_t matchstart = ov[0], matchend = ov[1];
				if (matchstart == matchend && matchstart == lastend) {
					matchend = start + 1;
					if (start+1 < base_len && basis[start] == '\r' && basis[start+1] == '\n' ) {
						matchend++;
					}
					while (matchend < base_len && (basis[matchend] & 0xc0) == 0x80) { 
						matchend++; 
					}
					if (matchend <= base_len) { 
						scope.append(basis, start, matchend - start);
					}
					start = matchend;
				} else {
					enum {u,U,l,L,E,n} transform = n;
					scope.append(basis, start, matchstart - start);
					size_t o = 0, s = 0 ;
					do {
						s = substitute.find('\\',o);
						string newbit = substitute.substr(o,s-o);
						if (! newbit.empty() ) {
							switch(transform) {
								case n: break;
								case u: newbit[0] = std::toupper(newbit[0]);transform=n; break;
								case U: String::toupper(newbit); break;
								case l: newbit[0] = std::tolower(newbit[0]);transform=n; break;
								case L: String::tolower(newbit); break;
								case E: transform=n; break;
							}
							scope.append(newbit);
						}
						if ( s != string::npos) {
							o = s+2;
							int c = substitute[s+1];
							if ( isdigit(c) ) {
								int sn = (c - '0');
								int st = ov[2 * sn];
								if (st >= 0) {
									string newxbit;
									const char *bb = basis.c_str() + st;
									int be = ov[2 * sn + 1];
									if (be > 0 ) { 
										newxbit.append(bb, be - st);
									}									
									if (! newxbit.empty() ) {
										switch(transform) {
											case n: break;
											case u: newxbit[0] = std::toupper(newxbit[0]);transform=n; break;
											case U: String::toupper(newxbit); break;
											case l: newxbit[0] = std::tolower(newxbit[0]);transform=n; break;
											case L: String::tolower(newxbit); break;
											case E: transform=n; break;
										}
										scope.append(newxbit);
									}
								}
							} else if (c == '\\') {
								scope.push_back('\\');
							} else { 
								/* maybe it's a case modifier. 
								 \u Make the next character uppercase
								 \U Make all following characters uppercase until reaching another case specifier (\u, \L, \l ) or \E
								 \l Make the next character lowercase
								 \L Make all following characters lowercase until reaching another case specifier (\u, \U, \l ) or \E
								 \E End case transformation opened by \U or \L
								 */
								switch (c) {
									case 'u': transform=u; break;
									case 'U': transform=U; break;
									case 'l': transform=l; break;
									case 'L': transform=L; break;
									case 'E': transform=E; break;
									default: break;
								}
							}
						}
					} while ( s != string::npos );
					start = matchend;
					lastend = matchend;
					count++;
				}
				count++;
				if (! do_all) {
					break;
				}
			}
			if (count != 0 && start < base_len) {
				scope.append(basis, start, base_len - start);
			}
			delete [] ov;
		}
		return count;
	}
Beispiel #29
0
EnvelopeProcessor::ErrorCode EnvelopeProcessor::processPoints(char* envState, string &newState, double dStartPos, double dEndPos, double dValMin, double dValMax, EnvModType envModType, double dStrength, double dOffset)
{
	//if(!envelope)
	//	return eERRORCODE_NOENVELOPE;

	if(dStartPos==dEndPos)
		return eERRORCODE_NULLTIMESELECTION;
	double dLength = dEndPos-dStartPos;

	double dEnvOffset = 0.5*(dValMin+dValMax);
	double dEnvMagnitude = 0.5*(dValMax-dValMin);

	//char* envState = GetSetObjectState(envelope, "");
	if(!envState)
		return eERRORCODE_NOOBJSTATE;

	//string newState;
	newState.clear();
	char cPtValue[128];

	double position, value;
	int iTmp;
	char* token = strtok(envState, "\n");

	while(token != NULL)
	{
		// Position, value, shape
		if(sscanf(token, "PT %lf %lf %d\n", &position, &value, &iTmp) == 3)
		{
			if(position>=dEndPos)
				break;
			if(position>dStartPos)
			{
				stringstream currentLine;
				currentLine << token;
				std::vector<string> lineTokens;
				while(!currentLine.eof())
				{
					string str;
					getline(currentLine, str, ' ');
					lineTokens.push_back(str);
				}

				string newLine;
				int linePos = 0;
				for(vector<string>::const_iterator it = lineTokens.begin(); it !=lineTokens.end(); ++it)
				{
					if(linePos == 2)
					{
						double dEnvNormValue = (value-dEnvOffset)/dEnvMagnitude;
						double dCarrier = 1.0;
						switch(envModType)
						{
							case eENVMOD_FADEIN :
								dCarrier = (position-dStartPos)/dLength;
								dCarrier = pow(dCarrier, dStrength);
								//dCarrier = EnvSignalProcessorFade((position-dStartPos), (dEndPos-dStartPos), true);
								dEnvNormValue = dCarrier*(dEnvNormValue - dOffset) + dOffset;
							break;
							case eENVMOD_FADEOUT :
								dCarrier = (dEndPos-position)/dLength;
								dCarrier = pow(dCarrier, dStrength);
								//dCarrier = EnvSignalProcessorFade((position-dStartPos), (dEndPos-dStartPos), false);
								dEnvNormValue = dCarrier*(dEnvNormValue - dOffset) + dOffset;
							break;
							case eENVMOD_AMPLIFY :
								dEnvNormValue = dStrength*(dEnvNormValue + dOffset);
							break;
						}

						value = dEnvMagnitude*dEnvNormValue + dEnvOffset;
						if(value < dValMin)
							value = dValMin;
						if(value > dValMax)
							value = dValMax;

						sprintf(cPtValue, "%lf", value);
						newLine.append(cPtValue);
					}

					else
						newLine.append(*it);

					newLine.append(" ");
					linePos++;
				}
				newState.append(newLine);
				newState.append("\n");

				token = strtok(NULL, "\n");
				continue;
			}
		}

		if(!strcmp(token, ">"))
			break;

		newState.append(token);
		newState.append("\n");
		token = strtok(NULL, "\n");
	}

	newState.append(token);
	newState.append("\n");
	token = strtok(NULL, "\n");
	while(token != NULL)
	{
		newState.append(token);
		newState.append("\n");
		token = strtok(NULL, "\n");
	}

//	FreeHeapPtr(envState);
//
//	if(GetSetObjectState(envelope, newState.c_str()))
//		return eERRORCODE_UNKNOWN;
//Undo_OnStateChangeEx("Envelope Processor", UNDO_STATE_ALL, -1);

	return eERRORCODE_OK;
}
Beispiel #30
0
int GoogleVoice::CheckSMS(string &results, string number, string keyword, bool delete_sms)
{
	if(!hcurl) {cout << "hcurl is NULL.  Did you forget to call Init()?\n"; return -1;}
	if(Login()) return -1;

    results = "";
	
    curl_easy_setopt(hcurl, CURLOPT_URL, "https://www.google.com/voice/inbox/recent/unread");
    //Doesn't need any post information since it's getting the XML file (focus on unread as it saves a ton of memory/time)

	curlbuf.clear(); cr=curl_easy_perform(hcurl);
	if(cr!=CURLE_OK) {cout << "curl() error on getting sms: " << errorbuf << endl; return -3;}
	
	if(debug&2) cout << "\nSendSMS curlbuf: [" << curlbuf << "]\n";
    string orig = curlbuf;

	regex rexp("\"unread\":(\\d+)"); cmatch m;
	if(regex_search(curlbuf.c_str(), m, rexp)) {
        string t=m[1];
        int num_unread = atoi(t.c_str());
	    //cout << num_unread << "\n" << curlbuf.c_str() << "\n";
        if(num_unread == 0) {
            return 0;
        } else {
            string msg_id;
            string reg_check="\"id\":\"([a-z0-9]+)\",";
            if(number != "") {
                reg_check += "\"phoneNumber\":\"\\+";
                reg_check += number;
                reg_check += "\"";
            }
            regex rexp3(reg_check); cmatch q;
	        if(regex_search(orig.c_str(), q, rexp3)) {
                msg_id=q[1];
                //cout << msg_id.c_str() << "\n";
            } else {
                //cout << "Couldn't read msg_id.\n"; 
                return -1;
            }
            //printf("First check passed!\n");
            //reg_check = number;
            string name = "";
            if(number == "") {
                reg_check ="class=\"gc-message-sms-from\">(.+?)</span>";
                regex rexp2(reg_check); cmatch n;
                string::const_iterator  begin = curlbuf.begin(), end = curlbuf.end();
                smatch  p;
                while(regex_search(begin, end, p, rexp2)) {
                    smatch::value_type  r = p[1];
                    begin = r.second;
                    string t2 = p[1];
                    name = t2;
                }
            }
            reg_check ="class=\"gc-message-sms-text\">";
            if(keyword != "") {
                reg_check+=keyword;
                reg_check+=" ";
            }
            reg_check+="(.+?)</span>";
            regex rexp2(reg_check); cmatch n;
            //regex rexp2("\"gc-message-sms-text\">([\\/ / /|/.\"><A-Za-z0-9/-]+)<\\/span>"); cmatch n;
            string::const_iterator  begin = curlbuf.begin(), end = curlbuf.end();
            smatch  p;
            while(regex_search(begin, end, p, rexp2)) {
                smatch::value_type  r = p[1];
                begin = r.second;
                string t2 = p[1];
                //results += t2;
                //results += "\n";
                results = t2;
            }
            if(name != "")
                results = name + results;
            if(results != "") {
                //printf("Second check passed!\n");
                MarkAsRead(msg_id);
                reg_check = "gc-message-sms-text(.+?)phoneNumber";
                regex rexpPhony(reg_check); cmatch f;
                if(regex_search(orig.c_str(), f, rexpPhony)) {
                    //someone is trying to spoof me and this is invalid
                    SendSMS(number,string("Spoof attack!"));
                    //BlockSMS(msg_id);
                    //DeleteSMS(msg_id);
                    results.clear();
                    //By exiting here, they will never be able to spoof the phoneNumber query
                    return -4;
                } else if(delete_sms)
                    DeleteSMS(msg_id);
                //printf("Third check passed!\n");
            }
        }
        return num_unread;
    } else {cout << "Something went wrong.  Enable debugging.\n"; return -1;}
	
	return 0;

}