Esempio n. 1
0
void UBGraphicsRuler::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    if (!mResizing && !mRotating)
    {
		QGraphicsItem::mouseMoveEvent(event);
    }
    else
    {
        if (mResizing)
        {
			QPointF delta = event->pos() - event->lastPos();
			if (rect().width() + delta.x() < sMinLength)
				delta.setX(sMinLength - rect().width());

            if (rect().width() + delta.x() > sMaxLength)
                delta.setX(sMaxLength - rect().width());

			setRect(QRectF(rect().topLeft(), QSizeF(rect().width() + delta.x(), rect().height())));
        }
        else
        {
            QLineF currentLine(rotationCenter(), event->pos());
            QLineF lastLine(rotationCenter(), event->lastPos());
            rotateAroundCenter(currentLine.angleTo(lastLine));
        }

        event->accept();
    }
}
Esempio n. 2
0
 /*! \brief
  * Returns the text for a line.
  *
  * \param[in] line  Zero-based line index.
  * \returns   Text for line \p line, or empty string if \p line has
  *     no text for this column.
  */
 std::string textForLine(int line) const
 {
     // The second conditional matches if there are no lines
     if (line < firstLine() || line > lastLine())
     {
         return std::string();
     }
     return lines_[line - firstLine()];
 }
Esempio n. 3
0
static void emitStory(const char* m)
{
    Story st;
    memset(&st, 0, sizeof(st));
    st.sub[0] = crewTable;
    st.subSize[0] = 100; // plenty
    st.sub[1] = opTable;
    st.subSize[1] = DIM(opTable);

    // emit on the message line
    lastLine();
    story(m, &st);    
}
Esempio n. 4
0
    vector<string> fullJustify(vector<string> &words, int L) {
        vector<string> result;
        if(L == 0) return vector<string>(1,"");
        if(words.size() == 0)
        {
            string lastLine(L, ' ');
            result.push_back(lastLine);
            return result;
        }

        helper(words, 0, L, result);
        return result;
    }
