text:
Q: how to ignore lines when writing to a file how can I write to a file at the nth line (for example the 5th line) in c++?
here's my attempt:
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream  stream1("1.txt");
    string line ;
    ofstream stream2("2.txt");
    int lineNumber = 0;

    while(getline( stream1, line ) )
    {
        if (lineNumber == 5)
        {
         stream2 << "Input" << endl;
         lineNumber = 0;
        }

    lineNumber++;
    }

    stream1.close();
    stream2.close();    return 0;
}

in "1.txt", I have the word "Student" at the 4th line, now I want to ignore the above 4 lines and input the word "Input" at the 5th line (below the word "Student"). When I run the above code, the output file is blank. Any suggestion how to fix this? Thanks.

A: If I understand it right, all you want is a replica of 1.txt in 2.txt with just the specific line number replaced with your personal content.
In your case it seems, the word is "Input".
Well here is a code that I modified from your original one -
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream  stream1("1.txt");
    string line ;
    ofstream stream2("2.txt");
    int lineNumber = 0;
    int line_to_replace = 4; //This will replace 5th line

    while(getline( stream1, line ) )
    {
            if (lineNumber == line_to_replace)
            {
                    stream2 << "Input" << endl;
            }
            else
                    stream2 << line << endl;

            lineNumber++;
    }

    stream1.close();
    stream2.close();
    return 0;
}

Input File (1.txt) -

sdlfknas
sdfas
sdf
g
thtr
34t4
bfgndty
45y564
grtg

Output File (2.txt) -

sdlfknas
sdfas
sdf
g
Input
34t4
bfgndty
45y564
grtg

p.s. To learn and understand programming better, I would recommend not to use:
using namespace std;

A: When you're reading the 5th line, lineNumber equals 4 b/c you start your counting at 0.
Change if(lineNumber == 5)
to if(lineNumber == 4)  You also have an issue where you're setting lineNumber = 0 then immediately incrementing to 1, so you're only going to count 4 lines before outputting again.

A: I would create a function like this...
bool isBlank(string line) {
    if (!line.empty()) {
        for (auto x: line) {
            if (isalnum(x)) {
                return false;
            }
        }
    }
    return true;
}

It returns true if a string is empty or has no alphanumeric characters.
You can call this function right after the getline statement.
The isalnum function is specified in <cctype>

A: After working with your code I managed to get the output that you desired. Here is the updated version of your code.
#include <iostream>
#include <fstream>

int main() {
    std::ifstream stream1( "1.txt" );
    std::string line;
    std::ofstream stream2( "2.txt" );
    int lineNumber = 1;

    while ( getLine( stream1, line ) ) {
        if ( lineNumber == 5 ) {
            stream2 << "Input" << std::endl;

        } else {
            stream2 << std::endl;
            lineNumber++;
        }
    }

    stream1.close();
    stream2.close();

    return 0;
}

The one thing you have to make sure is that in your 1.txt that has the word student on the 4th line is that you must have at least 2 empty lines after this text in the file. A simple enter or carriage return will do! If you do not the while( getline() ) will go out of scope and it will not read the next line and the code block will never enter your if() statement when lineNumber == 5 and it will not print the text "Input" to your stream2 file stream object.
If your last line of text in your 1.txt file is the line with the string of text Student what happens here is it will add this line of text to your line string variable then the code will increment your lineNumber to equal 5. The next time you go into the while loop to call getline() it returns false because you are at the EOF since there are no more lines of text from the file to read in and this causes the while loop to break out of execution and it goes out of scope and the if( lineNumber == 5 ) never gets called because it is nested within the while loop's scope.

A: My first answer addressed the issue with your problem and getting the output to your text file appropriately. However as I mentioned about the while loop for reading in a line of text and using the same counter for both file streams is not very elegant. A more accurate way to do this which will also allow for debugging to be simplified would be to read in your full input file one line at a time and save each line into a string while storing your strings in a vector. This way you can parse each line of text that you need one at a time and you can easily traverse your vector to quickly find your line of text. You should also do checks to make sure your file exists and that it opens correctly.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>

int main() {
    std::string strTextFileIn( "1.txt" );
    std::ifstream in;
    std::string strLine;
    std::vector<std::string> vFileContents;

    // Open File Stream
    in.open( strTextFileIn.c_str(), std::ios_base::in );
    // Test To Make Sure It Opened Properly And That It Exists
    if ( !in.is_open() ) {
        std::cout << "Failed to open file, check to make sure file exists." << std::endl;
        return -1;
    } else {
        while ( !in.eof() ) {
            // Get Line Of Text And Save To String
            std::getline( in, strLine );
            // Push String Into Vector
            vFileContents.push_back( strLine );
        }
    }

    // Done With File Close File Stream
    if ( in.is_open() ) {
        in.close();
    }

    // Now That We Have Read In The File Contents And Have Saved Each Line Of Text To A String
    // And Stored It In Our Container (Vector) We Can Traverse Our Vector To Find Which String
    // Matches The Text We Are Looking For Retrive Its Indexed Value And Then Write To Our
    // Output File According To Where You Want The Text To Be Written
    unsigned index = 0;
    const std::string strLookup( "Student" );
    for ( unsigned int i = 0; i < vFileContents.size(); i++ ) {
        if ( vFileContents[i] == strLookup ) {
             // Strings Match We Have Our Indexed Value
            index = i;
        }
    }

    // We Want To Write Our Line Of Text 1 Line Past Our Index Value As You Have Stated.
    std::string strTextFileOut( "2.txt" );
    std::ofstream out;

    // Open Our File For Writting
    out.open( strTextFileOut.c_str(), std::ios_base::out );
    if ( !out.is_open() ) {
        std::cout << "Failed To open file.";
        vFileContents.clear();
        return -1;
    } else {
        for ( unsigned int i = 1; i <= index; i++ ) {
            out << std::endl; // Write Blank Lines
        }
        // The Text Or String You Want To Write To File
        out << "Input" << std::endl;
    }

    // Done With File Stream
    if ( in.is_open() ) {
        in.close();
    }

    // Clear Out Vector
    vFileContents.clear();

    return 0;
} // main

Now this can be simplified a bit more by creating a class hierarchy for working with various file stream object types so that you don't have to write this code to open, close, check validity, read in full file or by line over and over again everywhere you need it. This makes it modular. However this structure relies on a few other classes such as an ExceptionHandler class and a Logger class. Below is a small multi file application.
stdafx.h NOTE: Not all of these includes and defines will be used here, but this is coming from a larger project of mine and I'm stripping out only the classes that are needed here, but leaving my standard header as is. The only contents that I stripped out of this "stdafx.h" is anything that has to deal with OpenGL, OpenAL, Ogg - Vorbis, GLM Libraries & APIs
#ifndef STDAFX_H
#define STDAFX_H

#define VC_EXTRALEAN // Exclude Rarely Used Stuff Windows Headers - Windows Only

// Instead of Creating Another File That VS Makes For You "targetver.h"
// I Will Just Append Its Contents Here
#include <SDKDDKVer.h> // Windows Only
#include <Windows.h> // Windows Only
#include <process.h>

#include <tchar.h>
#include <conio.h>

#include <memory>
#include <string>
#include <numeric>
#include <vector>
#include <array>
#include <unordered_map>
#include <queue>

#include <iostream>
#include <sstream>
#include <iomanip>
#include <fstream>

#include "ExceptionHandler.h"

namespace pro {
enum ReturnCode {
    RETURN_OK = 0,
    RETURN_ERROR = 1,
};

extern const unsigned INVALID_UNSIGNED;
extern const unsigned INVALID_UNSIGNED_SHORT;

} // namespace pro

#endif // STDAFX_H

stdafx.cpp
#include "stdafx.h"

namespace pro {
    const unsigned INVALID_UNSIGNED       = static_cast<const unsigned>( -1 );
    const unsigned INVALID_UNSIGNED_SHORT = static_cast<const unsigned short>( -1 );
} // namespace pro

ExceptionHandler.h
#ifndef EXCEPTION_HANDLER_H
#define EXCEPTION_HANDLER_H

namespace pro {

class ExceptionHandler sealed {
private:
    std::string m_strMessage;

public:
    explicit ExceptionHandler( const std::string& strMessage, bool bSaveInLog = true );
    explicit ExceptionHandler( const std::ostringstream& strStreamMessage, bool bSavedInLog = true );
    // ~ExceptionHandler(); // Default Okay
    // ExeptionHandler( const ExceptionHandler& c ); // Default Copy Constructor Okay & Is Needed

    const std::string& getMessage() const;

private:
    ExceptionHandler& operator=( const ExceptionHandler& c ); // Not Implemented

}; // ExceptionHandler

} // namespace pro

#endif // EXCEPTION_HANDLER_H

ExceptionHandler.cpp
#include "stdafx.h"
#include "ExceptionHandler.h"
#include "Logger.h"

namespace pro {

ExceptionHandler::ExceptionHandler( const std::string& strMessage, bool bSaveInLog ) :
m_strMessage( strMessage ) {
    if ( bSavedInLog ) {
        Logger::log( m_strMessage, Logger::TYPE_ERROR );
    }
}

ExceptionHandler::ExceptionHandler( const std::ostringstream& strStreamMessage, bool bSaveInLog ) :
m_strMessage( strStreamMessage.str() ) {
    if ( bSaveInLog ) {
        Logger::log( m_strMessage, Logger::TYPE_ERROR );
    }
}

const std::string& ExceptionHandler::getMessage() const {
    return m_strMessage;
}

} // namespace pro

BlockThread.h -- Needed For Logger
#ifndef BLOCK_THREAD_H
#define BLOCK_THREAD_H

namespace pro {

class BlockThread sealed {
private:
    CRITICAL_SECTION* m_pCriticalSection;

public:
    explicit BlockThread( CRITICAL_SECTION& criticalSection );
    ~BlockThread();

private:
    BlockThread( const BlockThread& c ); // Not Implemented
    BlockThread& operator=( const BlockThread& c ); // Not Implemented

}; // BlockThread

} // namespace pro

#endif // BLOCK_THREAD_H

BlockThread.cpp
#include "stdafx.h"
#include "BlockThread.h"

namespace pro {

BlockThread::BlockThread( CRTICAL_SECTION& criticalSection ) {
    m_pCriticalSection = &criticalSection;
    EnterCriticalSection( m_pCriticalSection );
}

BlockThread::~BlockThread() {
    LeaveCriticalSection( m_pCriticalSection );
}

} // namespace pro

Logger is a Singleton since you will only want one instance of it while your application is running.
Singleton.h
#ifndef SINGLETON_H
#define SINGLETON_H

namespace pro {

class Singleton {
public:
    enum SingletonType {
        TYPE_LOGGER = 0, // Must Be First!
        // TYPE_SETTINGS,
        // TYPE_ENGINE,
    };

private:
    SingletonType m_eType;
public:
    virtual ~Singleton();

protected:
    explicit Singleton( SingletonType eType );

    void logMemoryAllocation( bool isAllocated ) const;

private:
    Singleton( const Singleton& c ); // Not Implemented
    Singleton& operator=( const Singleton& c ); // Not Implemented

}; // Singleton

} // namespace pro

#endif // SINGLETON_H

Singleton.cpp
#include "stdafx.h"
#include "Logger.h"
#include "Singleton.h"
//#include "Settings.h"

namespace pro {

struct SingletonInfo {
    const std::string strSingletonName;
    bool              isConstructed;

    SingletonInfo( const std::string& strSingletonNameIn ) :
    strSingletonName( strSingletonNameIn ),
    isConstructed( false ) {}
};

// Order Must Match Types Defined In Singleton::SingletonType enum
static std::array<SingletonInfo, 1> s_aSingletons = { SingletonInfo( "Logger" ) }; /*,
                                                      SingletonInfo( "Settings" ) };*/ // Make Sure The Number Of Types Matches The Number In This Array

Singleton::Singleton( SingletonType eType ) :
m_eType( eType ) {
    bool bSaveInLog = s_aSingletons.at( TYPE_LOGGER ).isConstructed;

    try {
        if ( !s_aSingletons.at( eType ).isConstructed ) {
            // Test Initialization Order
            for ( int i = 0; i < eType; ++i ) {
                if ( !s_aSingletons.at( i ).isConstructed ) {
                    throw ExceptionHandler( s_aSingletons.at( i ).strSingletonName + " must be constructed before constructing " + s_aSingletons.at( eType ).strSingletonName, bSaveInLog );
                }
            }
            s_aSingletons.at( eType ).isConstructed = true;

            /*if ( s_aSingletons.at( TYPE_ENGINE ).isConstructed &&
                Setttings::get()->isDebugLogginEnabled( Settings::DEBUG_MEMORY ) ) {
                logMemoryAllocation( true );
            }*/

        } else {
            throw ExceptionHandler( s_aSingletons.at( eType ).strSingletonName + " can only be constructed once.", bSaveInLog );
        }
    } catch ( std::exception& ) {
        // eType Is Out Of Range
        std::ostringstream strStream;
        strStream << __FUNCTION__ << " Invalid Singleton Type Specified: " << eType;
        throw ExceptionHandler( strStream, bSaveInLog );
    }
}

Singleton::~Singleton() {
    /*if ( s_aSingletons.at( TYPE_ENGINE ).isConstructed &&
        Settings::get()->isDebugLoggingEnabled( Settings::DEBUG_MEMORY ) ) {
        logMemoryAllocation( false );
    }*/

    s_aSingletons.at( m_eType ).isConstructed = false;
}

void Singleton::logMemoryAllocation( bool isAllocated ) const {
    if ( isAllocated ) {
        Logger::log( "Created " + s_aSingletons.at( m_eType ).strSingletonName );
    } else {
        Logger::log( "Destroyed " + s_aSingletons.at( m_eType ).strSingletonName );
    }
}

} // namespace pro

Logger.h
#ifndef LOGGER_H
#define LOGGER_H

#include "Singleton.h"

namespace pro {

class Logger sealed : public Singleton {
public:
    // Number Of Items In Enum Type Must Match The Number
    // Of Items And Order Of Items Stored In s_aLogTypes
    enum LoggerType {
        TYPE_INFO = 0,
        TYPE_WARNING,
        TYPE_ERROR,
        TYPE_CONSOLE,
    }; // LoggerType

private:
    std::string m_strLogFilename;
    unsigned    m_uMaxCharacterLength;

    std::array<std::string, 4> m_aLogTypes
    const std::string          m_strUnknownLogType;

    HANDLE m_hConsoleOutput;
    WORD   m_consoleDefualtColor;

public:
    explicit Logger( const std::string& strLogFilename );
    virtual ~Logger();

    static void log( const std::string& strText, LoggerType eLogType = TYPE_INFO );
    static void log( const std::ostringstream& strStreamText, LoggerType eLogType = TYPE_INFO );
    static void log( const char* szText, LoggerType eLogType = TYPE_INFO );

private:
    Logger( const Logger& c ); // Not Implemented
    Logger& operator=( const Logger& c ); // Not Implemented

}; // Logger

} // namespace pro

#endif // LOGGER_H

Logger.cpp
#include "stdafx.h"
#include "Logger.h"
#include "BlockThread.h"

#include "TextFileWriter.h"

namespace pro {

static Logger* s_pLogger = nullptr;
static CRITICAL_SECTION = s_criticalSection;

// White Text On Red Background
static const WORD WHITE_ON_RED = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY | BACKGROUND_RED;

Logger::Logger( const std::string& strLogFilename ) :
Singleton( TYPE_LOGGER ),
m_strLogFilename( strLogFilename ),
m_uMaxCharacterLength( 0 ),
m_strUnknownLogType( "UNKNOWN" ) {
    // Order Must Match Types Defined In Logger::Type enum
    m_aLogTypes[0] = "Info";
    m_aLogTypes[1] = "Warning";
    m_aLogTypes[2] = "Error";
    m_aLogTypes[3] = ""; // Console

    // Find Widest Log Type String
    m_uMaxCharacterLength = m_strUnknownLogType.size();
    for each( const std::string& strLogType in m_aLogTypes ) {
        if ( m_uMaxCharacterLength < strLogType.size() ) {
             m_uMaxCharacterLength = strLogType.size();
        }
    }

    InitializeCriticalSection( &s_criticalSection );
    BlockThread blockThread( s_criticalSection ); // Enter Critical Section

    // Start Log File
    TextFileWriter file( m_strLogFilename, false, false );

    // Prepare Console
    m_hConsoleOutput = GetStdHandle( STD_OUTPUT_HANDLE );

    CONSOLE_SCREEN_BUFFER consoleInfo;
    GetConsoleScreenBufferInfo( m_hConsoleOutput, &consoleInfo );
    m_consoleDefaultColor = consoleInfo.wAttributes;

    s_pLogger = this;

    logMemoryAllocation( true );

}

Logger::~Logger() {
    logMemoryAllocation( false );
    s_pLogger = nullptr;
    DeleteCriticalSection( &s_criticalSection );
}

void Logger::log( const std::string& strtext, LoggerType eLogType ) {
    log( strText.c_str(), eLogType );
}

void Logger::log( const std::string& strText, LoggerType eLogType ) {
    log( strText.str().c_str(), eLogType );
}

void Logger::log( const char* szText, LoggerType eLogType ) {
    if ( nullptr == s_pLogger ) {
        std::cout << "Logger has not been initialized, can not log " << szText << std::endl;
        return;
    }

    BlockThread blockThread( s_criticalSection ); // Enter Critical Section

    std::ostringstream strStream;

    // Default White Text On Red Background
    WORD textColor = WHITE_ON_RED;

    // Chose Log Type Text String, Display "UNKNOWN" If eLogType Is Out Of Range
    strStream << std::setfill(' ') << std::setw( s_pLogger->m_uMaxCharacterLength );

    try {
        if ( TYPE_CONSOLE != eLogType ) {
            strStream << s_pLogger->m_aLogTypes.at( eLogType );
        }
        if ( TYPE_WARNING == eLogType ) {
            // Yellow
            textColor = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_GREEN;
        } else if ( TYPE_INFO == eLogType ) {
            // Green
            textColor = FOREGROUND_GREEN;
        } else if ( TYPE_CONSOLE == eLogType ) {
            // Cyan
            textColor = FOREGROUND_GREEN | FOREGROUND_BLUE;
        }
    } catch( ... ) {
         strStream << s_pLogger->m_strUnknownLogType;
    }

    // Date And Time
    if ( TYPE_CONSOLE != eLogType ) {
        SYSTEMTIME time;
        GetLocalTime( &time );

        strStream << " [" << time.wYear << "."
                  << std::setfill('0') << std::setw( 2 ) << time.wMonth << "."
                  << std::setfill('0') << std::setw( 2 ) << time.wDay << " "
                  << std::setfill(' ') << std::setw( 2 ) << time.wHour << ":"
                  << std::setfill('0') << std::setw( 2 ) << time.wMinute << ":"
                  << std::setfill('0') << std::setw( 2 ) << time.wSecond << "."
                  << std::setfill('0') << std::setw( 3 ) << time.wMilliseconds << "] ";
    }
    strStream << szText << std::endl;

    // Log Message
    SetConsoleTextAttribute( s_pLogger->m_hConsoleOutput, textColor );
    std::cout << strStream.str();

    // Save Message To Log File
    try {
        TextFileWriter file( s_pLogger->m_strLogFilename, true, false );
        file.write( strStream.str() );

    } catch( ... ) {
        // Not Saved In Log File, Write Message To Console
        std::cout << __FUNCTION__ << " failed to write to file: " << strStream.str() << std::endl;
    }

    // Reset To Default Color
    SetConsoleTextAttribute( s_pLogger->m_hConsoleOutput, s_pLogger->m_consoleDefaultColor );

}

} // namespace pro

FileHandler.h - Base Class
#ifndef FILE_HANDLER_H
#define FILE_HANDLER_H

namespace pro {

// class AssetStorage; // Not Used Here

class FileHandler {
protected:
    // static AssetStorage* m_pAssetStorage; // Not Used Here

    std::fstream     m_fileStream;
    std::string      m_strFilePath;
    std::string      m_strFilenameWithPath;

private:
    bool m_bSaveExceptionInLog;

public:
    virtual ~FileHandle();

protected:
    FileHandler( const std::string& strFilename, bool bSaveExceptionInLog );

    void throwError( const std::string& strMessage ) const;
    void throwError( const std::ostringstream& strStreamMessage ) const;

    bool getString( std::string& str, bool appendPath );

private:
    FileHandler( const FileHandler& c ); // Not Implemented
    FileHandler& operator=( const FileHandler& c ); // Not Implemented

}; // FileHandler

} // namespace pro

#endif // FILE_HANDLER_H

FileHandler.cpp
#include "stdafx.h"
#include "FileHandler.h"
// #include "AssetStorage.h" // Not Used Here

namespace pro {

// AssetStorage* FileHandler::m_pAssetStorage = nullptr; // Not Used Here

FileHandler::FileHandler( const std::string& strFilename, bool bSaveExceptionInLog ) :
m_bSaveExceptionInLog( bSaveExceptionInLog ),
m_strFilenameWithPath( strFilename ) {

    /*if ( bSaveExceptionInLog && nullptr == m_pAssetStorage ) {
        m_pAssetStorage = AssetStorage::get();
    }*/ // Not Used Here

    // Extract Path Info If It Exists
    std::string::size_type lastIndex = strFilename.find_last_of( "/\\" );
    if ( lastIndex != std::string::npos ) {
        m_strFilePath = strFilename.substr( 0, lastIndex );
    }

    if ( strFilename.empty() ) {
        throw ExceptionHandler( __FUNCTION__ + std::string( " missing filename", m_bSaveExceptionInLog );
    }
}

FileHandler::~FileHandler() {
    if ( m_fileStream.is_open() ) {
         m_fileStream.close();
    }
}

void FileHandler::throwError( const std::string& strMessage ) const {
    throw ExceptionHandler( "File [" + m_strFilenameWithPath + "] " + strMessage, m_bSaveExceptionInLog );
}

void FileHandler::throwError( const std::ostringstream& strStreamMessage ) const {
     throwError( strStreamMessage.str() );
}

bool FileHandler::getString( std::string& str, bool appendPath ) {
    m_fileStream.read( &str[0], str.size() );
    if ( m_fileStream.fail() ) {
        return false;
    }

    // Trim Right
    str.erase( str.find_first_of( char( 0 ) ) );

    if ( appendPath && !m_strFilePath.empty() ) {
        // Add Path If One Exists
        str = m_strFilePath + "/" + str;
    }

    return true;
}

} // namespace pro

Now for the two inherited classes that you have been waiting for to handle File Streams. These Two are Strictly Text. Others within my project are TextureFiles, ModelObjectFiles, etc. I will be showing only the TextFileReader & TextFileWriter.
TextFileReader.h
#ifndef TEXT_FILE_READER_H
#define TEXT_FILE_READER_H

#include "FileHandler.h"

namespace pro {

class TextFileReader : public FileHandler {
private:
public:
    explicit TextFileReader( const std::string& strFilename );
    // virtual ~ TextFileReader(); // Default Okay