Esempio n. 5
0
void UBGraphicsCompass::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    if (UBDrawingController::drawingController ()->stylusTool() != UBStylusTool::Selector &&
        UBDrawingController::drawingController ()->stylusTool() != UBStylusTool::Play)
        return;

    if (!mResizing && !mRotating && !mDrawing)
    {
        QGraphicsRectItem::mouseMoveEvent(event);
        mDrewCenterCross = false;
    }
    else
    {
        if (mResizing)
        {
            QPointF delta = event->pos() - event->lastPos();
            if (rect().width() + delta.x() < sMinRadius)
                delta.setX(sMinRadius - rect().width());
            setRect(QRectF(rect().topLeft(), QSizeF(rect().width() + delta.x(), rect().height())));
        }
        else
        {
            QLineF currentLine(needlePosition(), event->pos());
            QLineF lastLine(needlePosition(), event->lastPos());
            qreal deltaAngle = currentLine.angleTo(lastLine);
            if (deltaAngle > 180)
                deltaAngle -= 360;
            else if (deltaAngle < -180)
                deltaAngle += 360;
            rotateAroundNeedle(deltaAngle);

            if (mDrawing)
            {
                mSpanAngleInDegrees += deltaAngle;
                if (mSpanAngleInDegrees >= 1080)
                    mSpanAngleInDegrees -= 360;
                else if (mSpanAngleInDegrees < -1080)
                    mSpanAngleInDegrees += 360;
                drawArc();
            }
        }
        event->accept();
    }
}
Esempio n. 6
0
PassOwnPtr<FunctionCodeBlock> FunctionExecutable::produceCodeBlockFor(JSScope* scope, CodeSpecializationKind specializationKind, JSObject*& exception)
{
    if (!!codeBlockFor(specializationKind))
        return adoptPtr(new FunctionCodeBlock(CodeBlock::CopyParsedBlock, *codeBlockFor(specializationKind)));

    JSGlobalData* globalData = scope->globalData();
    JSGlobalObject* globalObject = scope->globalObject();
    ParserError error;
    DebuggerMode debuggerMode = globalObject->hasDebugger() ? DebuggerOn : DebuggerOff;
    ProfilerMode profilerMode = globalObject->hasProfiler() ? ProfilerOn : ProfilerOff;
    UnlinkedFunctionCodeBlock* unlinkedCodeBlock = m_unlinkedExecutable->codeBlockFor(*globalData, m_source, specializationKind, debuggerMode, profilerMode, error);
    recordParse(m_unlinkedExecutable->features(), m_unlinkedExecutable->hasCapturedVariables(), lineNo(), lastLine());

    if (!unlinkedCodeBlock) {
        exception = error.toErrorObject(globalObject, m_source);
        return nullptr;
    }

    OwnPtr<FunctionCodeBlock> result = adoptPtr(new FunctionCodeBlock(this, unlinkedCodeBlock, globalObject, source().provider(), source().startOffset()));
    result->copyPostParseDataFrom(codeBlockFor(specializationKind).get());
    return result.release();
}
Esempio n. 7
0
void editfile( struct options *options, list_ref list ){
   char stdinline[1024];
   char *operand = NULL;
   int stdincount = 0;
   int lineCount = 0;
   char *linepos = NULL;
   for(;;){
      if(!options->s_opt_silent)
		 printf("%s: ", progname); 
	  linepos = fgets( stdinline, sizeof stdinline, stdin );
      if( linepos == NULL ) break;
	  if(options->e_opt_echo && !options->s_opt_silent)
	     printf("%s",stdinline);
      linepos = strchr( stdinline, '\n' );
      if( linepos == NULL || stdinline[0] == '\0' ){
         badline( stdincount, stdinline );
      }else{
         *linepos = '\0';
		 operand=stdinline+1;
         switch( stdinline[0] ){
            case '$':
            	if(stdinline[1] != '\0') {
					badline(stdincount, stdinline);
					break;
				}
            	lastLine(list, options);
            	break;
            case '*':
            	if(stdinline[1] != '\0') {
					badline(stdincount, stdinline);
					break;
				}
            	printAll(list, options); 
            	break;
            case '.': 
            	if(stdinline[1] != '\0') {
					badline(stdincount, stdinline);
					break;
				}
            	printCurr(list, options);
            	break;
            case '0':
            	if(stdinline[1] != '\0') {
					badline(stdincount, stdinline);
					break;
				}
            	firstLine(list, options);
            	break;
            case '<': 
            	if(stdinline[1] != '\0') {
					badline(stdincount, stdinline);
					break;
				}
            	prevLine(list, options);
            	break;
            case '>': 
            	if(stdinline[1] != '\0') {
					badline(stdincount, stdinline);
					break;
				}
            	nextLine(list, options);
            	break;
            case '@': 
            	if(stdinline[1] != '\0') {
					badline(stdincount, stdinline);
					break;
				}
            	debugdump_list( list );
            	break;
            case 'a': 
            	insertAfter(list, operand, options);
            	break;
            case 'd': 
            	if(stdinline[1] != '\0') {
					badline(stdincount, stdinline);
					break;
				}
            	deleteLine(list, options);
            	break;
            case 'i': 
            	insertBefore(list, operand, options); 
            	break;
            case 'r':
				lineCount = readFile(list, operand, options); 
            	if(lineCount>=0 && !options->s_opt_silent)
					printf("%s: %d lines read.\n", progname, lineCount);
				break;
            case 'w': 
            	lineCount = writeFile(list, operand, options); 
            	if(lineCount>=0 && !options->s_opt_silent)
					printf("%s: %d lines written to %s\n", progname, lineCount, operand);
				break;
            default :
            	badline( stdincount, stdinline );
         };
      };
      ++stdincount;
   };
   if(!options->s_opt_silent)
	  printf("\n");
}
Esempio n. 8
0
QGestureRecognizer::Result QPinchGestureRecognizer::recognize(QGesture *state,
                                                              QObject *,
                                                              QEvent *event)
{
    QPinchGesture *q = static_cast<QPinchGesture *>(state);
    QPinchGesturePrivate *d = q->d_func();

    const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);

    QGestureRecognizer::Result result;

    switch (event->type()) {
    case QEvent::TouchBegin: {
        result = QGestureRecognizer::MayBeGesture;
        break;
    }
    case QEvent::TouchEnd: {
        if (q->state() != Qt::NoGesture) {
            result = QGestureRecognizer::FinishGesture;
        } else {
            result = QGestureRecognizer::CancelGesture;
        }
        break;
    }
    case QEvent::TouchUpdate: {
        d->changeFlags = 0;
        if (ev->touchPoints().size() == 2) {
            QTouchEvent::TouchPoint p1 = ev->touchPoints().at(0);
            QTouchEvent::TouchPoint p2 = ev->touchPoints().at(1);

            d->hotSpot = p1.screenPos();
            d->isHotSpotSet = true;

            QPointF centerPoint = (p1.screenPos() + p2.screenPos()) / 2.0;
            if (d->isNewSequence) {
                d->startPosition[0] = p1.screenPos();
                d->startPosition[1] = p2.screenPos();
                d->lastCenterPoint = centerPoint;
            } else {
                d->lastCenterPoint = d->centerPoint;
            }
            d->centerPoint = centerPoint;

            d->changeFlags |= QPinchGesture::CenterPointChanged;

            if (d->isNewSequence) {
                d->scaleFactor = 1.0;
                d->lastScaleFactor = 1.0;
            } else {
                d->lastScaleFactor = d->scaleFactor;
                QLineF line(p1.screenPos(), p2.screenPos());
                QLineF lastLine(p1.lastScreenPos(),  p2.lastScreenPos());
                d->scaleFactor = line.length() / lastLine.length();
            }
            d->totalScaleFactor = d->totalScaleFactor * d->scaleFactor;
            d->changeFlags |= QPinchGesture::ScaleFactorChanged;

            qreal angle = QLineF(p1.screenPos(), p2.screenPos()).angle();
            if (angle > 180)
                angle -= 360;
            qreal startAngle = QLineF(p1.startScreenPos(), p2.startScreenPos()).angle();
            if (startAngle > 180)
                startAngle -= 360;
            const qreal rotationAngle = startAngle - angle;
            if (d->isNewSequence)
                d->lastRotationAngle = 0.0;
            else
                d->lastRotationAngle = d->rotationAngle;
            d->rotationAngle = rotationAngle;
            d->totalRotationAngle += d->rotationAngle - d->lastRotationAngle;
            d->changeFlags |= QPinchGesture::RotationAngleChanged;

            d->totalChangeFlags |= d->changeFlags;
            d->isNewSequence = false;
            result = QGestureRecognizer::TriggerGesture;
        } else {
            d->isNewSequence = true;
            if (q->state() == Qt::NoGesture)
                result = QGestureRecognizer::Ignore;
            else
                result = QGestureRecognizer::FinishGesture;
        }
        break;
    }
    case QEvent::MouseButtonPress:
    case QEvent::MouseMove:
    case QEvent::MouseButtonRelease:
        result = QGestureRecognizer::Ignore;
        break;
    default:
        result = QGestureRecognizer::Ignore;
        break;
    }
    return result;
}
Esempio n. 9
0
RefPtr<CodeBlock> ScriptExecutable::newCodeBlockFor(
    CodeSpecializationKind kind, JSFunction* function, JSScope* scope, JSObject*& exception)
{
    VM* vm = scope->vm();

    ASSERT(vm->heap.isDeferred());
    ASSERT(startColumn() != UINT_MAX);
    ASSERT(endColumn() != UINT_MAX);

    if (classInfo() == EvalExecutable::info()) {
        EvalExecutable* executable = jsCast<EvalExecutable*>(this);
        RELEASE_ASSERT(kind == CodeForCall);
        RELEASE_ASSERT(!executable->m_evalCodeBlock);
        RELEASE_ASSERT(!function);
        return adoptRef(new EvalCodeBlock(
            executable, executable->m_unlinkedEvalCodeBlock.get(), scope,
            executable->source().provider()));
    }
    
    if (classInfo() == ProgramExecutable::info()) {
        ProgramExecutable* executable = jsCast<ProgramExecutable*>(this);
        RELEASE_ASSERT(kind == CodeForCall);
        RELEASE_ASSERT(!executable->m_programCodeBlock);
        RELEASE_ASSERT(!function);
        return adoptRef(new ProgramCodeBlock(
            executable, executable->m_unlinkedProgramCodeBlock.get(), scope,
            executable->source().provider(), executable->source().startColumn()));
    }
    
    RELEASE_ASSERT(classInfo() == FunctionExecutable::info());
    RELEASE_ASSERT(function);
    FunctionExecutable* executable = jsCast<FunctionExecutable*>(this);
    RELEASE_ASSERT(!executable->codeBlockFor(kind));
    JSGlobalObject* globalObject = scope->globalObject();
    ParserError error;
    DebuggerMode debuggerMode = globalObject->hasDebugger() ? DebuggerOn : DebuggerOff;
    ProfilerMode profilerMode = globalObject->hasProfiler() ? ProfilerOn : ProfilerOff;
    UnlinkedFunctionCodeBlock* unlinkedCodeBlock =
    executable->m_unlinkedExecutable->codeBlockFor(*vm, executable->m_source, kind, debuggerMode, profilerMode, error, executable->isArrowFunction());
    recordParse(executable->m_unlinkedExecutable->features(), executable->m_unlinkedExecutable->hasCapturedVariables(), firstLine(), lastLine(), startColumn(), endColumn()); 
    if (!unlinkedCodeBlock) {
        exception = vm->throwException(
            globalObject->globalExec(),
            error.toErrorObject(globalObject, executable->m_source));
        return nullptr;
    }

    SourceProvider* provider = executable->source().provider();
    unsigned sourceOffset = executable->source().startOffset();
    unsigned startColumn = executable->source().startColumn();

    return adoptRef(new FunctionCodeBlock(
        executable, unlinkedCodeBlock, scope, provider, sourceOffset, startColumn));
}
Esempio n. 10
0
bool wxTextFile::OnRead(const wxMBConv& conv)
{
    // file should be opened
    wxASSERT_MSG( m_file.IsOpened(), wxT("can't read closed file") );

    // read the entire file in memory: this is not the most efficient thing to
    // do it but there is no good way to avoid it in Unicode build because if
    // we read the file block by block we can't convert each block to Unicode
    // separately (the last multibyte char in the block might be only partially
    // read and so the conversion would fail) and, as the file contents is kept
    // in memory by wxTextFile anyhow, it shouldn't be a big problem to read
    // the file entirely
    size_t bufSize = 0;

    // number of bytes to (try to) read from disk at once
    static const size_t BLOCK_SIZE = 4096;

    wxCharBuffer buf;

    // first determine if the file is seekable or not and so whether we can
    // determine its length in advance
    wxFileOffset fileLength;
    {
        wxLogNull logNull;
        fileLength = m_file.Length();
    }

    // some non-seekable files under /proc under Linux pretend that they're
    // seekable but always return 0; others do return an error
    const bool seekable = fileLength != wxInvalidOffset && fileLength != 0;
    if ( seekable )
    {
        // we know the required length, so set the buffer size in advance
        bufSize = fileLength;
        if ( !buf.extend(bufSize) )
            return false;

        // if the file is seekable, also check that we're at its beginning
        wxASSERT_MSG( m_file.Tell() == 0, wxT("should be at start of file") );

        char *dst = buf.data();
        for ( size_t nRemaining = bufSize; nRemaining > 0; )
        {
            size_t nToRead = BLOCK_SIZE;

            // the file size could have changed, avoid overflowing the buffer
            // even if it did
            if ( nToRead > nRemaining )
                nToRead = nRemaining;

            ssize_t nRead = m_file.Read(dst, nToRead);

            if ( nRead == wxInvalidOffset )
            {
                // read error (error message already given in wxFile::Read)
                return false;
            }

            if ( nRead == 0 )
            {
                // this file can't be empty because we checked for this above
                // so this must be the end of file
                break;
            }

            dst += nRead;
            nRemaining -= nRead;
        }

        wxASSERT_MSG( dst - buf.data() == (wxFileOffset)bufSize,
                      wxT("logic error") );
    }
    else // file is not seekable
    {
        char block[BLOCK_SIZE];
        for ( ;; )
        {
            ssize_t nRead = m_file.Read(block, WXSIZEOF(block));

            if ( nRead == wxInvalidOffset )
            {
                // read error (error message already given in wxFile::Read)
                return false;
            }

            if ( nRead == 0 )
            {
                // if no bytes have been read, presumably this is a
                // valid-but-empty file
                if ( bufSize == 0 )
                    return true;

                // otherwise we've finished reading the file
                break;
            }

            // extend the buffer for new data
            if ( !buf.extend(bufSize + nRead) )
                return false;

            // and append it to the buffer
            memcpy(buf.data() + bufSize, block, nRead);
            bufSize += nRead;
        }
    }

    const wxString str(buf, conv, bufSize);

    // there's no risk of this happening in ANSI build
#if wxUSE_UNICODE
    if ( bufSize > 4 && str.empty() )
    {
        wxLogError(_("Failed to convert file \"%s\" to Unicode."), GetName());
        return false;
    }
#endif // wxUSE_UNICODE

    // we don't need this memory any more
    buf.reset();


    // now break the buffer in lines

    // the beginning of the current line, changes inside the loop
    wxString::const_iterator lineStart = str.begin();
    const wxString::const_iterator end = str.end();
    for ( wxString::const_iterator p = lineStart; p != end; p++ )
    {
        const wxChar ch = *p;
        if ( ch == '\r' || ch == '\n' )
        {
            // Determine the kind of line ending this is.
            wxTextFileType lineType = wxTextFileType_None;
            if ( ch == '\r' )
            {
                wxString::const_iterator next = p + 1;
                if ( next != end && *next == '\n' )
                    lineType = wxTextFileType_Dos;
                else
                    lineType = wxTextFileType_Mac;
            }
            else // ch == '\n'
            {
                lineType = wxTextFileType_Unix;
            }

            AddLine(wxString(lineStart, p), lineType);

            // DOS EOL is the only one consisting of two chars, not one.
            if ( lineType == wxTextFileType_Dos )
                p++;

            lineStart = p + 1;
        }
    }

    // anything in the last line?
    if ( lineStart != end )
    {
        // Add the last line; notice that it is certainly not terminated with a
        // newline, otherwise it would be handled above.
        wxString lastLine(lineStart, end);
        AddLine(lastLine, wxTextFileType_None);
    }

    return true;
}
void UBGraphicsTriangle::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
 
    if (!mResizing1 && !mResizing2 && !mRotating)
    {
        QGraphicsItem::mouseMoveEvent(event);
    }
    else
    {
        QPoint currPos = sceneTransform().inverted().map(event->screenPos());

        if (mResizing1)
        {
            if (mOrientation == TopLeft || mOrientation == BottomLeft)
            {
                int deltaX = currPos.x() - lastPos.x();
                if (lastRect.width() + deltaX < sMinWidth)
                    deltaX = sMinWidth - lastRect.width();

                setRect(QRectF(lastRect.left(), lastRect.top(),
                    lastRect.width() + deltaX, lastRect.height()), mOrientation);
            }
            else
            {
                int deltaX = lastPos.x() - currPos.x();
                if (lastRect.width() + deltaX < sMinWidth)
                    deltaX = sMinWidth - lastRect.width();

                setRect(QRectF(lastRect.left() - deltaX, lastRect.top(),
                    lastRect.width() + deltaX, lastRect.height()), mOrientation);
            }
        }

        //-----------------------------------------------//

        if (mResizing2)
        {
            if (mOrientation == BottomRight || mOrientation == BottomLeft)
            {
                int deltaY = lastPos.y() - currPos.y();
                if (lastRect.height() + deltaY < sMinHeight)
                    deltaY = sMinHeight - lastRect.height();

                setRect(QRectF(lastRect.left(), lastRect.top() - deltaY,
                        lastRect.width(), lastRect.height() + deltaY), mOrientation);
            }
            else
            {
                int deltaY = currPos.y() - lastPos.y();
                if (lastRect.height() + deltaY < sMinHeight)
                    deltaY = sMinHeight - lastRect.height();

                setRect(QRectF(lastRect.left(), lastRect.top(),
                        lastRect.width(), lastRect.height() + deltaY), mOrientation);
            }

        }

        //-----------------------------------------------//

        if (mRotating)
        {
            QLineF currentLine(rotationCenter(), event->pos());
            QLineF lastLine(rotationCenter(), event->lastPos());
            rotateAroundCenter(currentLine.angleTo(lastLine));
        }

        //-----------------------------------------------//

        event->accept();
    }
}
Esempio n. 12
0
int32_t ScriptEngineClient::start(std::string command)
{
	try
	{
		_socketPath = GD::runDir + "homegearSE.sock";
		for(int32_t i = 0; i < 2; i++)
		{
			_fileDescriptor = GD::bl->fileDescriptorManager.add(socket(AF_LOCAL, SOCK_STREAM, 0));
			if(!_fileDescriptor || _fileDescriptor->descriptor == -1)
			{
				GD::out.printError("Could not create socket.");
				return 1;
			}

			if(GD::bl->debugLevel >= 4 && i == 0) std::cout << "Info: Trying to connect..." << std::endl;
			sockaddr_un remoteAddress;
			remoteAddress.sun_family = AF_LOCAL;
			//104 is the size on BSD systems - slightly smaller than in Linux
			if(_socketPath.length() > 104)
			{
				//Check for buffer overflow
				GD::out.printCritical("Critical: Socket path is too long.");
				return 2;
			}
			strncpy(remoteAddress.sun_path, _socketPath.c_str(), 104);
			remoteAddress.sun_path[103] = 0; //Just to make sure it is null terminated.
			if(connect(_fileDescriptor->descriptor, (struct sockaddr*)&remoteAddress, strlen(remoteAddress.sun_path) + 1 + sizeof(remoteAddress.sun_family)) == -1)
			{
				GD::bl->fileDescriptorManager.shutdown(_fileDescriptor);
				if(i == 0)
				{
					GD::out.printDebug("Debug: Socket closed. Trying again...");
					//When socket was not properly closed, we sometimes need to reconnect
					std::this_thread::sleep_for(std::chrono::milliseconds(2000));
					continue;
				}
				else
				{
					GD::out.printError("Could not connect to socket. Error: " + std::string(strerror(errno)));
					return 3;
				}
			}
			else break;
		}
		if(GD::bl->debugLevel >= 4) std::cout << "Info: Connected." << std::endl;

		if(command.empty()) _pingThread = std::thread(&ScriptEngineClient::ping, this);

		rl_bind_key('\t', rl_abort); //no autocompletion

		std::string level = "";
		std::string lastCommand;
		std::string currentCommand;
		char* sendBuffer;
		char receiveBuffer[1025];
		int32_t bytes = 0;
		while(!command.empty() || (sendBuffer = readline((level + "> ").c_str())) != NULL)
		{
			if(command.empty())
			{
				if(_closed) break;
				bytes = strlen(sendBuffer);
				if(sendBuffer[0] == '\n' || sendBuffer[0] == 0) continue;
				if(strncmp(sendBuffer, "quit", 4) == 0 || strncmp(sendBuffer, "exit", 4) == 0 || strncmp(sendBuffer, "moin", 4) == 0)
				{
					_closed = true;
					//If we close the socket, the socket file gets deleted. We don't want that
					//GD::bl->fileDescriptorManager.close(_fileDescriptor);
					free(sendBuffer);
					return 4;
				}
				_sendMutex.lock();
				if(_closed)
				{
					_sendMutex.unlock();
					break;
				}
				if(send(_fileDescriptor->descriptor, sendBuffer, bytes, MSG_NOSIGNAL) == -1)
				{
					_sendMutex.unlock();
					GD::out.printError("Error sending to socket.");
					//If we close the socket, the socket file gets deleted. We don't want that
					//GD::bl->fileDescriptorManager.close(_fileDescriptor);
					free(sendBuffer);
					return 5;
				}
				currentCommand = std::string(sendBuffer);
				if(currentCommand != lastCommand)
				{
					lastCommand = currentCommand;
					add_history(sendBuffer); //Sets sendBuffer to 0
				}
				else
				{
					free(sendBuffer);
					sendBuffer = 0;
				}
			}
			else
			{
				_sendMutex.lock();
				if(_closed)
				{
					_sendMutex.unlock();
					break;
				}
				if(send(_fileDescriptor->descriptor, command.c_str(), command.size(), MSG_NOSIGNAL) == -1)
				{
					_sendMutex.unlock();
					GD::out.printError("Error sending to socket.");
					return 6;
				}
			}

			while(true)
			{
				bytes = recv(_fileDescriptor->descriptor, receiveBuffer, 1024, 0);
				if(bytes > 0)
				{
					receiveBuffer[bytes] = 0;
					std::string response(receiveBuffer);
					if(response.size() > 15)
					{
						if(response.compare(7, 6, "family") == 0)
						{
							if((signed)response.find("unselected") != (signed)std::string::npos)
							{
								level = "";
							}
							else if((signed)response.find("selected") != (signed)std::string::npos)
							{
								level = "(Family)";
							}
						}
						else if(response.compare(0, 4, "Peer") == 0)
						{
							if((signed)response.find("unselected") != (signed)std::string::npos)
							{
								level = "(Family)";
							}
							else if((signed)response.find("selected") != (signed)std::string::npos)
							{
								level = "(Peer)";
							}
						}
						/*else if(response.compare(0, 6, "Device") == 0)
						{
							if((signed)response.find("unselected") != (signed)std::string::npos)
							{
								level = "(Family)";
							}
							else if((signed)response.find("selected") != (signed)std::string::npos)
							{
								level = "(Device)";
							}
						}*/
					}

					if(bytes < 1024 || (bytes == 1024 && receiveBuffer[bytes - 1] == 0))
					{
						if(!command.empty())
						{
							_sendMutex.unlock();

							// {{{ Get last line and check if it contains the exit code.
							if(response.size() > 2)
							{
								const char* pos = response.c_str() + response.size() - 2; // -2, because last line ends with new line

								while(pos > response.c_str())
								{
									if(*pos == '\n')
									{
										pos++;
										break;
									}
									pos--;
								}

								int32_t count = (response.c_str() + response.size()) - pos - 1;
								std::string lastLine(pos, count);
								if(lastLine.compare(0, 11, "Exit code: ") == 0 && lastLine.size() > 11)
								{
									count = pos - response.c_str();
									response = response.substr(0, count);
									std::cout << response;
									std::string exitCode = lastLine.substr(11);
									return BaseLib::Math::getNumber(exitCode);
								}
								else std::cout << response;
							}
							// }}}

							return 0;
						}
						else std::cout << response;
						break;
					}
					else std::cout << response;
				}
				else
				{
					_sendMutex.unlock();
					if(bytes < 0) std::cerr << "Error receiving data from socket." << std::endl;
					else std::cout << "Connection closed." << std::endl;
					//If we close the socket, the socket file gets deleted. We don't want that
					//GD::bl->fileDescriptorManager.close(_fileDescriptor);
					return 8;
				}
			}
			_sendMutex.unlock();
		}
	}
    catch(const std::exception& ex)
    {
    	GD::out.printError("Couldn't create socket file " + _socketPath + ": " + ex.what());;
    }
    catch(BaseLib::Exception& ex)
    {
    	GD::out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what());
    }
    catch(...)
    {
    	GD::out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__);
    }
    return 0;
}
Esempio n. 13
0
PassRefPtr<CodeBlock> ScriptExecutable::newCodeBlockFor(
    CodeSpecializationKind kind, JSFunction* function, JSScope** scope, JSObject*& exception)
{
    VM* vm = (*scope)->vm();

    ASSERT(vm->heap.isDeferred());
    ASSERT(startColumn() != UINT_MAX);
    ASSERT(endColumn() != UINT_MAX);

    if (classInfo() == EvalExecutable::info()) {
        EvalExecutable* executable = jsCast<EvalExecutable*>(this);
        RELEASE_ASSERT(kind == CodeForCall);
        RELEASE_ASSERT(!executable->m_evalCodeBlock);
        RELEASE_ASSERT(!function);
        return adoptRef(new EvalCodeBlock(
            executable, executable->m_unlinkedEvalCodeBlock.get(), *scope,
            executable->source().provider()));
    }
    
    if (classInfo() == ProgramExecutable::info()) {
        ProgramExecutable* executable = jsCast<ProgramExecutable*>(this);
        RELEASE_ASSERT(kind == CodeForCall);
        RELEASE_ASSERT(!executable->m_programCodeBlock);
        RELEASE_ASSERT(!function);
        return adoptRef(new ProgramCodeBlock(
            executable, executable->m_unlinkedProgramCodeBlock.get(), *scope,
            executable->source().provider(), executable->source().startColumn()));
    }
    
    RELEASE_ASSERT(classInfo() == FunctionExecutable::info());
    RELEASE_ASSERT(function);
    FunctionExecutable* executable = jsCast<FunctionExecutable*>(this);
    RELEASE_ASSERT(!executable->codeBlockFor(kind));
    JSGlobalObject* globalObject = (*scope)->globalObject();
    ParserError error;
    DebuggerMode debuggerMode = globalObject->hasDebugger() ? DebuggerOn : DebuggerOff;
    ProfilerMode profilerMode = globalObject->hasProfiler() ? ProfilerOn : ProfilerOff;
    UnlinkedFunctionCodeBlock* unlinkedCodeBlock =
        executable->m_unlinkedExecutable->codeBlockFor(
            *vm, executable->m_source, kind, debuggerMode, profilerMode, error);
    recordParse(executable->m_unlinkedExecutable->features(), executable->m_unlinkedExecutable->hasCapturedVariables(), lineNo(), lastLine(), startColumn(), endColumn()); 
    if (!unlinkedCodeBlock) {
        exception = vm->throwException(
            globalObject->globalExec(),
            error.toErrorObject(globalObject, executable->m_source));
        return 0;
    }

    // Parsing reveals whether our function uses features that require a separate function name object in the scope chain.
    // Be sure to add this scope before linking the bytecode because this scope will change the resolution depth of non-local variables.
    if (!executable->m_didParseForTheFirstTime) {
        executable->m_didParseForTheFirstTime = true;
        function->addNameScopeIfNeeded(*vm);
        *scope = function->scope();
    }
    
    SourceProvider* provider = executable->source().provider();
    unsigned sourceOffset = executable->source().startOffset();
    unsigned startColumn = executable->source().startColumn();

    return adoptRef(new FunctionCodeBlock(
        executable, unlinkedCodeBlock, *scope, provider, sourceOffset, startColumn));
}
Esempio n. 14
0
PassRefPtr<FunctionCodeBlock> FunctionExecutable::produceCodeBlockFor(JSScope* scope, CodeSpecializationKind specializationKind, JSObject*& exception)
{
    RefPtr<FunctionCodeBlock> alternative = codeBlockFor(specializationKind);
    
    if (!!alternative) {
        RefPtr<FunctionCodeBlock> result = adoptRef(new FunctionCodeBlock(CodeBlock::CopyParsedBlock, *codeBlockFor(specializationKind)));
        result->setAlternative(alternative);
        return result.release();
    }

    VM* vm = scope->vm();
    JSGlobalObject* globalObject = scope->globalObject();
    ParserError error;
    DebuggerMode debuggerMode = globalObject->hasDebugger() ? DebuggerOn : DebuggerOff;
    ProfilerMode profilerMode = globalObject->hasProfiler() ? ProfilerOn : ProfilerOff;
    UnlinkedFunctionCodeBlock* unlinkedCodeBlock = m_unlinkedExecutable->codeBlockFor(*vm, m_source, specializationKind, debuggerMode, profilerMode, error);
    recordParse(m_unlinkedExecutable->features(), m_unlinkedExecutable->hasCapturedVariables(), lineNo(), lastLine(), startColumn());

    if (!unlinkedCodeBlock) {
        exception = error.toErrorObject(globalObject, m_source);
        return 0;
    }

    SourceProvider* provider = source().provider();
    unsigned sourceOffset = source().startOffset();
    unsigned startColumn = source().startColumn();

    return adoptRef(new FunctionCodeBlock(this, unlinkedCodeBlock, scope, provider, sourceOffset, startColumn));
}
Esempio n. 15
0
int main(int argc, char **argv) {
  /* Initial number of changepoints */
  int nK0=1;
  
#ifdef FIXED
  FILE *pfp, *kfp, *Lfp;
  char *pfn="Probs.dat", *kfn="K.dat", *Lfn="Likelihood.dat";
  prefix=NULL;
#endif

#ifndef FIXED
  getArgs(argc, argv);
#else
  getFixedArgs(argc, argv);
#endif
  processData(dataFn);

  initialise();

#ifdef FIXED
  if(prefix) {
    pfn=addPrefix(pfn, prefix);
    kfn=addPrefix(kfn, prefix);
    Lfn=addPrefix(Lfn, prefix);
  }
  pfp=fopen(pfn,"w");
  kfp=fopen(kfn,"w");
  Lfp=fopen(Lfn,"w");

  setData(CDFdata, getNdata());
  setSample(sampleMixed);
  iterate(pfp, kfp, Lfp, /* dPriorNew */dPriorFixedChangepoints, dFixedLikelihood,p0,nProb, ip0, nK, seed, nIter);
#endif

#ifdef DEFAULT
    if(!restart) {

    iterateRJ(prefix, prefix, prefix, prefix,
	      sampleBirthDeath,
	      dPriorChangepoints,dLikelihood,
	      p0, nK0+1,1, nProb,
	      ip0, nK0,1, nK, seed,  nIter);
  }
  else {
  /* int k0[]={50000, 100000}; */
  /* nK0=2; */
  /* initialiseLocations(ip0, k0, CDFdata,getNdata()-1, */
  /* 		       p0, 2); */
  FILE *re_fp=fopen(re_K, "rb");
  char *buf=malloc(MAX_LEN+1);
  char *ll;
  int nReK=0, nReP=0;
  int i;
  
  int nums[NCHANGE+1];
  double dNums[NCHANGE+2];
  
  ll=lastLine(re_fp, buf, MAX_LEN);
  fclose(re_fp);
  
  nReK=str2ints(ll, nums);
  /* for(i=0; i<nReK; i++) { */
  /*   fprintf(OUT, "%d\t", nums[i]); */
  /* } */
  /* fprintf(OUT, "\nSuccessfully converted %d integers\n", nReK); */
  

  re_fp=fopen(re_P, "rb");
  ll=lastLine(re_fp, buf, MAX_LEN);
  free(buf);
  fclose(re_fp);
  
  nReP=str2doubles(ll, dNums);
  /* for(i=0; i<nReP; i++) { */
  /*   fprintf(OUT, "%f\t", dNums[i]); */
  /* } */
  /* fprintf(OUT, "\nSuccessfully converted %d doubles\n", nReP); */

  initialiseLocationsAndProbs(ip0, p0,
			      nums+1, dNums+1,
			      nReK-1);
  /* printIntParameters(OUT, ip0, nReK-1); */
  /* printParameters(OUT, p0, nReP-1); */
  /* exit(1); */

  iterateRJ(prefix, prefix, prefix, prefix,
	    sampleBirthDeath,
	    dPriorChangepoints,dLikelihood,
	    p0, nReP-1,1, nProb,
	    ip0, nReK-1,1, nK, seed,  nIter);
  }
#endif

#ifdef GEO
  iterateRJ(prefix, prefix, prefix, prefix,
	    sampleBirthDeath,
	    dPriorChangepointsGeo,dLikelihood,
	    p0, nK0+1,1, nProb,
	    ip0, nK0,1, nK, seed,  nIter);
#endif

#ifdef NEGATIVEBINK1
  iterateRJ(prefix, prefix, prefix, prefix,
	    sampleBirthDeath,
	    dPriorChangepointsNegativeBinK1,dLikelihood,
	    p0, nK0+1,1, nProb,
	    ip0, nK0,1, nK, seed,  nIter);
#endif
#ifdef NEGATIVEBINK2
  iterateRJ(prefix, prefix, prefix, prefix,
	    sampleBirthDeath,
	    dPriorChangepointsNegativeBinK2,dLikelihood,
	    p0, nK0+1,1, nProb,
	    ip0, nK0,1, nK, seed,  nIter);
#endif
#ifdef NJGEONEGATIVEBINK1
  iterateRJ(prefix, prefix, prefix, prefix,
	    sampleBirthDeath,
	    dPriorChangepoints_nJGeoNegativeBinK1,dLikelihood,
	    p0, nK0+1,1, nProb,
	    ip0, nK0,1, nK, seed,  nIter);
#endif
#ifdef NJGEONEGATIVEBINK2
  iterateRJ(prefix, prefix, prefix, prefix,
	    sampleBirthDeath,
	    dPriorChangepoints_nJGeoNegativeBinK2,dLikelihood,
	    p0, nK0+1,1, nProb,
	    ip0, nK0,1, nK, seed,  nIter);
#endif

  return 0;  
}
Esempio n. 16
0
void Debugger::handleControlKey(ControlKey ck)
{
	pthread_mutex_lock(&printingMutex);
	int heapLines = heapSize / wHeapBytes;
	int stackLines = stackMaxSize / wStackBytes;
	int codeWindowHeight = 20;

	if (ck == ckTab)
	{
		activeWindow = (DebuggerActiveWindow)((activeWindow + 1) % dawSize);
	}

	else if (ck == ckUp && activeWindow == dawCode)
	{
		wSelectedLineFollowsFlow = false;
		wSelectedLine --;
	}
	else if (ck == ckDown && activeWindow == dawCode)
	{
		wSelectedLineFollowsFlow = false;
		wSelectedLine ++;
	}
	else if (ck == ckPageUp && activeWindow == dawCode)
	{
		wSelectedLineFollowsFlow = false;
		wSelectedLine -= codeWindowHeight / 2;
	}
	else if (ck == ckPageDown && activeWindow == dawCode)
	{
		wSelectedLineFollowsFlow = false;
		wSelectedLine += codeWindowHeight / 2;
	}
	else if (ck == ckSpace && activeWindow == dawCode)
	{
		wSelectedLineFollowsFlow = true;
	}

	else if (ck == ckUp && activeWindow == dawHeap)
	{
		wHeapTopRow --;
	}
	else if (ck == ckDown && activeWindow == dawHeap)
	{
		wHeapTopRow ++;
	}
	else if (ck == ckUp && activeWindow == dawStack)
	{
		wStackTopRow --;
	}
	else if (ck == ckDown && activeWindow == dawStack)
	{
		wStackTopRow ++;
	}

	else if (ck == ckPageUp && activeWindow == dawHeap)
	{
		wHeapTopRow -= topSpace / 2;
	}
	else if (ck == ckPageDown && activeWindow == dawHeap)
	{
		wHeapTopRow += topSpace / 2;
	}
	else if (ck == ckPageUp && activeWindow == dawStack)
	{
		wStackTopRow -= topSpace / 2;
	}
	else if (ck == ckPageDown && activeWindow == dawStack)
	{
		wStackTopRow += topSpace / 2;
	}

	if (wSelectedLine < 0) wSelectedLine = 0;
	if (wSelectedLine > lastLine()) wSelectedLine = lastLine();

	if (wHeapTopRow < 0) wHeapTopRow = 0;
	if (wHeapTopRow > heapLines) wHeapTopRow = heapLines;

	if (wStackTopRow < 0) wStackTopRow = 0;
	if (wStackTopRow > stackLines) wStackTopRow = stackLines;

	pthread_mutex_unlock(&printingMutex);

	updateUI();
}