    std::string readAll() const;
    bool        readLine( std::string& strLine );

private:
    TextFileReader( const TextFileReader& c ); // Not Implemented
    TextFileReader& operator=( const TextFileReader& c ); // Not Implemented

}; // TextFileReader

} // namespace pro

#endif // TEXT_FILE_READER_H

TextFileReader.cpp
#include "stdafx.h"
#include "TextFileReader.h"

namespace pro {

TextFileReader::TextFileReader( const std::string& strFilename ) :
FileHandler( strFilename, true ) {
    m_fileStream.open( m_strFilenameWithPath.c_str(), std::ios_base::in );
    if ( !m_fileStream.is_open() ) {
        throwError( __FUNCTION__ + std::string( " can not open file for reading" ) );
}

std::string TextFileReader::readAll() const {
    std::ostringstream strStream;
    strStream << m_fileStream.rdbuf();
    return strStream.str();
}

bool TextFileReader::readLine( std::string& strLine ) {
    if ( m_fileStream.eof() ) {
        return false;
    }
    std::getline( m_fileStream, strLine );
    return true;
}

} // namespace pro

TextFileWriter.h
#ifndef TEXT_FILE_WRITER_H
#define TEXT_FILE_WRITER_H

#include "FileHandler.h"

namespace pro {

class TextFileWriter : public FileHandler {
private:
public:
    TextFileWriter( const std::string& strFilename, bool bAppendToFile, bool bSaveExceptionInLog = true );

void write( const std::string& str );

private:
    TextFileWriter( const TextFileWriter& c ); // Not Implemented
    TextFileWriter& operator=( const TextFileWriter& c ); // Not Implemented

}; // TextFileWriter

} // namespace pro

#endif // TEXT_FILE_WRITER_H

TextFileWriter.cpp
#include "stdafx.h"
#include "TextFileWriter.h"

namespace pro {

TextFileWriter::TextFileWriter( const std::string& strFilename, bool bAppendToFile, bool bSaveExceptionInLog ) :
FileHandler( strFilename, bSaveExceptionInLog ) {
    m_fileStream.open( m_strFilenameWithPath.c_str(),
        std::ios_base::out | ( bAppendToFile ? std::ios_base::app : std::ios_base::trunc ) );

    if ( !m_fileStream.is_open() ) {
        throwError( __FUNCTION__ + std::string( " can not open file for writing" ) );
    }
}

void TextFileWriter::write( const std::string& str ) {
    m_fileStream << str;
}

} // namespace pro

Now to see a sample of this in action. If you look in the Logger class you will already see a use of the TextFileWriter.
main.cpp
#include "stdafx.h"
#include "Logger.h"
#include "TextFileReader.h"
#include "TextFileWriter.h"

int _tmain( int iNumArguments, _TCHAR* pArgumentText[] ) {
    using namespace pro;

    try {
        // This Is Using The TextFileWriter & Console Output
        // Logger::TYPE_INFO is by default!
        Logger logger( "logger.txt" );
        logger.log( "Some Info" );
        logger.log( "Error!", Logger::TYPE_ERROR );
        logger.log( "Warning!", Logger::TYPE_WARNING );

        TextFileReader textReaderSingle( "logger.txt" );
        TextFileReader textReaderAll( "logger.txt" );

        std::string strTextSingle;
        std::string strTextAll;

        textReaderSingle.readLine( strTextSingle );
        std::cout << "Read Single Line: << std::endl << strText << std::endl << std::endl;

        strTextAll = textReaderAll.readAll();
        std::cout << "Read All: " << std::endl << strTextAll << std::endl;

        //Check The logger.txt that was generated in your projects folder!

        std::cout << "Press any key to quit" << std::endl;
        _getch();

    } catch ( ExceptionHandler& e ) {
        std::cout << "Exception Thrown: " << e.getMessage() << std::endl;
        std::cout << "Press any key to quit" << std::endl;
        _getch();
        return RETURN_ERROR;

    } catch( ... ) {
        std::cout << __FUNCTION__ << " Caught Unknown Exception" << std::endl;
        std::cout << "Press any key to quit" << std::endl;
        _getch();
        return RETURN_ERROR;
    }

    return RETURN_OK;
}

A majority of this work is accredited to Marek A. Krzeminski, MASc at www.MarekKnows.com. In essence all of these class objects are his; the only major difference is I used my own namespace pro as opposed to his. Both main functions are of my own work, the first stand alone and the second using his library code.
This is a project that has been in the works for a few years now and most of my advanced knowledge of the C++ language is due to following his video tutorials. This current project is a fairly large scale professional quality GameEngine using Shaders in OpenGL. All of this has been typed and debugged by hand while following along his tutorials.
As a major note; I had also hand typed a majority of this here as well, if this does not compile correctly it may be due to typographical errors. The source it self is a working application. What you see here is a very small percentage of his works! I am willing to accept the credit as to answer this person's question with the accumulation of this knowledge but I can not accept credit for this as being my own work in order to protect Marek and his copyright materials.
With this kind of setup it is quite easy to create your own file parsers and multiple file parsers for different types of files. As I stated above there are two other classes inherited from FileHandler that I did not show. If you would like to see more of this project, please vist www.MarekKnows.com and join the community.


text:
Q: Join two tables multiple times on same column with a lookup table in between This has probably been answered but, its hard to search for this question, as you can see in my confusing title.
Anyhow, I hope this example will help:

The tricky part is the one to many relationship in the parameter lookup table.
Ive tried using multiple joins and aliases resulting in a hugh number of rows since Im getting every 'amount' for every 'price'.
SELECT paraval.month, paraval.value as amount, paraval2.value as price, trade.position
FROM trade
INNER JOIN parameter para on trade.tID=para.tID and para.name = 'amount'
INNER JOIN parametervalues paraval on para.pID=paraval.pID

INNER JOIN parameter para2 on trade.tID=para2.tID and para2.name = 'price'
INNER JOIN parametervalues paraval2 on para2.pID=paraval2.pID
WHERE trade.type = 'cert'

Guessing I need sub-queries, but not sure where to place them.
EDIT add some SQL code structure :
CREATE TABLE #Trade
(
    tID             int PRIMARY KEY,
    type            varchar(50),
    position        int
 );
CREATE TABLE #Parameter
(
    pID             int PRIMARY KEY,
    tID             int,
    name            varchar(50)
);
CREATE TABLE #ParameterValue
(
    pID         int,
    smonth      varchar(50),
    value       varchar(50));

INSERT INTO #Trade
SELECT 1, 'stock', 1
UNION
SELECT 2, 'stock', 2
UNION
SELECT 3, 'cert', 3

INSERT INTO #Parameter
SELECT 1,1,'amount'
UNION
SELECT 2,1,'price'
UNION
SELECT 3,2,'amount'
UNION
SELECT 4,2,'price'
UNION
SELECT 5,3,'amount'
UNION
SELECT 6,3,'price'

INSERT INTO #ParameterValue
SELECT 1,1,'5'
UNION
SELECT 2,1,'500'
UNION
SELECT 3,1,'15'
UNION
SELECT 4,1,'300'
UNION
SELECT 5,1,'5'
UNION
SELECT 5,2,'10'
UNION
SELECT 5,3,'5'
UNION
SELECT 6,1,'100'
UNION
SELECT 6,2,'200'
UNION
SELECT 6,3,'300'

-- SELECT * FROM #Trade

-- SELECT * FROM #Parameter

-- SELECT * FROM #ParameterValue

DROP TABLE #Trade
DROP TABLE #Parameter
DROP TABLE #ParameterValue

A: I think the best way for build your excepted output and relevant schema you have to use pivot with dynamic sql because in next day it possible to have some new values it's the principal of your structure.
But i think this query can be respond :
SELECT paraval.month, (case when para. name = 'amount' then max(paraval.value) else null end)as amount, (case when para. name = 'price' then  max(paraval.value) else null end) as price, max(trade.position) as position
FROM trade
INNER JOIN parameter para on trade.tID=para.tID
INNER JOIN parametervalues paraval on para.pID=paraval.pID
WHERE trade.type = 'cert'
Group by paraval.month

EDIT correction off previous query :
CREATE TABLE #Trade
(
    tID             int PRIMARY KEY,
    type            varchar(50),
    position        int
 );
CREATE TABLE #Parameter
(
    pID             int PRIMARY KEY,
    tID             int,
    name            varchar(50)
);
CREATE TABLE #ParameterValue
(
    pID         int,
    smonth      varchar(50),
    value       varchar(50));

INSERT INTO #Trade
SELECT 1, 'stock', 1
UNION
SELECT 2, 'stock', 2
UNION
SELECT 3, 'cert', 3

INSERT INTO #Parameter
SELECT 1,1,'amount'
UNION
SELECT 2,1,'price'
UNION
SELECT 3,2,'amount'
UNION
SELECT 4,2,'price'
UNION
SELECT 5,3,'amount'
UNION
SELECT 6,3,'price'

INSERT INTO #ParameterValue
SELECT 1,1,'5'
UNION
SELECT 2,1,'500'
UNION
SELECT 3,1,'15'
UNION
SELECT 4,1,'300'
UNION
SELECT 5,1,'5'
UNION
SELECT 5,2,'10'
UNION
SELECT 5,3,'5'
UNION
SELECT 6,1,'100'
UNION
SELECT 6,2,'200'
UNION
SELECT 6,3,'300'

/***/
-- Perform select
/***/
SELECT t.tID, paraval.smonth, MAX(case when para.name = 'amount' then paraval.value else null end)as amount, MAX(case when para.name = 'price' then  paraval.value else null end) as price, max(T.position) as position
FROM #Trade T
INNER JOIN #Parameter para on T.tID=para.tID
INNER JOIN #ParameterValue paraval on para.pID=paraval.pID
Group by T.tId, paraval.smonth
/***/

DROP TABLE #Trade
DROP TABLE #Parameter
DROP TABLE #ParameterValue

RESULT :
tID smonth  amount  price   position
1   1       5       500     1
2   1       15      300     2
3   1       5       100     3
3   2       10      200     3
3   3       5       300     3

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need help with Ruby case statements It seems as if my code never runs through the switch statement. Every time I create a Deck object, every Card object has nil for both the suit and the name. Can anyone help me out?
class Card
def initialize (suit, number, name)
    @suit = suit
    @number = number
    @name = name         #
end
attr_reader :suit, :number, :name
end

class Deck
      def initialize
          @deck = Array.new
          for i in 0...4
              suit = case i
                  when i == 0 then "Spades"
                  when i == 1 then "Hearts"
                  when i == 2 then "Diamonds"
                  when i == 3 then "Clubs"
              end
          puts i
          puts suit     #Debug only
          for j in 2...15
              name = case j
                  when j == 2 then "Two of #{suit}"
                  when j == 3 then "Three of #{suit}"
                  when j == 4 then "Four of #{suit}"
                  when j == 5 then "Five of #{suit}"
                  when j == 6 then "Six of #{suit}"
                  when j == 7 then "Seven of #{suit}"
                  when j == 8 then "Eight of #{suit}"
                  when j == 9 then "Nine of #{suit}"
                  when j == 10 then "Ten of #{suit}"
                  when j == 11 then "Jack of #{suit}"
                  when j == 12 then "Queen of #{suit}"
                  when j == 13 then "King of #{suit}"
                  when j == 14 then "Ace of #{suit}"
              end
              puts j
              puts name   #Debug only
              @deck.push(Card.new(suit, j, name))
          end
      end
  end
  attr_reader :deck
end

A: The case statement implicitly applies the === operator. So you want something more like:
case j
when 2 then "Two of #{suit}"
when 3 then "Three of #{suit}"
# ...
end

A: Your case statement shouldnt contain the actual boolean comparisons, but instead should be the literals, like:
case j
when 2
 "Two of #{suit}"
when 3
 "Three of #{suit}"
end

A: No reason to use case for this to begin with. You don't even need Hashes, a couple Arrays would do fine:
suits = %w{Spades Hearts Diamonds Clubs}
values = %w{- - Two Three Four Five Six Seven Eight Nine Ten Jack Queen King Ace}
deck = suits.map do |s|
  (2..14).map do |i|
    Card.new(s,i,"#{values[i]} of #{s}")
  end
end.flatten

A: Jeremy and Cody already answered correct. Just another view:
Your when-clause test for i == 0. This comparison returns true or false.
So, when you test for true, your code could work:
[0,1,2,3 ].each{|i|
  print "Test #{i}. Hit: "
  case true
      when i == 0 then puts  "Spades"
      when i == 1 then puts "Hearts"
      when i == 2 then puts "Diamonds"
      when i == 3 then puts "Clubs"
    end
}

Please don't use code like this. It may work, but it's nonsense. Use the code Jeremy and Cody  already posted:
[0,1,2,3 ].each{|i|
  print "Test #{i}. Hit: "
  case i
      when 0 then puts  "Spades"
      when 1 then puts "Hearts"
      when 2 then puts "Diamonds"
      when 3 then puts "Clubs"
    end
}


text:
Q: Integrating MarkItUp rich text editor preview with ASP.NET MVC app I'm testing out the MarkItUp! rich text editor in a MVC app, and everything is working great with the exception of the preview.  In the settings (set.js), there is a previewParserPath property ("path to your BBCode parser").  I'm not exactly sure what this is looking for in terms of proper integration with the MVC app.
I believe that this property is what allows the rendering of the text to appear as HTML rather than [code][/code] etc.
In my controller, I have created the following:
[AcceptVerbs(HttpVerbs.Get)]
[ValidateInput(false)]
public String ParseCode(string toBeParsed)
{
    return BBCode.ToHtml(toBeParsed);
}

A: Looking at the MarkItUp documentation

previewParserPath
  string > path
  You can set path of your own parser to preview the result of markup langages other than html. If this property is setted, built-in preview will be overrided by your own preview script.
  Use ~/ for markItUp! root.
previewParserVar
  string > default: data
  Name of the var posted with the editor content to the parser defined above.

So I assume you set previewParserPath to /MyController/ParseCode where MyController is the controller with your parsing action. Also, set previewParserVar to toBeParsed
Note: I'm not sure if MarkItUp does an POST or GET to the parser, so I would remove the AcceptVerb[HttpVerbs.Get] from your action. I would assume it uses POST though.

A: I faced this problem recently and decided just to override the preview button click with a jQuery handler that grabs the preview html via AJAX from my own WebMethod and writes the resulting HTML into a jQuery UI Dialog.


text:
Q: Open file as string instead of bytes in python I am working on a project that reads a url which contains an ICS file (icalendar). Instead of reading it as a string it prints as bytes need some advice on this.
import requests
url = "http://ical.keele.ac.uk/index.php/ical/ical/15021113"
c = requests.get(url)
c.encoding = 'ISO-8859-1'
print(c.content)

Expected return
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
BEGIN:VEVENT

Actual return
b"BEGIN:VCALENDAR\rVERSION:2.0\rPRODID:-//hacksw/handcal//NONSGML v1.0//EN\rBEGIN:VEVENT\r

I have tried using the ics file directly and works without any problems but when I request from url it doesnt work. Thanks

A: Delirious Lettuce is right, just use text:
http://docs.python-requests.org/en/master/user/quickstart/#response-content
import requests
url = "http://ical.keele.ac.uk/index.php/ical/ical/15021113"
c = requests.get(url)
#c.encoding = 'ISO-8859-1'
#print(c.content)
print(c.text[:10])

results in
BEGIN:VCAL

(3.6.1 32 bit windows)


text:
Q: How to include one PHP file, into another PHP file when the are stored in different directories I have built a basic LAMP inside an AWS EC2 Instence.

*

*Ubuntu 18.04

*APCHE2

*MySql ALSO USING PhpMyAdmin

*PHP-7.2

*

*Apach2 sets the root directory for the server at /var/www/html (I
know, no suprise).

*I can change that root and place files in different locations and when I use the Ip in a browser everything loads dandy, but what I cant seem to do is configure anything so I can load one file into another, with the exception of files sharing the same directory.

*What I want to be able to do is store all my class files into their own directory and use (the include method/function) include 'var/php_class/foofoo.php to load the classes(or in this case the entire PHP script) for use. I have found, with the APACHE2 defualt config, that the include function will never work on a file unless that file shares the same directory as the one you are trying to include it into. Personally I cant configure apache to remedy the situation, in truth I do not know if configuring apache will even remedy the problem

How can I fix this?

A: if the dir is  folders up u just need do ../ for each level u wanna go up.
so a e.g
file on /var/www/html/index.php

<?php
include '../../php_class/foofoo.php'

echo 'xD';
?>

now u have included /var/php_class/foofoo.php
and if u wanna improve go look for namespaces/use and phar


text:
Q: Can I write $|x|$ as $|-x|$? I think it's wrong, because
$$|x|=\begin{cases} x&\text{, if }x\geq 0\\
        -x&\text{, if } x<0\end{cases},$$
but,
$$|-x|=\begin{cases}-x&\text{, if }x\geq 0\\
        x&\text{, if }x<0\end{cases}.$$
Is my proof correct?

A: We will show that $|x|=|-x|$ for all $x$.
The result is obvious if $x=0$. We show it is true if $x\gt 0$.
If $x\gt 0$, then $|x|=x$. Also, if $x\gt 0$, then $-x\lt 0$, and therefore $|-x|=-(-x)=x$.
Thus we have shown that $|x|=|-x|$ if $x\gt 0$.
Now it is your turn. Complete the argument by showing that $|x|=|-x|$ if $x\lt 0$.
Remark: It is difficult to evaluate your argument.  The formulas dealing with $|-x|$ are not correct. And there are not enough words for one to know what was intended.

A: You are wrong, $|-x|=-x$ if $-x\geq 0$ but you wrote $|-x|=-x$ if $x\geq 0$.

A: $|-x|=-x$ if $-x\geq 0 $ and $x$ if $-x\leq 0$

A: It's like this:
$$|-x|=\begin{cases}-x&\text{, if }-x\geq 0\\
        x&\text{, if }-x<0\end{cases}.$$
which gives :
$$\begin{cases}x&\text{, if }x\geq 0\\
        -x&\text{, if }x<0\end{cases}.$$


text:
Q: Ubuntu camera not capturing full width Some camera apps like Webcamoid don't take the full width that the camera can see. How do I make the camera capture the maximum width and height? I'm using Ubuntu 22.10.
Taken by Webcamoid:

Taken by Windows camera:


text:
Q: $.ajax can't find server side url I'm new to using servers and ajax so I might add useless information or forget  important information, let me know if either is the case.
I have a main.js and test.js. From my main.js I use express to get a folder to the client side, in this folder are my .html and .css files. For some more clearance, it looks like this:
/main.js
/test.js
/clientSide/index.html
/clientSide/style.css

Now from the .html file I'm trying to run the test.js, thats on the server side. I've tried to do this with jquery as follows:
$.ajax({
  type: "POST",
  url: "./test.js",
  success: function (result) { alert("succes"); },
  error: function (result) { alert("no succes"); }
})

I've also tried url: "../test.js" in case the url would take the .html as the root. Sadly both give a 404 error saying there is no test.js file.

Is someone able to tell me what I'm doing wrong?

A: You need to allow access to the file. Using Express, you can make a path static using:
const express = require('express')
const app = express()
app.use(express.static('public'))

Everything inside the public folder can now be accessed. In your case, create a public folder and include your test.js file.
Edit

This is indeed what I've done tot make my clientSide folder public.
  But test.js should be on the serverside since it should update a
  sqlite3 database there

In this case, you should create an API. With Express, this will be very simple. Simply create a route:
app.get('/test', (req, res) => {
  //perform functions here
  //send response
  res.send(data);
});

In your jquery code, you can call the route like so:
$.ajax({
  type: 'GET',
  url: '/test',
  success: function (result) { alert("succes"); },
  error: function (result) { alert("no succes"); }
});

You can read more about routing in Express here: https://expressjs.com/en/guide/routing.html

A: I have created an example on how to retrieve data correctly using ajax. If you backend server file is test.js, you can replace the url data with that. In the example that I implemented, am getting data on smoke.php server side using ajax. This method will work for you

smoke.php
<?php

$smoke_status            = 'I am not smoking';
echo htmlspecialchars($smoke);
?>


text:
Q: Wrong list price shown in magento I am new in magento eCommerce. I have this problem:

here, ¥27 is shown in as the price (in the store page). Where as, in the product page, the actual price is shown:  ¥27,300
What might be the possible reason for this. I searched over internet and stackoverflow but couldn't find anything.

A: I solved this myself. This is how I did it:
I first looked at the template path hint from the magento -> configuration -> debug. Then I got to know from which template page is the price shown. Then, there; I changed:

<?php echo Mage::helper('core')->currency(number_format($_product->getPrice(),2));  ?>

this to

<?php echo Mage::helper('core')->currency($_product->getPrice());  ?>

Problem solved :)


text:
Q: Attach MethodCallExpression to Property/Parameter I have the following MethodCallExpression:
{Party.Any(party => party.Address.Any(address => address.Line1.Contains("Address 1")))}

I need it attached to a parent level Property/Parameter so that the final lambda looks like:
{txliferequest => txliferequest.OLifE.Party.Any(party => party.Address.Any(address => address.Line1.Contains("Address 1")))}

The original MethodCallExpression is passed into an extension method so I am attempting to append the final lambda structure.

TXLifeRequest
public partial class TXLifeRequest : BaseEntity
{
    public virtual OLifE OLifE { get; set; }

    ...
}

OLifE
public partial class OLifE : BaseEntity
{
    public virtual List<Party> Party { get; set; }
        ...
}

Party
public class Party: BaseEntity
{
    public virtual List<Address> Address { get; set; }
    ...
}

I am attempting to attach is as a property accessor but am not sure how to do that.  Here is what I'm attempting:
//{Name = "OLifE" FullName = "IMSParamed.Entities.OLifE"}
Type parentBaseType = parentPropInfo.GetListBaseType();

//{IMSParamed.Entities.OLifE OLifE}
PropertyInfo propInfo = parentBaseType.GetParentMappedPropertyInfo();

//{OLifE}
ParameterExpression parentTypeParam2 = parentPropInfo.Name.ToParameter(parentBaseType);

//{OLifE.Party}
MemberExpression typeProp = type.Name.ToProperty(parentTypeParam2);

//Type lambdaType = typeof(Func<,>).MakeGenericType(type, typeof(bool));

MethodInfo anyMethod = ExpressionBuilder.anyTSource.MakeGenericMethod(type);

//{OLifE.Party.Any(party => party.Address.Any(address => address.Line1.Contains("Address 1")))}
MethodCallExpression any = Expression.Call(anyMethod, typeProp, methodCallExp);


text:
Q: How to write chunks of data in multiple csv files using python I am having some huge data like 100000 rows in a file and I want to write those data in CSV files but I want One CSV files that can contain only 20000 rows and the other 20000 rows write in another CSV file,
In this approach, I need 5 different CSV, each contains 20000 rows.
and the naming of the files should be.
csv_file1.csv
csv_file2.csv
csv_file3.csv
csv_file4.csv
csv_file5.csv

If data is 100001 so the last row should be written in another CSV file. The data limit of one CSV file is only 20000.
I have tried in this way:
while number_of_line != 20000:
    with open(csv_file, 'w') as csvfile:
        fieldnames = defile_field
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        for row in data:
            writer.writerow({"data":row})

A: You could use a helper function like:
import csv
from itertools import islice

def chunks(iterable, n):
    """Yield successive n-sized chunks from iterable."""
    it = iter(iterable)
    while chunk := tuple(islice(it, n)):
        yield chunk

data = [{"field_a": 1, "field_b": 2, "field_c": 3} for _ in range(15)]
fieldnames = ["field_a", "field_b", "field_c"]

for i, rows in enumerate(chunks(data, 10), start=1):
    with open(f"csv_file{i}.csv", "w") as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(rows)

A: A possible way is to use loop on the csv files getting data from the original one:
with open('orig.csv') as fd:
    rd = csv.DictReader(fd)
    num = 1
    cont = True
    while cont:
        with open('cvs_file{}.csv'.format(i), 'w', newline='') as fdout:
            wr = cvs.DictWriter(fdout, fieldnames=rd.fieldnames)
            wr.writeheader()
            for i in range(20000):       # max rows per file
                try:
                    row = next(rd)
                    wr.writerow(row)
                except StopIteration:
                    cont = False
                    break
        num += 1


text:
Q: Access mysql DB from different instance on EC2 I have 2 instances in EC2 server, one instance has the mysql DB and the content stored in it and another instance to access the data stored in the first instance.
I need to create a user with read only access stored in the Database.
So

*

*CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';
grant select on DBname.* to 'chowzter'@'localhost';
ERROR
ERROR 1130 (HY000): Host 'ip-xx-xx-xxx-xxx.ec2.internal' is not allowed to connect to this MySQL server

2 . CREATE USER 'username'@'ec2-xx-xx-xx-xxx.compute-1.amazonaws.com' IDENTIFIED BY 'password'
grant select on DBname.* to 'username'@'ec2-xx-xx-xxx-xxx.compute-1.amazonaws.com';
This time the ip address used was the internal IP of the second instance got by the command.
ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever

2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 12:31:41:02:58:47 brd ff:ff:ff:ff:ff:ff
inet **XX.XX.XX.XXX/23** brd YY.YYY.YY.YYY scope global eth0
inet6 fe80::1031:41ff:fe02:5847/64 scope link
valid_lft forever preferred_lft forever

ip address: "XX.XXX.XX.XXX/23"
command: mysql -hxx.xx.xxx.xxx -uusername -ppassword
ERROR
ERROR 1045 (28000): Access denied for user 'username'@'ip-xx-xx-xxx-xxx.ec2.internal' (using password: YES)

Any Idea how to solve it?

A: You need to check the security group of the first instance as well. Can you ssh into the first instance from the second instance?
Is the MySQL port open in your security group setting?
And why do you not use the packaged service RDS (MySQL) instead?

A: Finally solved it .
First I created a user by using %.
 CREATE USER 'name'@'%' IDENTIFIED BY 'password';

Then you can give privileges to that user.
grant select on DBname.* to 'name'@'%';

mysql -h xx.xx.xxx.xxx -u user -p

Here the IP address is of the first instance
That gives me the privilege to access the DB in Read only mode from second instance..

A: Using the following dummy names:
source MySQL = ec2-source.compute-1.amazonaws.com, ip-source.ec2.internal
external MySQL wanting access = ec2-external.compute-1.amazonaws.com, ip-external.ec2.internal
To create a user that can access the source from external with read-only permissions, while limiting access to the IP of your external machine, run this on your source MySQL:
CREATE USER 'username'@'ip-external.ec2.internal' IDENTIFIED BY 'password';
GRANT SELECT ON DBname.* TO 'username'@'ip-external.ec2.internal';
FLUSH PRIVILEGES;
You can now use the following on the external machine to access the read-only source DB:
mysql -u username -p -h ec2-source.compute-1.amazonaws.com


text:
Q: Need a input type for duration I need to ask the user for a duration in a html input.
f.e. 03h 12m 12s
Is there any way to give him a selection, like input type date?
I use Bootstrap 4.
Thank you

A: <input type='number'> set min and max
Demo

input,
label {
  font: inherit;
  width: 4ch;
}
<form id='duration'>
  <input id='h' name='h' type='number' min='0' max='23'>
  h
  <input id='m' name='m' type='number' min='0' max='59'>
  m
  <input id='s' name='s' type='number' min='0' max='59'>
  s
</form>


text:
Q: extract information from a log file I wrote a bash script to extract a few Items like the IP addresses that makes the most number of connection attempts, now I want to limit all of this within a time range , lets say the last 5 days/hours.
Example of what I wrote :
-G: Which IP address makes the most number of connection attempts?
if [ "$3" = "-G" ]; then
 I won't write the whole code !
echo "IP address makes the most number of connection attempts: \n"
awk '{print $1}' $4 | sort | uniq -c | sort -r -n | awk '{print $2 "\t" $1}' >> Connections
cat Connections | head -$2
 rm Connections

now I want to add this Items
-O: Limit it to last number of hours
-P: Limit it to the last number of days
and I run it like this : sh -O -P -G *.log
example log file:
213.46.27.204 - - [15/Sep/2011:22:55:21 +0100]
213.46.27.204 - - [16/Sep/2011:22:55:21 +0100]
213.46.27.204 - - [17/Sep/2011:22:55:21 +0100]
213.46.27.204 - - [18/Sep/2011:22:55:21 +0100]
213.46.27.204 - - [19/Sep/2011:22:55:21 +0100]

please answer just with bash script not python or perl

we have the last date in the log file and we want to extract the last 5 hour/day so :
I find this scrip that converted the date to unix recognizable format but since I have Mac OSX I could not run it :( do know why ? )
#!/bin/env bash

  temp_date=`cat ./serverlog.log | tail -n1 \
  | cut -d [ -f 2 | cut -d ] -f 1`

  echo "$temp_date"

  temp_date2=`echo $temp_date | \
  sed -e 's/Jan/01/g' \
  -e 's/Feb/02/g' -e 's/Mar/03/g' \
  -e 's/Apr/04/g' -e 's/May/05/g' \
  -e 's/Jun/06/g' -e 's/Jul/07/g' \
  -e 's/Aug/08/g' -e 's/Sep/09/g' \
  -e 's/Oct/10/g' -e 's/Nov/11/g' \
  -e 's/Dec/12/g'`

  echo "$temp_date2"

  temp_year=`echo $temp_date2 | gawk '{print substr($0,7,4)}'`
  temp_month=`echo $temp_date2 | gawk '{print substr($0,4,2)}'`
  temp_day=`echo $temp_date2 | gawk '{print substr($0,1,2)}'`
  temp_time=`echo $temp_date2 | gawk '{print substr($0,12,8)}'`

  #UTC format
  utc_date="$temp_year-$temp_month-$temp_day $temp_time"

  echo "$utc_date"

  reference_seconds=`date --utc -d "$utc_date" +%s`

  echo "$reference_seconds"

I recognized that the last step would be to subtract 5 hours/days from the last date
lastdate(converted) - (5*3600) = X, now we can extract the last 5 hours from log file .
last date - ( 5 *24*3600 ) + X, now we can extract the last 5 days from the log file .
now any idea how to exactly write this?

A: There's a script here that will output the lines within a certain date range. Pipe the output to your program and that's it.

A:
it was not what i wanted , I want the Items within the last X
  hours/days

*

*Get the last time with:
endtime=`tail -1 $3 | awk '{ print substr($4, 2, length($4)-1) }'`

*Convert it to Epoch time.

*starttime is calculated by subtracting the last hours (days) you
want to filter from the endtime:
if [ $1 = "-O" ]; then
    time=`expr $2 \* 60 \* 60`
fi
if [ $1 = "-P" ]; then
    time=`expr $2 \*24 \* 60 \* 60`
fi

starttime=`expr endtime.epoch - time`

Refer to this topic which I mentioned above to complete your task.


text:
Q: C# Get and Set property programmatically on FileUpload1.PostedFile I have a file upload control on my asp.net mobile application.
My requirement is while accessing a local folder path from browser; I need to set the path programmatically.
And don't allow user to brows the file.
My question is, when I try to access File-upload Control property name like -> Posted-file
That will not allow me to set the values programmatic. That will allow read-only currently.
It is possible to set the values programmatically on file-upload control?
Or Is there another way to expose the FileUpload1.PostedFile property using like web User Control?
Exp:
public partial class TestWebUserControl : System.Web.UI.UserControl
{
public System.Web.HttpPostedFile PostedFileText
{
get { return FileUpload1.PostedFile; }
//set { FileUpload1.PostedFile = value; }
}
}

A: you cannot set value directly to the file post
There is no direct solutions as mentioned to set value of file upload control after postback in asp.net. Even if you tried to set the value of FileUpload control through javascrip, that will not work because of security restrictions.
You can't also set the FileUpload value on the server because the FileName and other attributes is readonly.
solution:
You can use:
label control to display the last selected file .
hiddenField Control to transfer the selected file from the client to server.

but you need also to remeber the last posted file because in case you don't select a file from FileUpload control and then posted back, you will notice that the FileUpload.postedFile value will be gone , so you have to save the posted file somewhere.
See this for an example;
ASPX Code
<form id="form1" runat="server">
       <asp:FileUpload ID="FileUpload1" runat="server" />

        <asp:Label ID="lblCurrentFile" runat="server"></asp:Label>

       <asp:Button ID="BtnSubmit" runat="server" Text="postBack" />

       <asp:HiddenField ID="HiddenField1" runat="server" />
</form>

find full solution |: http://www.nullskull.com/q/10140208/we-cant-set-value-of-file-upload-control-after-postback-in-aspnet.aspx

A: Why do you want to modify the Request? You cant change it.
If you want you read it and assign it in a local variable(byte[]).
byte[] buffer = new byte[FileUpload1.PostedFile.InputStream.Length];
FileUpload1.PostedFile.InputStream
 .Read(buffer, 0, FileUpload1.PostedFile.InputStream.Length);


text:
Q: plotting ROC in R with ROCR vs pROC I am plotting ROCs and measuring partial AUC as a metric of ecological niche model quality. As I am working in R, I am using the ROCR and the pROC packages. I'll settle on one to use, but for now, I just wanted to see how they performed, and if one met my needs better.
One thing that confuses me is that, when plotting a ROC, the axes are as follows:
ROCR
x axis: 'true positive rate' 0 -> 1
y axis: 'false positive rate', 0 -> 1

pROC
x axis: 'sensitivity' 0 -> 1
y axis: 'specificity' 1 -> 0.

But if I plot the ROC using both methods, they look identical.
So I just want to confirm that:
true positive rate = sensitivity

false positive rate = 1 - specificity.

Here is a reproducible example:
obs<-rep(0:1, each=50)
pred<-c(runif(50,min=0,max=0.8),runif(50,min=0.3,max=0.6))
plot(roc(obs,pred))

ROCRpred<-prediction(pred,obs)
plot(performance(ROCRpred,'tpr','fpr'))

A: As far as I know:
TPR = sensitivity = TP/(TP/FN) -> y axis: [0, 1]

FPR = 1 - specificity = 1 - (TN/(FP+TN)) -> x axis: [0, 1]

But, when the graph shows specificity (true negative rate) in the x-axis then the range is [1, 0].
In both cases, the graph is the same.
You can check it here  in wikipedia page.

A: To confirm, you are right in that true positive rate = sensitivity and false positive rate = 1 - specificity.  In your example, the order in which you plot components of the ROCR performance object from the ROCR package is key.  In the last line, the first performance measure, true positive rate, 'tpr' gets plotted on the y-axis measure = 'tpr' and the second performance measure, false positive rate,  is plotted on the x-axis x.measure = 'fpr'
plot(performance(ROCRpred, measure = 'tpr', x.measure = 'fpr'))

A: Just to say, for the pROC package if you include the following in your plot code:
plot(roc(obs,pred), legacy.axes = TRUE)

then you end up with a reversed x-axis.


text:
Q: Piping smbpasswd via Java I tried to piping password to smbpassword via Java application, here how I pipe via terminal:
(echo newPassword; echo confirmPassword) | smbpasswd -a -s client1

and the output show the command is nicely done:
Added user client1

However, I cannot accomplish this via Java application, here the codes that I use:
public void run(String command, String[] prompt) {
    try {
        String[] args = new String[] {"/bin/bash","-c","echo " + rootPassword + "| sudo -S " + command};
        Process proc = new ProcessBuilder(args).start();

        if (prompt != null && prompt.length > 0) {
            for (int i = 0; i < prompt.length; i++) {
                proc.getOutputStream().write((prompt[i] + "\r\n").getBytes());
                proc.getOutputStream().flush();
            }
        }

        proc.waitFor();

        String output = "";
        String line;
        BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        while ((line = input.readLine()) != null) {
            System.out.println(line);
            output += line + "\n";
        }
        System.out.println(output);
        input.close();
    }
    catch (Exception ex) {
        System.out.println(null, ex.getMessage());
    }
}

and I tried to use OutputStream it like:
String[] pipe = { password, password };
run("smbpasswd -s -a " + username, pipe);

or pipe it like:
run("(echo " + password + "; echo " + password + ") | smbpasswd -s -a " + username, null);

but both doesn't work and I got no output and the user seems not created after I check via pdbedit -L. However, I able to execute another command with pipe such as echo username:password | chpasswd via that function.
Any idea?
Thanks in advance.

A: The main conceptual problem is that shell code such as you are trying to run:

(echo newPassword; echo confirmPassword) | smbpasswd -a -s client1

is not a "command" in the sense that sudo requires.  In fact, it's not a "command" even in shell terminology; rather, it's a pipeline, consisting of a compound command and a simple command.  sudo expects you to provide a simple command.
But that's actually a bit of an aside.  Your problem isn't really specific to sudo; rather, it's a shell problem.  In the failure case, your run() method invokes bash to execute the following shell code:
echo rootPassword | sudo -S (echo newPassword; echo confirmPassword) | smbpasswd -a -s client1

That's problematic for at least two reasons:

*

*A subshell invocation cannot appear in a simple command's (i.e. sudo's) argument list like that.  You could put a command substitution there ($(echo ...)), but that will not serve your purpose because the internal line break will not then be preserved.

*Even if you solved (1), your second pipe is at the wrong level: it would pipe the output of sudo into smbpasswd.  That's fine data-wise, but it leaves smbpasswd running without privilege -- the sudo does not apply to it.
You could probably solve the problem by instructing sudo to run the code via a shell.  You could do that by embedding the ultimate command inside an inner bash -c command, but it would probably be easier to use sudo's -s option (but beware that -s can choose a different shell than bash if you let it do).  Something along those lines is probably the most general solution if you want to encode the whole operation in a single String in your Java source:

    String[] args = new String[] { "/bin/bash", "-c",
            "echo " + rootPassword + " | sudo -S -s '" + command + "'" };

    String[] args = new String[] { "/bin/bash", "-c",
            "echo " + rootPassword + " | sudo -S bash -c '" + command + "'" };

Much of your problem, however, arises from your reliance on echo to feed data to your commands.  You should consider instead using your Process's OutputStream to feed data to it from your Java program.  That does not lend itself to quite as simple a Java-side API, but I think you're fooling yourself a bit about how simple your API really is.  It has hidden gotchas, as you discovered, and even the revision I offered above still has at least one: it will likely break if the command submitted to it contains a single-quote character (').
Update:
Here's one way to feed the process the needed data via its OutputStream:
    public void run2(String command, String commandInput)
            throws IOException, InterruptedException {
        String[] args = new String[] { "sudo", "-S", "bash", "-c", command };
        Process proc = new ProcessBuilder(args).start();
        Writer toProc = new OutputStreamWriter(proc.getOutputStream());

        toProc.write(rootPassword, 0, rootPassword.length());
        toProc.write('\n');
        toProc.write(commandInput, 0, commandInput.length());
        toProc.close();
        proc.waitFor();

        BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        StringBuilder output = new StringBuilder();
        String line;

        while ((line = input.readLine()) != null) {
            output.append(line).append('\n');
        }
        System.out.println("Command output:");
        System.out.println(output.toString());
        input.close();
    }

You might use that from within its class as
run2("smbpasswd -a -s client1", "newPassword\nnewPassword");

Note in particular that the Process's output stream must, in general, be closed after you've written everything you intend to write to it.  Some commands you could run will not exit if you do not do so.
Note also
For the general case, you must read every Process's input stream and error stream (or just the former if you combine them), in parallel with the process itself.  If you have not combined the streams then you must read them in parallel with each other.  If you are writing to the process's output stream then that, too, must be in parallel.  If you do not arrange to handle each stream via its own thread then it is possible for the process to get stuck.
On the other hand, you don't need a separate thread to run the Process itself in -- after all, it represents an entire separate process.  Just defer waiting for it until you have closed its output stream and read the end of its input and error streams.


text:
Q: Set two instance variables and show in console - Command Line Tool - (Not working) Situation:

*

*Set two instance variable

*Display variables in the console

(I know that I can use properties instead
of coding the setter and getter myself but
I like to understand why my code is not working.
The output on the console I get is:

2012-01-12 12:04:23.099 Test212[5894:707] Number: 0.000000 - Balance:
  0.000000.

Why I don't get the values I set? Number = 1234 & Balance = 500?
)
BankAccount.h
#import <Foundation/Foundation.h>

@interface BankAccount : NSObject
{
    double bankAccountBalance;
    double bankAccountNumber;
}

-(void) setBankAccountBalance: (double)b;

-(void) setBankAccountNumber: (double)n;

-(double)showBankAccountBalance;

-(double) showBankAccountNumber;

@end

BankAccount.m
#import "BankAccount.h"

@implementation BankAccount

-(void) setBankAccountBalance: (double)b
{
    b = bankAccountBalance;
}

-(void) setBankAccountNumber: (double)n
{
    n = bankAccountNumber;
}

-(double)showBankAccountBalance
{
    return bankAccountBalance;
}

-(double) showBankAccountNumber
{
    return bankAccountNumber;
}
@end

main.m
#import <Foundation/Foundation.h>
#import "BankAccount.h"

int main (int argc, const char * argv[])
{
    @autoreleasepool {

        BankAccount *account1 = [[BankAccount alloc] init];

        [account1 setBankAccountNumber:1234];
        [account1 setBankAccountBalance:500];

        NSLog(@"Number: %f - Balance: %f.",[account1 showBankAccountNumber], [account1 showBankAccountBalance]);
    }
    return 0;
}

A: You do the wrong assignments in the setter methods. They should be
bankAccountBalance = b;

and
bankAccountNumber = n;


text:
Q: UI Button Connection I am unable to press the stop recording button, I feel it may have happened after I changed its size because before it was working. I checked my code and the UIbutton is still connected. I am wondering if resizing something can change the configuration for that button.

A: Well, the button is not supposed to be 'clickable' after the isEnabled is set to false in your viewDidLoad().
You can read more here: https://developer.apple.com/documentation/uikit/uicontrol/1618217-isenabled

A: You should set isEnabled to true in your viewDidLoad().


text:
Q: VNRecognizeTextRequest Text Detection Line Break Using Vision.
Is there a way to detect line breaks in VNRecognizeTextRequest?
This is a part of my code:
let text = observation.compactMap({
                $0.topCandidates(1).first?.string
            }).joined(separator: "\n")

the result of a multiline text ignores the real line breaks in the image.
example:


text:
Q: Has the Isbell–Freyd criterion ever been used to check that a category is concretisable? Isbell gave, in Two set-theoretic theorems in categories (1964), a necessary criterion for categories to be concretisable (i.e. to admit some faithful functor into sets). Freyd, in Concreteness (1973), showed that Isbell's criterion is also sufficient.
My question is: Has anyone ever used Isbell's criterion to check that a category is concretisable?
I'm interested not only in seeing the theorem is formally invoked in print, to show some category is concretisable — though of course that would be a perfect answer, if it's happened.  What I'm also interested in, and suspect is more likely to have occurred, is if anyone's found the criterion useful as a heuristic for checking whether a category is concretisable, in a situation where one wants it to be concrete but finding a suitable functor is not totally trivial.  (I'm imagining a situation similar to the adjoint functor theorems: they give very useful quick heuristics for guessing whether adjoints exist, but if they suggest an adjoint does exist, usually there's an explicit construction as well, so they're used as heuristics much more often than they're formally invoked in print.)
What I'm not so interested in is uses of the criterion to confirm that an expected non-concretisable category is indeed non-concretisable — I'm after cases where it's used in expectation of a positive answer.

A: I did this once with the category of schemes in response to this question, with help from Laurent Moret-Bailly. But then Zhen Lin Low pointed out there's an obvious concretizing functor. Maybe it wasn't so obvious until we were sure it was there, though. So I suppose this falls under the "useful heuristic" category. In practice, the Isbell-Freyd criterion translated the problem into something more concrete (pardon the pun!) which an algebraic geometer had a sense for how to answer. At the time, I didn't know enough algebraic geometry to answer this question on my own, so translating it into more geometric language which I could ask somebody else was an essential step for me.
It helped that, as Ivan Di Liberti points out in the comments, the criterion is especially simple in a finitely-complete category.

A: [Answer converted from a comment by Jiří Rosický on another answer.]
Isbell's criterion is used directly in Libor Barto's paper Accessible set functors are universal (pdf), Section 4, to show that the category of "accessible set functors" (i.e. accessible endofunctors on $\mathrm{Set}$) is concretisable.  A slightly different argument, based on the simpler criterion "regular-well-powered" for the finitely complete case, is used for this same example in Remarks 5.5–6 of Adámek–Rosičký How nice are free completions of categories? (arXiv:1806.02524)

A: An inverse category can be defined as a category where every $f$ admits a unique regular inverse, i.e. a map $g$ such that $fgf=f$ and $gfg=g$. In [1], Kastl proves that any locally small inverse category admits a faithful functor into $PInj$, the category of sets and partial injections. The proof first verifies Isbell's criterion, obtaining a faithful functor to $Set$ and then one proves a general result giving rise to a faithful functor to $PInj$.
[1] J. Kastl. Inverse categories. Studien zur Algebra und ihre Anwendungen, 7:51–
60, 1979.


text:
Q: How can I make a dummy directory tree with dummy files that contain realistic data? I'm looking for preferably a one-liner that drops a directory tree a few layers deep with files that contain "realistic" data, as in, not /dev/zero nor /dev/urandom. Data that noticeably compresses when tar.gz'd.
Is this possible using existing tools or do I have to write my own?


text:
Q: Trinket M0 PWM ValueError: duty_cycle must be between 0 and 65535 inclusive (16 bit resolution) I'm trying to control a servo motor from a Trinket M0. My circuitpython code is:
import time
import board
import pulseio
from adafruit_motor import servo
pwm = pulseio.PWMOut(board.A4, duty_cycle=2 ** 15, frequency=1000)
my_servo = servo.Servo(pwm)
my_servo.angle = 180

But I get a ValueError saying that "PWM duty_cycle must be between 0 and 65535 inclusive (16 bit resolution)."
Full disclosure: this used to work but I accidentally short circuited my wiring by connecting the control wire of the servo to the reset pin of the Trinket M0. Is it possible that this would have damaged the SAMD21 on the M0?


text:
Q: Kamon: Aspectjweaver missing I'm developing a java application with help of akka framework (version 2.3 especially).
And I need to monitor my working actors in runtime. More precisely I need to get actors mailbox size / count of working actors etc.
I choosed Kamon framework and tried to connect it to my application but faced with problem. I did everything according to the documentation.
As they said on their web-site

Add the kamon-jmx dependency to your project and ensure that it is in
  your classpath at runtime, that's it. Kamon's module loader will
  detect that the JMX module is in the classpath and automatically start
  it.

Ok. I added kamon-akka, kamon-jmx, kamon-core  dependencies (all of them are 0.6.7 version), added one line of code in my main method:
public static void main(String[] args) {
    Kamon.start();
    .....
}

I pressed run in my IDE and then I've got this message in my console:
  ___                           _      ___   _    _                                 ___  ___ _            _
 / _ \                         | |    |_  | | |  | |                                |  \/  |(_)          (_)
/ /_\ \ ___  _ __    ___   ___ | |_     | | | |  | |  ___   __ _ __   __ ___  _ __  | .  . | _  ___  ___  _  _ __    __ _
|  _  |/ __|| '_ \  / _ \ / __|| __|    | | | |/\| | / _ \ / _` |\ \ / // _ \| '__| | |\/| || |/ __|/ __|| || '_ \  / _` |
| | | |\__ \| |_) ||  __/| (__ | |_ /\__/ / \  /\  /|  __/| (_| | \ V /|  __/| |    | |  | || |\__ \\__ \| || | | || (_| |
\_| |_/|___/| .__/  \___| \___| \__|\____/   \/  \/  \___| \__,_|  \_/  \___||_|    \_|  |_/|_||___/|___/|_||_| |_| \__, |
            | |                                                                                __/ |
            |_|                                                                                |___/

 It seems like your application was not started with the -javaagent:/path-to-aspectj-weaver.jar option but Kamon detected
 the following modules which require AspectJ to work properly:

      kamon-akka, kamon-scala, kamon-play

 If you need help on setting up the aspectj weaver go to http://kamon.io/introduction/get-started/ for more info. On the
 other hand, if you are sure that you do not need or do not want to use the weaver then you can disable this error message
 by changing the kamon.show-aspectj-missing-warning setting in your configuration file.

I've tried all of the following:

*

*adding kamon-autoweaver to the dependencies section

*passing in the javaagent argument to my application:
java -javaagent:~/.aspectj/aspectj-weaver.jar my-app.jar

But result is the same: AspectJWeaver missing.

A: Solved this problem by changing kamon-akka, kamon-core versions to 0.5.2 and exporting metrics to StatsD instead of JMX.


text:
Q: what is the best project to introduce among 'Google oauth2.0 java client' and 'java-scribe' to provide user logins for facebook/twitter? I am trying to provide additional login mechanisms for our web applications. Currently, it is using the Google accounts login.  I want users to login using facebook/twitter etc.
After searching the group and on the stack overflow, I am thinking, that you can do in the following ways
- Google oauth2.0 java client (https://code.google.com/p/google-oauth-java-client/wiki/OAuth2).  An example of using the DailyMotion oauth2.0 using this jars is found here.
- Use java-scribe. An example is found here https://code.google.com/p/gwtoauthlogindemo/ and here
Any suggestions, what should I choose going forward?

A: I would suggest taking a look at Google Identity Toolkit - this offers more than just Google Accounts:
https://developers.google.com/identity-toolkit/


text:
Q: error in PHP program ,Why don't this correctly run? <select name="filtering">
<option value="a">a</option>
<option value="b">b</option>

if (isset($_POST['filtering']) == "a") {
    $stmt = prepare("SELECT * FROM user_posts ORDER BY post_time DESC LIMIT :limit OFFSET :offset");
}

if (isset($_POST['filtering']) == "b") {
    $stmt = prepare("SELECT * FROM user_posts ORDER BY post_time ASC LIMIT :limit OFFSET :offset");
}

A: Isset will return only true or false
if (isset($_POST['filtering'])&&($_POST['filtering']=="a")){
    $stmt = prepare("SELECT * FROM user_posts ORDER BY post_time DESC LIMIT :limit OFFSET :offset");
}

if (isset($_POST['filtering'])&&($_POST['filtering']=="b")) {
    $stmt = prepare("SELECT * FROM user_posts ORDER BY post_time ASC LIMIT :limit OFFSET :offset");
}


text:
Q: Reading a value of a short from file data I have a file (pointed to by *data) which begins with a struct.
I would like to get to the value of nsectionheaders in memory so that I can use it.
I've tried this, but it's returning a strangely large negative value. How do I get it to return the right value?
   void read_file_header(void *data) {

    int offset = (sizeof(char) * 16) + (sizeof(int) * 4) + sizeof(int) + (sizeof(short) * 6);
    char *pointer = (char *) data + offset;

    short num_sec_headers = 0;
    memcpy(&num_sec_headers, &pointer, sizeof(short));
    printf("The number of headers is %d\n", num_sec_headers);

   }

A: The line
memcpy(&num_sec_headers, &pointer, sizeof(short));

is incorrect. You are taking the address of the pointer, instead of just using pointer:
memcpy(&num_sec_headers, pointer, sizeof(short));

A: You have a secure offsetof in the standard (include stddef.h):
   void read_file_header(void *data) {
       int offset = offsetof(ElfFileHeader, nsectionheaders);
       short num_sec_headers;

       memcpy(&num_sec_headers, (char *)data + offset, sizeof(short));
       printf("The number of headers is %d\n", num_sec_headers);
   }


text:
Q: Selecting rows following a certain flag value in r I have a dataframe consisting of two columns 'group' and 'value'.  I want to select a max of three rows following the value '4' within each group.  If there is fewer than 3 rows before the beginning of the next group then select just 0/1/2 rows.
Ideally I would get some sort of vector of values of 1/0s or True/Falses to indicate whether I selected the row.
Any ideas?
  mydf= structure(list(group = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("a",
 "b"), class = "factor"), value = c(6, 5, 4, 6, 1, 4, 1, 4, 6,
 6, 7, 3, 7, 4, 7, 5, 7, 3, 2, 4)), .Names = c("group", "value"
 ), row.names = c(NA, -20L), class = c("data.table", "data.frame"
  ), .internal.selfref = <pointer: 0x102805578>);
 mydf

A: It would have been better to show the expected result as well.  May be this helps.
 library(data.table)
 mydf[, indx:= cumsum(value==4) , group][, flag:= if (indx!=0) 1:.N %in%
              2:4 else FALSE, list(group, indx)][, indx:=NULL][]
 #   group value  flag
 #1:     a     6 FALSE
 #2:     a     5 FALSE
 #3:     a     4 FALSE
 #4:     a     6  TRUE
 #5:     a     1  TRUE
 #6:     a     4 FALSE
 #7:     a     1  TRUE
 #8:     a     4 FALSE
 #9:     a     6  TRUE
#10:     a     6  TRUE
#11:     b     7 FALSE
#12:     b     3 FALSE
#13:     b     7 FALSE
#14:     b     4 FALSE
#15:     b     7  TRUE
#16:     b     5  TRUE
#17:     b     7  TRUE
#18:     b     3 FALSE
#19:     b     2 FALSE
#20:     b     4 FALSE


text:
Q: Slack API file.upload to a user? I'm trying to follow the tutorial found here https://api.slack.com/methods/files.upload .
curl -F file=@example.txt -F "initial_comment=I play the drums." -F channels=C024BE91L -F thread_ts=1532293503.000001 -H "Authorization: Bearer xoxp-xxxxxxxxx-xxxx" https://slack.com/api/files.upload

I'm able to upload files to a specific channel. However, how do I upload files to a user through direct message?

A: Similar to how sending direct messages work you can simply use the user ID for the channel and the file will be uploaded in a direct message channel between that user and the owner of the token.
Alternatively you can first open a direct message channel from your app with im.open and then use the channel ID of that IM in files.upload.


text:
Q: Cannot start webpack-dev-server - MODULE NOT FOUND (I'm attempting to follow this tutorial)
When I  run npm start I get the following error:
PS C:\Users\user\Desktop\Projects\Websites\project\project> npm start
> PROJECT@0.0.0 start C:\Users\user\Desktop\Projects\Websites\project\project
> webpack-dev-server --config webpack.config.js --open

'find_dp0' is not recognized as an internal or external command,
operable program or batch file.
internal/modules/cjs/loader.js:775
    throw err;
    ^

Error: Cannot find module 'C:\webpack-dev-server\bin\webpack-dev-server.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:772:15)
    at Function.Module._load (internal/modules/cjs/loader.js:677:27)
    at Function.Module.runMain (internal/modules/cjs/loader.js:999:10)
    at internal/main/run_main_module.js:17:11 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}

I think the main issue is that it's looking for the webpack-dev-server module in my C:/ drive since the error is saying:
Error: Cannot find module 'C:\webpack-dev-server\bin\webpack-dev-server.js'

Why would it be looking there for the module and not in the local node_modules folder? This is at least what I think is causing the issue, maybe it is something else though?
I couldn't find this same error online anywhere else (where it was looking in the users C:/ drive). I am working in Visual Studio Community 2019. Any help would be greatly appreciated!
package.json:
{
    "name": "drewpel.com",
    "description": "drewpel.com",
    "author": "James Pelusi",
    "version": "0.0.0",
    "private": true,
    "scripts": {
        "start": "webpack-dev-server --config webpack.config.js --open",
        "test": "echo \"Error: no test script was specified\" && exit 1"
    },
    "dependencies": {
        "express": "4.17.1",
        "morgan": "1.10.0",
        "pug": "3.0.0"
    },
    "devDependencies": {
        "css-loader": "4.2.2",
        "extract-loader": "5.1.0",
        "file-loader": "6.0.0",
        "sass": "1.26.10",
        "sass-loader": "10.0.1",
        "webpack": "4.44.1",
        "webpack-cli": "3.3.12",
        "webpack-dev-server": "3.11.0"
    }
}

webpack.config.js:
module.exports = [{
    entry: './css/index.scss',
    output: {
        // This is necessary for webpack to compile
        // But we never use style-bundle.js
        filename: 'style-bundle.js',
    },
    module: {
        rules: [
            {
                test: /\.scss$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: 'bundle.css',
                        },
                    },
                    { loader: 'extract-loader' },
                    { loader: 'css-loader' },
                    {
                        loader: 'sass-loader',
                        options: {
                            // Prefer Dart Sass
                            implementation: require('sass'),

                            // See https://github.com/webpack-contrib/sass-loader/issues/804
                            webpackImporter: false,
                        },
                    },
                ]
            }
        ]
    },
}];

A: "start": "webpack serve --config webpack.config.js --open"

change the package.json start to this above . I hope it will work


text:
Q: Android Google Gson convert object toJson is null value I am using google gson version 2.4
I have added file gson-2.4.jar to my Android project in Android studio under libs folder. The code build successfully.
My code is as below
class Test{
        private final int id;
        private final String name;
        public Test(){
            id = 1;
            name = "Hello world";
        }
    }
    GsonBuilder gsonBuilder = new GsonBuilder();
    Test test = new Test();
    gsonBuilder.setPrettyPrinting().serializeNulls();
    Gson gson = gsonBuilder.create();

    String json = gson.toJson(test);
    System.out.print(json);

The json is always null value.
My expected result as
{"id":1,"name":"Hello world"}

How can i fix it?
Thanks

A: It looks like you are implementing it in another way as it should...
class Test{
        private final int id;
        private final String name;
        public Test(){
            id = 1;
            name = "Hello world";
        }
    }

public String convertToJson(){
        Gson gson = new Gson();

        return  gson.toJson(this);
}

and this should print out what you are expecting:
{"id":1,"name":"Hello world"}


text:
Q: Trying to create a 2D Array from a custom Object being a Pair class. Won't compile So I am trying to create a 2D array of nodes which are basically 2D plot coordinates. The first column so to speak (ie. [0][0], [1,0] ...) will be the head element wheras all points in the same row following it are successors which link to the first point. From this I am implementing some simple search algorithms. The class I have created (MyPair) simply takes two arguments being aVal, bVal which are both ints. However I don't know how to put these custom objects a 2D array without compilation errors. A snippet of the code follows.
    public class GraphNodes {
public MyPair[][] graphNodes;

public GraphNodes(){
    this.graphNodes = new MyPair[][]
            {{(0,0), (1,0), (0,1)},
            {(0,1), (0,0), (1,1), (0,2)},
            {(0,2), (0,3), (0,1)},
            {(0,3), (0,2), (0,4)},
            {(0,4), (0,3), (0,5)},
            {(0,5), (0,6), (1,5), (0,4)},
            {(0,6), (1,6), (0,5)},
            {(1,0), (0,0), (1,1), (2,0)},
            {(1,1), (1,2), (2,1), (1,0), (0,1)},

I thought doing it this way would work but I am getting an error saying The left-hand side of an assignment must be a variable in eclipse. Any ideas?

A: (0,0) cannot be converted by the compiler to your MyPair class automatically.
You have to invoke a constructor such as new MyPair(0,0) (assuming you have such a constructor).
If you have such a constructor, you can replace any (x,y) in your code with new MyPair(x,y).


text:
Q: linking error while building tbb using mingw and at same time opencv runtime error I want to use MINGW +tbb + opencv When I tried. The problem is I get error while running opencv test or some program.
for example

test_job_automaton.exe - Entry Point Not Found
The procedure entry point __gxx_personality_v0 could not be located in the dynamic link library c:\tbb\build\windows_ia32_gcc_mingw4.9.1_debug\test_job_automaton.exe.

or

LIBFR.exe - Entry Point Not Found
The procedure entry point __gxx_personality_v0 could not be located in the dynamic link library D:\Dropbox\face sdks\QTprojects\build-libfr-Desktop_Qt_5_4_0_MinGW_32bit-Release\release\tbb.dll.

I run this command in tbb dir to build it
mingw32-make arch=ai32 compiler=gcc -j4

it builds 3 dlls ok, also building opencv with these dlls is ok, but running is not
I tried Mingw 4.9.1 and also 4.8.2
I found out that i should try to use g++ instead but for windows it is not supported when I tried it
I also tried to use mingw32 and mingw32-w64
The same error I get when I also try to build rml within tbb, so you do not have to try to install opencv to find out the problem.
To build rml I use this command
mingw32-make arch=ai32 compiler=gcc -j4 rml

I also tried 4 different version of tbb
Any ideas anybody?

A: The absence of __gxx_personality_v0 suggests that (as you mentioned) the program must be linked differently, e.g. via g++ which enables C++ exception handling and links C++ runtime. So the real problem is not with TBB but rather with your inability to use g++. With my installation of MinGW, it works fine. And if you are able to build TBB, it also supposes that g++ works since it is used to build TBB.
For example, you can see how g++ is used when TBB and a test are compiled:
mingw32-make -rj compiler=gcc tbb test_task -C src

Also, I doubt you will ever need RML.
In the case when you really cannot enable RTTI and exception handling, you might experiment with building TBB without exceptions support:
mingw32-make -rj compiler=gcc clean tbb CXXFLAGS=-DTBB_USE_EXCEPTIONS=0

A: The problem was that the installation of GnuPG has also libstdc++-6.dll from different version of mingw, it was automatically added to my path, and make was using this dll instead of the one in the gcc directory, removing it from path made it all work, thank you for help


text:
Q: declaring a string in assembly I have this assembly code that computes some prime numbers:
#include <stdio.h>

int main() {
    char format[] = "%d\t";

    _asm{
        mov ebx, 1000
        mov ecx, 1
        jmp start_while1
incrementare1:
        add ecx, 1
start_while1:
        cmp ecx, ebx
        jge end_while1
        mov edi, 2
        mov esi, 0
        jmp start_while2
incrementare2:
        add edi, 1
start_while2:
        cmp edi, ecx
        jge end_while2
        mov eax, ecx
        xor edx, edx
        div edi
        test edx, edx
        jnz incrementare2
        mov esi, 1
end_while2:
        test esi, esi
        jnz incrementare1
        push ecx
        lea ecx, format
        push ecx
        call printf
        pop ecx
        pop ecx
        jmp incrementare1
end_while1:
        nop
    }
    return 0;
}

It works fine but I would like to also declare the 'format' string in asm, not in C code. I have tried adding something like format db "%d\t", 0 but it didn't work.

A: If all else fails there's always the ugly way:
format_minus_1:
mov ecx,0x00096425  ; '%', 'd', '\t', '\0' in little-endian format
lea ecx,format_minus_1 + 1  ; skip past the "mov ecx" opcode
push ecx
call printf

A: You cannot define objects inside the _asm block with those directives. The C declaration is allocating space on the stack for you so if you want to do something like that inside the _asm block you need to manipulate the stack pointer and initialize the memory yourself:
sub esp, 4
mov [esp], '%'
mov [esp + 1], 'd'
mov [esp + 2], '\t'
mov [esp + 3], '\0'
...
push ecx
push esp + 4
call printf

Note this is one way. Not necessarily the best way. The best way being let C do your memory management for you.


text:
Q: how to use"and" in a list
Glucose lowering agents consist of multiple subcategories of drugs, including metformin, DPP-4 inhibitors, and insulin and analogues.

My question is how should I write a list with an "and" in one of the items? in this example: is "and 'insulin and analogues'" right?


text:
Q: Strava Mobile Application OAuth 2.0 how to handle redirect URL I'm developing an app which use strava API to fetch user details.
Once the user authenticate using strava im getting authorization code in url, but i dont know how to get that code from url   "http://localhost/exchange_token?state=&code=sdfgdfghdfghjdfghjdfghfghjghj&scope=read"
I used
val intentUri = Uri.parse("https://www.strava.com/oauth/mobile/authorize")
.buildUpon()
.appendQueryParameter("client_id", "1234321")
.appendQueryParameter("redirect_uri", "https://www.yourapp.com") .appendQueryParameter("response_type", "code")
.appendQueryParameter("approval_prompt", "auto")
.appendQueryParameter("scope", "activity:write,read")
.build()

 val intent = Intent(Intent.ACTION_VIEW, intentUri)
 startActivity(intent)

this code to launch the auth screen, but i dont know how to get code in call back url in my android app again.
can any one give sample code how to retrieve authorization code from callback url


text:
Q: Toolbar height resets to 44px in landscape after presenting view controller I'm using the method posted here to adjust the size of my toolbar when rotating the device. This works well and it shows the appropriate size including icon size etc.
However, when I present a view controller with [self presentViewController:theViewController animated:YES completion:nil];, the toolbar height gets set back to 44px instead of 32. It's easy to see that the size increase already happens when presenting the view controller as it's already taller during the animation. It also remains tall after dismissing the view controller. The app targets iOS 6. Just in case that might be related.
Is there a way to keep the smaller size in landscape?

A: Reduce your target developement to lower than iOS 6 and it will work. Just a wild guess.:)


text:
Q: Check if email id exist or not I want to check if the mail id exists or not. I tried smtp/helo to the server, but it is not 100% accurate. I want 100% accuracy so the best solution I check online is to send mail to a person, which I am fine with it, but there is one problem: my IP will be blacklisted. Is there any way to send an email without my IP being blacklisted?
I think that if I connect to a VPN and send an email, my IP address will not be blacklisted.
At least I want to verify 200 mail per day
Please share any thoughts you have.


text:
Q: Cannot install pyenchant on OSX I am trying to install pyenchant on OSX snow Leopard.
I have installed enchant via macports and it produced no errors, but when I try to install pyEnchant via setup.py it gives me this error:
OSError: [Errno 2] No such file or directory: './tools/pyenchant-bdist-osx-sources/build/lib'

I cannot find anything on the pyenchant site og google about this error so I turn to you guys.
What can I do to make this work?

A: You could look at the Portfile to see what MacPorts does to make it work.
Why can't you use the MacPorts version?


text:
Q: "concurrently" not working for parent directory client reactjs server "concurrently" not working for parent directory client reactjs server.
concurrently commands are:
"scripts": {
    "client": "cd ../ --prefix client && npm run start",
    "server": "nodemon index.js",
    "dev" : "concurrently \"npm run client\" \"npm run server\" "
  }

Directory structure is
client
server

A: With Your folder structure Try this settings:
"scripts": {
    "start": "node server/index.js",
    "server": "nodemon server/index.js",
    "client": "npm start --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client\"",
  },

And hit npm run dev It should work fine ;-) Remember to install concurrently correct.


text:
Q: Where is it best to put the "when" of a sentence?
*

*John yesterday went to the store to buy eggs.

*John went to the store yesterday to buy eggs.

*John went to the store to buy eggs yesterday.

A: I suggest the reason we usually position adverbial yesterday at the beginning or end of OP's example sentence (whereas we'd put an adverb like willingly immediately before or after the relevant verb went) is because it modifies the entire sentence.
See this earlier ELU answer about the difference between "sentence" and a "manner" adverbs. But at the end of the day it's largely down to individual stylistic choices.


text: Q: How to Run CakePHP 3 Shell in Cpanel Very simple and straightforward question. Yes I've searched and searched, but couldn't find an answer on the internet that works with CakePHP 3. I'm trying to run a CakePHP 3 shell as cron job on cpanel. Can anyone help out please?


text:
Q: How do you change the add button text instead of a The add button that comes as the default for the MasterDetail template in XCode displays a + symbol.  I would rather have the word "Add" instead.  I tried using the following line in the viewDidLoad method:
self.navigationItem.rightBarButtonItem.title = @"Add";
to no avail.

A: This is probably because the bar button that has already been created as UIBarButtonSystemItemAdd like so:
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject:)];

You should rewrite this line to create a bar button item with a title, like this:
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:@"Add" style:UIBarButtonItemStyleBordered target:self action:@selector(insertNewObject:)];

You can find this in the viewDidLoad method of your master view controller.


text:
Q: Using .htaccess to fix multiple broken links in my site I've recently bulk imported 14,000 items into a joomla K2 database and now realised the 'external URL' field required an http:// in front of the URL!  So all the external links on my site are now going to http://www.example.com/www.externalurl.com instead of http://www.externalurl.com
I've worked out that I can probably use the .htaccess file to rewrite the incorrect URLs (which are going to a 404 error page at the moment) but I need a bit of help with the code for doing this.
If anyone can point me in the right direction that would be great - thanks.
Update from comment:
These suggestions unfortunately don't work - I think I should clarify my original question by saying I don't know what the "externalurl" is because it's different on various pages on the site.  I think I need something like this:
RewriteRule ^/www\.([a-zA-Z0-9_-]+)$ www\.$1 [L]

i.e. rewrite www.mywebsite.com/www.externalurl.com to www.externalurl.com
I tried this and it's not having any effect though...
Hope you can help.

A: Try:
RedirectMatch 301 ^/www\.externalurl\.com/?(.*) /$1

A: You are trying to redirect them externally, then the redirect match would be:
RedirectMatch 301 ^/www\.externalurl\.com/?(.*) http://www.externalurl.com/$1

Jon Lin's redirect match will redirect them back to your own site.


text:
Q: Read all child nodes in XML tag I have XML file, for example this:
<?xml version="1.0" encoding="utf-8"?>

<Fields>
    <Field name="rampam" />
    <Field name="rampampam" />
</Fields>

<NotFields>
    <Field name="testName1" />
    <Field name="testName2" />
</NotFields>

and I want to read all Field's attribute value of name  which are under `Fields'. I have tried this code :
static public void getInputFields(
        XmlResourceParser parseXML) throws XmlPullParserException,
        IOException {
    int eventType = -1;

    while (eventType != XmlResourceParser.END_DOCUMENT) {
        if (eventType == XmlResourceParser.START_TAG) {
            if (parseXML.getName().equals("Fields")) {
                parseXML.next();
                while (parseXML.getName().equals("Field")) {

                    String fieldName = parseXML.getAttributeValue(null,
                            "name");

                    parseXML.next();
                }
            }
        }
        eventType = parseXML.next();
    }
}

and it reads first Field but after it gets nulls from getAttributeValue(), what am I missing?
p.s. I'm new in parsing xmls.