text
stringlengths
184
4.48M
/* * Copyright (C) 2004-2006 Alo Sarv <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /** * \file clients.cpp Implementation of clients-related classes */ #include <hncore/ed2k/clients.h> #include <hncore/ed2k/ed2k.h> #include <hncore/ed2k/serverlist.h> #include <hncore/ed2k/creditsdb.h> #include <hncore/ed2k/parser.h> #include <hncore/ed2k/clientext.h> #include <hnbase/lambda_placeholders.h> #include <hnbase/timed_callback.h> #include <hnbase/ssocket.h> #include <hnbase/prefs.h> #include <hncore/metadb.h> #include <hncore/sharedfile.h> #include <hncore/partdata.h> #include <hncore/fileslist.h> #include <hncore/hydranode.h> #include <hncore/hashsetmaker.h> // for ed2khashmaker #include <boost/lambda/bind.hpp> #include <boost/lambda/construct.hpp> namespace Donkey { /** * Here's a collection of things that can be used to tweak the ed2k inter-client * communication procedures. Don't change these unless you know what you'r * doing. Incorrect values here can seriously affect the modules' networking * performance. */ enum Ed2k_ClientConstants { /** * Time between source queue ranking reasks. Ed2K netiquette says that * you shouldn't do reasks more often than once per 30 minutes. Major * clients drop queued clients from uploadqueue when no reask has been * done during 1 hour. UDP reasks should be used when possible, falling * back to TCP only if neccesery. */ SOURCE_REASKTIME = 30*60*1000, /** * UDP reask timeout. How long to wait for response after sending UDP * ReaskFilePing. If two UDP reasks fail, we attempt TCP reask, if that * also fails, drop the client as dead. */ UDP_TIMEOUT = 30000, /** * Specifies the TCP stream socket timeout; when there's no activity * in the socket for this amount of time, the socket connection is * dropped. */ SOCKET_TIMEOUT = 10000, /** * Specifices LowID callback request timeout; if the called client * doesn't respond within this timeframe, the client is considered dead. * * lugdunum servers can delay LowId callbacks up to 12 seconds * internally, in order to group several callback requests, so values * lower than 15 seconds are not recommended. */ CALLBACK_TIMEOUT = 60000, /** * Specifies the TCP connection attempt timeout. */ CONNECT_TIMEOUT = 5000 }; //! Client trace mask const std::string TRACE_CLIENT = "ed2k.client"; const std::string TRACE_SECIDENT = "ed2k.secident"; const std::string TRACE_DEADSRC = "ed2k.deadsource"; const std::string TRACE_SRCEXCH = "ed2k.sourceexchange"; //! UDP Socket for performing Client <-> Client UDP communication ED2KUDPSocket *s_clientUdpSocket = 0; ED2KUDPSocket* Client::getUdpSocket() { return s_clientUdpSocket; } // we allow rewriting existing udp socket as well, e.g. during runtime config // changes void Client::setUdpSocket(ED2KUDPSocket *sock) { s_clientUdpSocket = sock; } namespace Detail { boost::signal<void (Client*, uint32_t)> changeId; boost::signal< bool (const Hash<ED2KHash>&, IPV4Address, IPV4Address, bool) > foundSource; boost::signal<void (IPV4Address)> foundServer; boost::signal<bool (const std::string&)> checkMsgFilter; } // Client class // ------------ IMPLEMENT_EVENT_TABLE(Client, Client*, ClientEvent); // Packet handlers declarations // get-to-know-you chit-chat DECLARE_PACKET_HANDLER(Client, Hello ); DECLARE_PACKET_HANDLER(Client, HelloAnswer ); DECLARE_PACKET_HANDLER(Client, MuleInfo ); DECLARE_PACKET_HANDLER(Client, MuleInfoAnswer ); // uploading/downloading DECLARE_PACKET_HANDLER(Client, ReqFile ); DECLARE_PACKET_HANDLER(Client, SetReqFileId ); DECLARE_PACKET_HANDLER(Client, ReqHashSet ); DECLARE_PACKET_HANDLER(Client, StartUploadReq ); DECLARE_PACKET_HANDLER(Client, ReqChunks ); DECLARE_PACKET_HANDLER(Client, CancelTransfer ); DECLARE_PACKET_HANDLER(Client, FileName ); DECLARE_PACKET_HANDLER(Client, FileDesc ); DECLARE_PACKET_HANDLER(Client, FileStatus ); DECLARE_PACKET_HANDLER(Client, NoFile ); DECLARE_PACKET_HANDLER(Client, HashSet ); DECLARE_PACKET_HANDLER(Client, AcceptUploadReq); DECLARE_PACKET_HANDLER(Client, QueueRanking ); DECLARE_PACKET_HANDLER(Client, MuleQueueRank ); DECLARE_PACKET_HANDLER(Client, DataChunk ); DECLARE_PACKET_HANDLER(Client, PackedChunk ); // source exchange DECLARE_PACKET_HANDLER(Client, SourceExchReq ); DECLARE_PACKET_HANDLER(Client, AnswerSources ); DECLARE_PACKET_HANDLER(Client, AnswerSources2 ); // misc DECLARE_PACKET_HANDLER(Client, Message ); DECLARE_PACKET_HANDLER(Client, ChangeId ); // secident DECLARE_PACKET_HANDLER(Client, SecIdentState ); DECLARE_PACKET_HANDLER(Client, PublicKey ); DECLARE_PACKET_HANDLER(Client, Signature ); // Constructor Client::Client(ED2KClientSocket *c) : BaseClient(&ED2K::instance()), m_id(), m_tcpPort(), m_udpPort(), m_features(), m_clientSoft(), m_sessionUp(), m_sessionDown(), m_parser(new ED2KParser<Client>(this)), m_socket(c), m_credits(), m_callbackInProgress(false),m_reaskInProgress(false), m_failedUdpReasks(), m_lastReaskTime(), m_lastReaskId(), m_sentChallenge(), m_reqChallenge(), m_upReqInProgress(), m_dnReqInProgress() { CHECK_THROW(c); CHECK_THROW(c->isConnected() || c->isConnecting()); m_sessionState.reset(new SessionState); m_id = c->getPeer().getAddr(); m_tcpPort = c->getPeer().getPort(); setConnected(true); c->setHandler(this, &Client::onSocketEvent); m_parser->parse(c->getData()); } Client::Client(IPV4Address addr, Download *file):BaseClient(&ED2K::instance()), m_id(addr.getAddr()), m_tcpPort(addr.getPort()), m_udpPort(), m_features(), m_clientSoft(), m_sessionUp(), m_sessionDown(), m_parser(new ED2KParser<Client>(this)), m_socket(),m_credits(), m_callbackInProgress(false), m_reaskInProgress(false), m_failedUdpReasks(), m_lastReaskTime(), m_lastReaskId(), m_sentChallenge(), m_reqChallenge(), m_upReqInProgress(), m_dnReqInProgress() { addOffered(file, false); // don't connect right away } Client::~Client() { getEventTable().delHandlers(this); delete m_socket; } void Client::destroy() { getEventTable().postEvent(this, EVT_DESTROY); if (m_socket) try { m_socket->disconnect(); } catch (...) {} delete m_socket; m_socket = 0; m_downloadInfo.reset(); m_queueInfo.reset(); m_sourceInfo.reset(); m_uploadInfo.reset(); } void Client::checkDestroy() { if (!m_sourceInfo && !m_downloadInfo && !m_queueInfo && !m_uploadInfo) { destroy(); } } std::string Client::getIpPort() const { boost::format fmt("%s:%s"); if (isHighId()) { fmt % Socket::getAddr(getId()); } else { fmt % boost::lexical_cast<std::string>(getId()); } fmt % getTcpPort(); return fmt.str(); } /** * Attempt to establish connection with the remote client. If the remote client * is LowID, we will request a callback via server (but only if we are connected * to a server, and the remote client is on same server as we are). If the * remote client is HighID, we attempt to connect it directly. If anything * goes wrong, std::runtime_error will be thrown. * * If this method is called and socket already exists, it silently returns. The * reason for not throwing exceptions on that case is that there's a lot of race * conditions floating around regarding re-establishing connections. While some * of them are internal, and could (should) be fixed, many of them are inherent * from remote client's bad protocol usage, and it is nearly impossible to * handle all cases correctly. */ void Client::establishConnection() try { if (m_socket) { return; // silently ignored } if (isLowId() && ED2K::instance().isLowId()) { logTrace(TRACE_DEADSRC, boost::format( "[%s] Unable to perform LowID <-> " "LowID callback." ) % getIpPort() ); destroy(); } else if (isHighId()) { // highid logTrace( TRACE_CLIENT, boost::format("[%s] Connecting...") % getIpPort() ); m_socket = new ED2KClientSocket(); m_socket->setHandler(this, &Client::onSocketEvent); IPV4Address addr(m_id, m_tcpPort); m_socket->connect(addr, CONNECT_TIMEOUT); // avoids race condition when reaskForDownload is called // when socket is connected, but SOCK_CONNECTED event hasn't // arrived yet. m_sessionState.reset(new SessionState); } else { IPV4Address curServ = ServerList::instance().getCurServerAddr(); if (m_serverAddr && m_serverAddr != curServ) { logTrace(TRACE_DEADSRC, boost::format( "[%s] We are on server %s, client is " "on server %s; dropping." ) % getIpPort() % curServ % m_serverAddr ); destroy(); return; } logTrace(TRACE_CLIENT, boost::format("[%s] %p: Performing LowID callback...") % getIpPort() % this ); ServerList::instance().reqCallback(m_id); getEventTable().postEvent( this, EVT_CALLBACK_T, CALLBACK_TIMEOUT ); m_callbackInProgress = true; } } catch (std::exception &e) { (void)e; logTrace( TRACE_DEADSRC, boost::format( "[%s] Error performing LowID callback: %s" ) % getIpPort() % e.what() ); destroy(); } MSVC_ONLY(;) // Add an offered file. This is the public accessor and really forwards the // call to DownloadInfo sub-object (constructing it if neccesery). // doConn variable allows delaying connection attempt for later void Client::addOffered(Download *file, bool doConn) { if (!m_sourceInfo) { logTrace(TRACE_CLIENT, boost::format("[%s] %p: Creating new SourceInfo") % getIpPort() % this ); m_sourceInfo.reset(new Detail::SourceInfo(this, file)); if (isConnected() && !m_downloadInfo) { reqDownload(); } else if (!m_socket && doConn) { establishConnection(); } } else { logTrace(TRACE_CLIENT, boost::format("[%s] %p: Adding offered file.") % getIpPort() % this ); m_sourceInfo->addOffered(file); } } void Client::remOffered(Download *file, bool cleanUp) { CHECK_THROW(file); if (m_sourceInfo) { m_sourceInfo->remOffered(file, cleanUp); if (!m_sourceInfo->getOffCount()) { logTrace( TRACE_CLIENT, boost::format( "[%s] Removed last offered file %s" ) % getIpPort() % file->getPartData()->getDestination().leaf() ); m_sourceInfo.reset(); m_lastReaskTime = 0; } else { logTrace( TRACE_CLIENT, boost::format("[%s] Removed offered file %s") % getIpPort() % file->getPartData()->getDestination().leaf() ); } } if (m_downloadInfo) { if (m_downloadInfo->getReqPD() == file->getPartData()) { m_downloadInfo.reset(); } } checkDestroy(); } // merge all the information that we need from the other client. Keep in mind // that the other client will be deleted shortly after this function is called // by clientlist, so we must take everything we need from that client. void Client::merge(Client *c) { CHECK_THROW(c != this); if (m_socket && c->m_socket) { throw std::runtime_error("Client is already connected!"); } else if (c->m_socket && !m_socket) { m_socket = c->m_socket; m_socket->setHandler(this, &Client::onSocketEvent); c->m_socket = 0; c->setConnected(false); m_sessionState = c->m_sessionState; } m_parser = c->m_parser; m_parser->setParent(this); if (c->m_queueInfo && !m_queueInfo) { m_queueInfo = c->m_queueInfo; m_queueInfo->setParent(this); } if (c->m_sourceInfo && !m_sourceInfo) { m_sourceInfo = c->m_sourceInfo; m_sourceInfo->setParent(this); } if (c->m_uploadInfo && !m_uploadInfo) { m_uploadInfo = c->m_uploadInfo; m_uploadInfo->setParent(this); } if (c->m_downloadInfo && !m_downloadInfo) { m_downloadInfo = c->m_downloadInfo; m_downloadInfo->setParent(this); } if (c->m_hash && !m_hash) { m_hash = c->m_hash; } if (c->m_udpPort && !m_udpPort) { m_udpPort = c->m_udpPort; } if (c->m_pubKey && !m_pubKey) { m_pubKey = c->m_pubKey; } if (c->m_serverAddr && !m_serverAddr) { m_serverAddr = c->m_serverAddr; } if (c->m_nick.size() && !m_nick.size()) { m_nick = c->m_nick; } if (c->m_clientSoft && !m_clientSoft) { m_clientSoft = c->m_clientSoft; } if (c->m_credits && !m_credits) { m_credits = c->m_credits; } if (c->m_lastReaskTime && !m_lastReaskTime) { m_lastReaskTime = c->m_lastReaskTime; } if (c->m_sentChallenge && !m_sentChallenge) { m_sentChallenge = c->m_sentChallenge; } if (c->m_reqChallenge && !m_reqChallenge) { m_reqChallenge = c->m_reqChallenge; } if (m_callbackInProgress) { logTrace(TRACE_CLIENT, boost::format("[%s] %p: LowID callback succeeded.") % getIpPort() % this ); m_callbackInProgress = false; } if (m_socket && m_socket->isConnected()) { setConnected(true); } } // Event handler for socket events. // note that due to changeId() signal handlers, we might be deleted when // returning from parser, so do NOT do anything in this function after returning // from parse(), since we might have been deleted. void Client::onSocketEvent(ED2KClientSocket *c, SocketEvent evt) { assert(m_socket); assert(c == m_socket); // 2 minutes timeout when transfer is in progress, since emule often // sets clients in "stalled" transfer, however gaining an upload slot // in ed2k is so damn time-consuming that we really want to give the // remote client more chances to send stuff before we give up on it. // 2 minutes timeout when transfer is in progress ought to be enough. if (m_uploadInfo || m_downloadInfo) { m_socket->setTimeout(120000); } else { m_socket->setTimeout(SOCKET_TIMEOUT); } if (evt == SOCK_READ) try { m_parser->parse(c->getData()); } catch (std::exception &er) { logTrace(TRACE_DEADSRC, boost::format( "[%s] Destroying client: error during client " "stream parsing/handling: %s" ) % getIpPort() % er.what() ); destroy(); } else if (evt == SOCK_WRITE && m_uploadInfo) { sendNextChunk(); } else if (evt == SOCK_CONNECTED) { logTrace(TRACE_CLIENT, boost::format( "[%s] Connection established, sending Hello" ) % getIpPort() ); *m_socket << ED2KPacket::Hello(); m_failedUdpReasks = 0; m_upReqInProgress = false; m_dnReqInProgress = m_sourceInfo ? true : false; setConnected(true); m_sessionState.reset(new SessionState); m_sessionState->m_sentHello = true; } else if (evt == SOCK_CONNFAILED) { logTrace( TRACE_DEADSRC, boost::format( "[%s] Dropping client (unable to connect)" ) % getIpPort() ); destroy(); } else if (evt == SOCK_TIMEOUT) { logTrace(TRACE_CLIENT, boost::format("[%s] Connection timed out.") % getIpPort() ); onLostConnection(); } else if (evt == SOCK_LOST) { logTrace(TRACE_CLIENT, boost::format("[%s] Connection lost.") % getIpPort() ); onLostConnection(); } else if (evt == SOCK_ERR) { logTrace(TRACE_CLIENT, boost::format( "[%s] Connection lost (socket error)." ) % getIpPort() ); onLostConnection(); } } void Client::onLostConnection() { if (m_socket) { m_sessionUp += m_socket->getUploaded(); m_sessionDown += m_socket->getDownloaded(); } setConnected(false); delete m_socket; m_socket = 0; m_sentChallenge = 0; m_reqChallenge = 0; if (!m_queueInfo && m_sourceInfo && !m_lastReaskTime) { logTrace(TRACE_DEADSRC, boost::format( "[%s] Destroying client: Source, but " "never connected." ) % getIpPort() ); destroy(); } else if (!m_sourceInfo && !m_queueInfo) { logTrace(TRACE_DEADSRC, boost::format( "[%s] Destroying client: TCP connection" " lost/failed, and no src/queue info is" " available." ) % getIpPort() ); destroy(); } else if (m_failedUdpReasks > 2) { logTrace(TRACE_DEADSRC, boost::format( "[%s] Destroying client: 3 UDP Reasks " "failed, and TCP Reask also failed." ) % getIpPort() ); destroy(); } else if (m_downloadInfo || (m_sourceInfo && m_dnReqInProgress)) { // handles two cases: when socket timeouts while downloading, // and when download request was sent, but no answer received getEventTable().postEvent( this, EVT_REASKFILEPING, SOURCE_REASKTIME ); m_lastReaskTime = EventMain::instance().getTick(); } else if (m_uploadInfo) { if (!m_queueInfo) { m_queueInfo.reset( new Detail::QueueInfo(this, m_uploadInfo) ); } getEventTable().postEvent(this, EVT_UPLOADREQ); } else if ( m_sourceInfo && m_sessionState && !m_sessionState->m_sentReq && !m_queueInfo ) { logTrace(TRACE_DEADSRC, boost::format( "[%s] Destroying client: is source, but file " "request could not be sent this session." ) % getIpPort() ); destroy(); } else if (m_sessionState && !m_sessionState->m_gotHello) { logTrace(TRACE_DEADSRC, boost::format( "[%s] Destroying client: connection lost " "before completing handshake." ) % getIpPort() ); destroy(); } m_upReqInProgress = false; m_dnReqInProgress = false; m_downloadInfo.reset(); m_uploadInfo.reset(); m_sessionState.reset(); } // Get to know you chit chat // ------------------------- // Before we can do anything other useful things with the remote client, we // must first get to know him/her and also introduce ourselves. We do it by // saying Hello, and expecting HelloAnswer. Alternatively, if he/she said // Hello to us, we politely respond with HelloAnswer. // // There are rumors about some old mules walking around the network, using some // odd mule-language. Newer-generation mules have learned english, and no longer // require the usage of mule-language, however, for old-generation mules, we // must speak their language, and thus also say MuleInfo and/or MuleInfoAnswer. // // Stores client info found in packet internally. This is used as helper // method by Hello/HelloAnswer packet handler void Client::storeInfo(const ED2KPacket::Hello &p) { m_tcpPort = p.getClientAddr().getPort(); m_udpPort = p.getUdpPort(); m_features = p.getFeatures(); m_hash = p.getHash(); m_serverAddr = p.getServerAddr(); m_nick = p.getNick(); if (getClientSoft() != CS_MLDONKEY_NEW2) { // new mldonkeys send muleinfo with mldonkey info, and THEN // hello with ID 0x00 (emule) - this check detects it. m_clientSoft = p.getMuleVer(); } if (!m_clientSoft) { m_clientSoft |= p.getVersion() << 24; } logTrace(TRACE_CLIENT, boost::format( "[%s] (Hello) ClientSoftware is " COL_BBLUE "%s" COL_BGREEN " %s" COL_NONE ) % getIpPort() % getSoft() % getSoftVersion() ); logTrace(TRACE_CLIENT, boost::format("[%s] (Hello) Nick: %s Userhash: %s UDPPort: %d") % getIpPort() % m_nick % m_hash.decode() % m_udpPort ); std::string msg("[" + getIpPort() + "] (Hello) Features: "); if (supportsPreview()) msg += "Preview "; if (supportsMultiPacket()) msg += "MultiPacket "; if (supportsViewShared()) msg += "ViewShared "; if (supportsPeerCache()) msg += "PeerCache "; if (supportsUnicode()) msg += "Unicode "; if (getCommentVer()) { msg += (boost::format("Commentv%d ") % static_cast<int>(getCommentVer())).str(); } if (getExtReqVer()) { msg += (boost::format("ExtReqv%d ") % static_cast<int>(getExtReqVer())).str(); } if (getSrcExchVer()) { msg += (boost::format("SrcExchv%d ") % static_cast<int>(getSrcExchVer())).str(); } if (getSecIdentVer()) { msg += (boost::format("SecIdentv%d ") % static_cast<int>(getSecIdentVer())).str(); } if (getComprVer()) { msg += (boost::format("Comprv%d ") % static_cast<int>(getComprVer())).str(); } if (getUdpVer()) { msg += (boost::format("Udpv%d ") % static_cast<int>(getUdpVer())).str(); } if (getAICHVer()) { msg += (boost::format("AICHv%d ") % static_cast<int>(getAICHVer())).str(); } logTrace(TRACE_CLIENT, msg); Detail::changeId(this, p.getClientAddr().getAddr()); } std::string Client::getSoft() const { switch (m_clientSoft >> 24) { case CS_EMULE: return "eMule"; case CS_CDONKEY: return "cDonkey"; case CS_LXMULE: return "(l/x)mule"; case CS_AMULE: return "aMule"; case CS_SHAREAZA: case CS_SHAREAZA_NEW: return "Shareaza"; case CS_EMULEPLUS: return "eMulePlus"; case CS_HYDRANODE: return "Hydranode"; case CS_MLDONKEY_NEW2: return "MLDonkey"; case CS_LPHANT: return "lphant"; case CS_HYBRID: return "eDonkeyHybrid"; case CS_DONKEY: return "eDonkey"; case CS_MLDONKEY: return "OldMLDonkey"; case CS_OLDEMULE: return "OldeMule"; case CS_MLDONKEY_NEW: return "MLDonkey"; case CS_UNKNOWN: default: return ( boost::format("Unknown %s") % Utils::hexDump(m_clientSoft >> 24) ).str(); } } std::string Client::getSoftVersion() const { std::string ret; if (getClientSoft() == CS_EMULE) { ret += "0."; ret += boost::lexical_cast<std::string>(getVerMin()); ret += static_cast<uint8_t>(getVerPch() + 0x61); } else { boost::format fmt("%d.%d.%d-%d"); fmt % getVerMjr() % getVerMin() % getVerPch() % getVerBld(); ret += fmt.str(); } return ret; } // base class virtuals // ------------------- IPV4Address Client::getAddr() const { if (m_socket) { return m_socket->getPeer(); } else if (isHighId()) { return IPV4Address(m_id, m_tcpPort); } else { return IPV4Address(); } } std::string Client::getNick() const { return m_nick; } uint64_t Client::getSessionUploaded() const { if (m_socket) { return m_sessionUp + m_socket->getUploaded(); } else { return m_sessionUp; } } uint64_t Client::getSessionDownloaded() const { if (m_socket) { return m_sessionDown + m_socket->getDownloaded(); } else { return m_sessionDown; } } uint64_t Client::getTotalUploaded() const { return m_credits ? m_credits->getUploaded() : m_sessionUp; } uint64_t Client::getTotalDownloaded() const { return m_credits ? m_credits->getDownloaded() : m_sessionDown; } uint32_t Client::getUploadSpeed() const { return m_socket ? m_socket->getUpSpeed() : 0; } uint32_t Client::getDownloadSpeed() const { return m_socket ? m_socket->getDownSpeed() : 0; } uint32_t Client::getQueueRanking() const { return m_queueInfo ? m_queueInfo->getQR() : 0; } uint32_t Client::getRemoteQR() const { return m_sourceInfo ? m_sourceInfo->getQR() : 0; } bool Client::isMule() const { if (getClientSoft() == CS_EMULE && m_hash) { return m_hash.getData()[5] == 14 && m_hash.getData()[14] == 111; } else { return false; } } // Hi there little one void Client::onPacket(const ED2KPacket::Hello &p) { CHECK_THROW(m_socket); *m_socket << ED2KPacket::HelloAnswer(); if (isMule() && getVerMin() < 43) { logTrace(TRACE_CLIENT, "Old eMule detected, sending MuleInfo."); // eMule (old) extended protocol - also send MuleInfo *m_socket << ED2KPacket::MuleInfo(); } CHECK_THROW(m_sessionState); m_sessionState->m_gotHello = true; m_sessionState->m_sentHello = true; storeInfo(p); } // Nice to meet you too void Client::onPacket(const ED2KPacket::HelloAnswer &p) { logTrace(TRACE_CLIENT, boost::format("[%s] Received HelloAnswer.") % getIpPort() ); CHECK_THROW(m_sessionState); m_sessionState->m_gotHello = true; storeInfo(p); } void Client::onPacket(const ED2KPacket::MuleInfo &p) { logTrace(TRACE_CLIENT, boost::format("[%s] Received MuleInfo.") % getIpPort() ); processMuleInfo(p); CHECK_THROW(m_socket); *m_socket << ED2KPacket::MuleInfoAnswer(); } // the old extinct mule language void Client::onPacket(const ED2KPacket::MuleInfoAnswer &p) { logTrace(TRACE_CLIENT, boost::format("[%s] Received MuleInfoAnswer") % getIpPort() ); processMuleInfo(p); } void Client::processMuleInfo(const ED2KPacket::MuleInfo &p) { m_clientSoft |= p.getCompatCliID() << 24; // compat client id m_clientSoft |= (p.getVersion() + 8) << 10; // minor version, in hex logTrace(TRACE_CLIENT, boost::format("[%s] %s %s using old eMule protocol.") % getIpPort() % getSoft() % getSoftVersion() ); if (isMule() && getVerMin() < 42) { handshakeCompleted(); } } // Upload requests // --------------- // Here we go again. Just as we arrived on the net, ppl start wanting something // from us. Can't they just leave us alone and stop wanting every last bit of // our preciousssss files? *sigh* // // Well, here goes. // He/she wants a file. "Ask, and thou shall receive." void Client::onPacket(const ED2KPacket::ReqFile &p) { CHECK_THROW(isConnected()); using boost::signals::connection; logTrace(TRACE_CLIENT, boost::format("[%s] Received ReqFile for %s") % getIpPort() % p.getHash().decode() ); SharedFile *sf = MetaDb::instance().findSharedFile(p.getHash()); if (sf) { *m_socket << ED2KPacket::FileName(p.getHash(), sf->getName()); m_upReqInProgress = true; if (sf->isPartial() && !m_sourceInfo) { logTrace(TRACE_CLIENT, boost::format( "[%s] Passivly adding source " "and sending ReqFile." ) % getIpPort() ); Download *file = 0; file = DownloadList::instance().find(p.getHash()); CHECK_THROW(file); m_sourceInfo.reset(new Detail::SourceInfo(this, file)); reqDownload(); } } else { *m_socket << ED2KPacket::NoFile(p.getHash()); logTrace(TRACE_CLIENT, boost::format( "[%s] Sending NoFile for hash %s" ) % getIpPort() % p.getHash().decode() ); } } // Seems he/she is confident in his/her wishes. Well, can't argue there. // Confidence is a virtue :) void Client::onPacket(const ED2KPacket::SetReqFileId &p) { CHECK_THROW(isConnected()); SharedFile *sf = MetaDb::instance().findSharedFile(p.getHash()); if (sf) { logTrace(TRACE_CLIENT, boost::format("[%s] Received SetReqFileId for %s") % getIpPort() % sf->getName() ); *m_socket << ED2KPacket::FileStatus( p.getHash(), sf->getPartData() ); if (m_uploadInfo) { if (m_uploadInfo->getReqChunkCount()) { logTrace(TRACE_CLIENT, boost::format( "[%s] Cannot SetReqFileId " "after ReqChunks!" ) % getIpPort() ); return; } else { m_uploadInfo->setReqFile(sf); } } else if (m_queueInfo) { m_queueInfo->setReqFile(sf, p.getHash()); } else { m_queueInfo.reset( new Detail::QueueInfo(this, sf, p.getHash()) ); m_queueInfo->m_lastQueueReask = Utils::getTick(); m_uploadInfo.reset(); getEventTable().postEvent(this, EVT_UPLOADREQ); } } else { *m_socket << ED2KPacket::NoFile(p.getHash()); logTrace(TRACE_CLIENT, boost::format( "[%s] Received request for unknown file %s" ) % getIpPort() % p.getHash().decode() ); } } // So, seems they'r really sure they want this file. Ohwell, let's see what // we can do. But wait - we can't do anything yet - we need to ask permission // from our parent first. More on this later... // // PS: Rumors say some mules starting with A letter want to start upload before // actually saying what they want in setreqfileid. Poor bastards, but // we must serve all equally, so try to work around it and grant the request // anyway, if we have enough information at this point. void Client::onPacket(const ED2KPacket::StartUploadReq &p) { logTrace(TRACE_CLIENT, boost::format("[%s] Received StartUploadReq.") % getIpPort() ); onUploadReq(p.getHash()); } // handles upload requests void Client::onUploadReq(Hash<ED2KHash> hash) { if (!hash && !m_uploadInfo && !m_queueInfo) { return; // not enough info to do anything with this request } SharedFile *sf = 0; if (!hash && m_uploadInfo) { hash = m_uploadInfo->getReqHash(); sf = m_uploadInfo->getReqFile(); } else if (!hash && m_queueInfo) { hash = m_queueInfo->getReqHash(); sf = m_queueInfo->getReqFile(); } if (hash && !sf) { sf = MetaDb::instance().findSharedFile(hash); } if (!hash || !sf) { logTrace( TRACE_CLIENT, boost::format( "[%s] Received upload request, but for what?" ) % getIpPort() ); return; } if (m_uploadInfo) { m_uploadInfo->setReqFile(sf); m_uploadInfo->setReqHash(hash); startUpload(); } else if (m_queueInfo) { m_queueInfo->setReqFile(sf, hash); m_queueInfo->m_lastQueueReask = Utils::getTick(); getEventTable().postEvent(this, EVT_UPLOADREQ); } else { m_queueInfo.reset(new Detail::QueueInfo(this, sf, hash)); m_queueInfo->m_lastQueueReask = Utils::getTick(); getEventTable().postEvent(this, EVT_UPLOADREQ); } } // So, they want to know the entire hashset of the file? Interesting concept. // Do we have the hashset? Do WE actually know what we are sharing? Might not // always be the case, if we don't have the file ourselves yet, or something // else is wrong. On the other hand, if we have even few bytes of the file, // and thus are sharing it, then we should have the hashset of it anyway, since // we ask for a hashset ourselves first time we start a download. So we can // be pretty sure we know the hashset of the file we'r sharing at this point. void Client::onPacket(const ED2KPacket::ReqHashSet &p) { logTrace(TRACE_CLIENT, boost::format("[%s] Received ReqHashSet for %s") % getIpPort() % p.getHash().decode() ); MetaData *md = MetaDb::instance().find(p.getHash()); if (md == 0) { return; // ignored } HashSetBase *hs = 0; for (uint32_t i = 0; i < md->getHashSetCount(); ++i) { hs = md->getHashSet(i); if (hs->getFileHashTypeId() == CGComm::OP_HT_ED2K) { break; } } if (hs == 0) { return; // ignored } ED2KHashSet *ehs = dynamic_cast<ED2KHashSet*>(hs); if (!ehs) { logDebug("Internal type error upcasting HashSetBase."); return; } CHECK_THROW(m_socket); *m_socket << ED2KPacket::HashSet(ehs); } // Actual uploading // ---------------- // Well, this is fun. We wait for chunk requests, once those arrive, we send // those chunks, and so on and so forth, until we run out of chunks. But in // reality, they never stop sending chunk requests, so at some point we'll have // to pull the plug. When exactly we do it is up to us - I guess we'll just // treat all the same and kick 'em after few MB's or so. // Initialize upload sequence. This is done by sending AcceptUploadReq packet // to the remote client. If we already have requested chunks list at this point, // we can start sending data right away. However, some clients seem request // chunks only AFTER receiving AcceptUploadReq packet, so in that case, the // data sending is delayed until we receive the chunk request. void Client::startUpload() { if (!m_uploadInfo) { m_uploadInfo.reset(new Detail::UploadInfo(this, m_queueInfo)); } if (m_queueInfo) { m_queueInfo.reset(); } if (isConnected()) { logTrace(TRACE_CLIENT, boost::format("[%s] Starting upload.") % getIpPort() ); *m_socket << ED2KPacket::AcceptUploadReq(); m_uploadInfo->connectSpeeder(); if (m_uploadInfo->getReqChunkCount()) { sendNextChunk(); } else { logTrace(TRACE_CLIENT, boost::format( "[%s] Waiting for chunk requests." ) % getIpPort()); } } else try { establishConnection(); } catch (std::exception &e) { (void)e; logTrace(TRACE_DEADSRC, boost::format("[%s] Unable to connect to client: %s") % getIpPort() % e.what() ); destroy(); } } // You are #X on my queue. Please stay calm and wait your turn, it'll come // (eventually anyway). void Client::sendQR() { CHECK_THROW(isConnected()); CHECK_THROW(m_queueInfo); CHECK_THROW(m_queueInfo->getQR()); CHECK_THROW(!m_uploadInfo); logTrace(TRACE_CLIENT, boost::format("[%s] Sending QueueRanking %d.") % getIpPort() % m_queueInfo->getQR() ); if (isMule()) { *m_socket << ED2KPacket::MuleQueueRank(m_queueInfo->getQR()); } else { *m_socket << ED2KPacket::QueueRanking(m_queueInfo->getQR()); } m_upReqInProgress = false; } void Client::disconnect() { if (m_socket) { m_socket->disconnect(); delete m_socket; m_socket = 0; } onLostConnection(); } // More work? work work. void Client::onPacket(const ED2KPacket::ReqChunks &p) { CHECK_THROW(m_uploadInfo); CHECK_THROW(isConnected()); for (uint8_t i = 0; i < p.getReqChunkCount(); ++i) { m_uploadInfo->addReqChunk(p.getReqChunk(i)); } sendNextChunk(); } // Send next requested chunk to client. // // We send data in 10k chunks, in the order of which they were requested. void Client::sendNextChunk() try { CHECK_THROW(m_uploadInfo); CHECK_THROW(!m_queueInfo); CHECK_THROW(isConnected()); if (!m_uploadInfo->getReqChunkCount()) { if (!m_uploadInfo->getSent()) { return; } logTrace(TRACE_CLIENT, boost::format("[%s] No more reqchunks.") % getIpPort() ); m_uploadInfo.reset(); getEventTable().postEvent(this, EVT_CANCEL_UPLOADREQ); m_queueInfo.reset(); if (!m_downloadInfo) { disconnect(); } if (!m_sourceInfo) { logTrace(TRACE_DEADSRC, boost::format( "[%s] Destroying client: No more requested " "chunks for uploading, and no source " "information.") % getIpPort() ); destroy(); } return; } if (!m_credits && m_pubKey) { m_credits = CreditsDb::instance().create(m_pubKey, m_hash); } logTrace(TRACE_CLIENT, boost::format( COL_SEND "[%s] Uploading file %s%s, total sent %s" COL_NONE ) % getIpPort() % m_uploadInfo->getReqFile()->getName() % (m_uploadInfo->isCompressed() ? COL_COMP " (compressed)" COL_SEND : "" ) % Utils::bytesToString(m_uploadInfo->getSent()) ); if (!m_uploadInfo->hasBuffered()) try { m_uploadInfo->bufferData(); // if (getComprVer()) { // m_uploadInfo->compress(); // } } catch (SharedFile::ReadError &e) { if (e.reason() == SharedFile::ETRY_AGAIN_LATER) { Utils::timedCallback( boost::bind(&Client::sendNextChunk, this), 3000 ); return; } else { throw; } } boost::tuple<uint32_t, uint32_t, std::string> nextChunk; nextChunk = m_uploadInfo->getNext(10240); // if (getComprVer() && m_uploadInfo->isCompressed()) { // *m_socket << ED2KPacket::PackedChunk( // m_uploadInfo->getReqHash(), nextChunk.get<0>(), // nextChunk.get<1>(), nextChunk.get<2>() // ); // } else { *m_socket << ED2KPacket::DataChunk( m_uploadInfo->getReqHash(), nextChunk.get<0>(), nextChunk.get<1>(), nextChunk.get<2>() ); // } if (m_credits) { m_credits->addUploaded(nextChunk.get<2>().size()); } m_uploadInfo->getReqFile()->addUploaded(nextChunk.get<2>().size()); } catch (std::exception &e) { logDebug( boost::format("[%s] Sending next chunk to ed2kclient: %s") % getIpPort() % e.what() ); if (m_uploadInfo) { m_queueInfo.reset(new Detail::QueueInfo(this, m_uploadInfo)); m_queueInfo->m_lastQueueReask = Utils::getTick(); m_uploadInfo.reset(); getEventTable().postEvent(this, EVT_UPLOADREQ); } else { checkDestroy(); } } MSVC_ONLY(;) // No more? No less. Was a bad file anyway. void Client::onPacket(const ED2KPacket::CancelTransfer &) { logTrace(TRACE_CLIENT, boost::format("[%s] Received CancelTransfer.") % getIpPort() ); m_uploadInfo.reset(); m_queueInfo.reset(); if (!m_sourceInfo) { logTrace(TRACE_DEADSRC, boost::format( "[%s] Destroying client: Received CancelTransfer, and " "no sourceinfo is available.") % getIpPort() ); destroy(); } else { getEventTable().postEvent(this, EVT_CANCEL_UPLOADREQ); } } // Downloading // ----------- // Enough of serving others. Time to get something for ourselves too, right? // Let's get started right away. Let's see what can they tell us. // Oh? A filename? Riiight, very useful. Stuff it somewhere and get over it. void Client::onPacket(const ED2KPacket::FileName &p) { logTrace(TRACE_CLIENT, boost::format("[%s] Received FileName for hash %s: %s.") % getIpPort() % p.getHash().decode() % p.getName() ); if (!m_sourceInfo) { Download *d = DownloadList::instance().find(p.getHash()); if (d) { addOffered(d, false); } } if (!m_sourceInfo) { // happens when addOffered() discovers we don't need the file // from the client afterall. Just ignore it then. return; } CHECK_THROW(isConnected()); CHECK_THROW(m_sourceInfo); Download *d = m_sourceInfo->getReqFile(); MetaData *md = d->getPartData()->getMetaData(); if (md) { m_sourceInfo->addFileName(md, p.getName()); } logTrace(TRACE_CLIENT, boost::format("[%s] Sending SetReqFileId for hash %s") % getIpPort() % m_sourceInfo->getReqFile()->getHash().decode() ); *m_socket << ED2KPacket::SetReqFileId( m_sourceInfo->getReqFile()->getHash() ); if (d->isSourceReqAllowed(this)) { logTrace(TRACE_SRCEXCH, boost::format( "[%s] SourceExchange: Requesting sources for file %s." ) % getIpPort() % d->getHash().decode()); *m_socket << ED2KPacket::SourceExchReq(d->getHash()); d->setLastSrcExch(Utils::getTick()); } } // Description of the file ... well, actually, a comment. Rather useless, if // you ask me, but well - some like them. void Client::onPacket(const ED2KPacket::FileDesc &p) { CHECK_THROW(m_sourceInfo); CHECK_THROW(m_sourceInfo->getReqFile()); boost::format fmt( "Received comment for file %s:\nRating: %s Comment: %s" ); fmt %m_sourceInfo->getReqFile()->getPartData()->getDestination().leaf(); fmt % ED2KFile::ratingToString(p.getRating()); fmt % p.getComment(); logMsg(fmt); MetaData *md = m_sourceInfo->getReqFile()->getPartData()->getMetaData(); if (md) { boost::format fmt("%s (Rating: %s)"); fmt % p.getComment() % ED2KFile::ratingToString(p.getRating()); md->addComment(fmt.str()); } } // Status of the file ... now we'r getting somewhere. Among other useful things, // this contains which chunks of the file the sender has. Niice. This is useful, // keep it around somewhere, since we might want to x-ref it with our own chunk // lists to generate nice chunk requests. // // Now we can indicate that we are really really sure we really want the file // we'v been trying to request so far, so tell it to it -> startuploadreq. // As a sidenote though, we might want to know more of the file than we already // know, e.g. part hashes, so locate the corresponding hashset from metadb, and // request a hashset if we need one. // // Note that if the source does not have any needed parts for us (checked via // m_sourceInfo->hasNeededParts() method), we keep the source alive for now - // it might become useful at some later time. void Client::onPacket(const ED2KPacket::FileStatus &p) { logTrace(TRACE_CLIENT, boost::format("[%s] Received FileStatus.") % getIpPort() ); CHECK_THROW(isConnected()); if (!m_sourceInfo) { Download *d = DownloadList::instance().find(p.getHash()); if (d) { addOffered(d); } } if (!m_sourceInfo) { // happens when addOffered() discovers we don't need the file // from the client afterall. Just ignore it then. return; } m_sourceInfo->setPartMap(p.getPartMap()); m_dnReqInProgress = false; // only send StartUploadReq if we don't have downloadinfo yet if (m_sourceInfo->hasNeededParts() && !m_downloadInfo) { logTrace(TRACE_CLIENT, boost::format("[%s] Sending StartUploadReq for hash %s") % getIpPort() % m_sourceInfo->getReqFile()->getHash().decode() ); ED2KPacket::StartUploadReq p( m_sourceInfo->getReqFile()->getHash() ); *m_socket << p; getEventTable().postEvent( this, EVT_REASKFILEPING, SOURCE_REASKTIME ); m_lastReaskTime = EventMain::instance().getTick(); } else if (!m_sourceInfo->hasNeededParts()) { logTrace(TRACE_CLIENT, boost::format("[%s] Client has no needed parts.") % getIpPort() ); // re-establish connection in one hour Utils::timedCallback( boost::bind(&Client::establishConnection, this), SOURCE_REASKTIME * 2 ); } if (m_sourceInfo->getReqFile()->getSize() <= ED2K_PARTSIZE) { return; // don't need hashset } MetaData *md = m_sourceInfo->getReqFile()->getPartData()->getMetaData(); for (uint32_t i = 0; i < md->getHashSetCount(); ++i) { HashSetBase *hs = md->getHashSet(i); if (hs->getFileHashTypeId() != CGComm::OP_HT_ED2K) { continue; } if (!hs->getChunkCnt()) { *m_socket << ED2KPacket::ReqHashSet( m_sourceInfo->getReqFile()->getHash() ); } } } // Oh? But ... but you said you had the file ? What did you do it ? Did you // delete it already? But why? Was it a bad file? .... // So many questions.... so little time. void Client::onPacket(const ED2KPacket::NoFile &p) { logTrace(TRACE_CLIENT, boost::format("[%s] Received NoFile.") % getIpPort() ); if (!m_sourceInfo) { logTrace(TRACE_CLIENT, boost::format("[%s] Got NoFile, but no sourceinfo?") % getIpPort() ); return; } Download *d = DownloadList::instance().find(p.getHash()); if (d && m_sourceInfo->offers(d)) { remOffered(d); } } // This could be useful... any cool info is always welcome. So here ... hashes? // hum, let's update MetaDb then, if we received this, we probably needed them. void Client::onPacket(const ED2KPacket::HashSet &p) { if (!m_sourceInfo || !m_sourceInfo->getReqFile()) { return; } logTrace(TRACE_CLIENT, boost::format("[%s] Received HashSet for %s") % getIpPort() % p.getHashSet()->getFileHash().decode() ); verifyHashSet(p.getHashSet()); MetaData *md = m_sourceInfo->getReqFile()->getPartData()->getMetaData(); if (!md) { logTrace(TRACE_CLIENT, boost::format( "[%s] Received HashSet, but for what file?" ) % getIpPort() ); return; } HashSetBase *hs = 0; for (uint32_t i = 0; i < md->getHashSetCount(); ++i) { if (md->getHashSet(i)->getFileHashTypeId()!=CGComm::OP_HT_ED2K){ continue; } hs = md->getHashSet(i); break; } if (!hs) { logTrace(TRACE_CLIENT, boost::format( "[%s] Received HashSet, but for what file?" ) % getIpPort() ); return; } ED2KHashSet *ehs = dynamic_cast<ED2KHashSet*>(hs); CHECK_THROW(ehs); CHECK_THROW(ehs->getFileHash() == p.getHashSet()->getFileHash()); if (ehs->getChunkCnt()) { return; // no chunk hashes needed } for (uint32_t i = 0; i < p.getHashSet()->getChunkCnt(); ++i) { ehs->addChunkHash((*p.getHashSet())[i].getData()); } if (m_sourceInfo && m_sourceInfo->getReqFile()) { m_sourceInfo->getReqFile()->getPartData()->addHashSet(ehs); } } // verify the contents of passed hashset void Client::verifyHashSet(boost::shared_ptr<ED2KHashSet> hs) { ED2KHashMaker maker; for (uint32_t i = 0; i < hs->getChunkCnt(); ++i) { maker.sumUp((*hs)[i].getData().get(), 16); } boost::scoped_ptr<HashSetBase> ret(maker.getHashSet()); if (ret->getFileHash() != hs->getFileHash()) { throw std::runtime_error("Client sent invalid hashset!"); } } // note: don't disconnect the client here, since he might want smth from us // too. While this does impose up to 30-sec longer delay in keeping sockets // open, if we disconnect here, we ruin remote client's attempt to request // stuff from us. // // using our smart early-disconnection scheme, we can disconnect the client // here, if we are sure the remote client has sent all their requests already. void Client::setOnQueue(uint32_t qr) { CHECK_THROW(m_sourceInfo); CHECK_THROW(m_sourceInfo->getReqFile()); logTrace(TRACE_CLIENT, boost::format( COL_GREEN "[%s] We are queued on position" COL_COMP " %d " COL_GREEN "for file %s" COL_NONE ) % getIpPort() % qr % m_sourceInfo->getReqFile()-> getPartData()->getDestination().leaf() ); m_sourceInfo->setQR(qr); // when transfer was in progressn, and we got queue ranking, also // schedule next reask, otherwise we never reask this client. if (m_downloadInfo) { getEventTable().postEvent( this, EVT_REASKFILEPING, SOURCE_REASKTIME ); m_lastReaskTime = EventMain::instance().getTick(); } // reset download-info here, to work around the case where client sends // us queue-ranking while downloading is in progress (in which case, it // put us on queue, and is supposed to stop transfering data to us). // This also handles next AcceptUpload properly (which is otherwise // simply ignored, if DownloadInfo object is alive when it arrives). m_downloadInfo.reset(); m_dnReqInProgress = false; } void Client::onPacket(const ED2KPacket::QueueRanking &p) { setOnQueue(p.getQR()); } void Client::onPacket(const ED2KPacket::MuleQueueRank &p) { setOnQueue(p.getQR()); } void Client::reqDownload() { CHECK_THROW(m_sourceInfo); CHECK_THROW(isConnected()); m_sourceInfo->swapToLowest(); Download *d = m_sourceInfo->getReqFile(); CHECK_THROW(d); CHECK_THROW(DownloadList::instance().valid(d)); // don't reask more often than allowed if (m_lastReaskTime + SOURCE_REASKTIME > Utils::getTick()) { // this is necessery, otherwise when we'r uploading to a client, // but did UDP reask earlier, we drop the source, since // onLostConnection thinks we failed to send req this session. if (m_sessionState) { m_sessionState->m_sentReq = true; } return; } logTrace(TRACE_CLIENT, boost::format("[%s] Requesting download.") % getIpPort() ); *m_socket << ED2KPacket::ReqFile(d->getHash(), d->getPartData()); m_lastReaskId = ED2K::instance().getId(); CHECK_THROW(m_sessionState); m_sessionState->m_sentReq = true; // reset it here, to avoid requesting multiple times in row. // Note that we shouldn't emit REASKFILEPING event here - that's done // after sending StartUploadReq m_lastReaskTime = Utils::getTick(); m_dnReqInProgress = true; m_failedUdpReasks = 0; } // Ok, now we'r really getting somewhere - seems we can start downloading now. // Send out chunk requests and start waiting for data. // We may already have m_downloadInfo alive at this point if we were already // downloading from this client, and it simply re-sent us AcceptUploadReq // again for some reason (mules seem to do it after every 9500kb part. // // It's also possible that we were called back, and the sending client sent // Hello + Accept in straight row (mules do it), in which case we get here // before we have handled id-change properly (parsing is done via direct // calls, events go through main event loop, thus slower). In that case, just // don't do anything here - after merging (or whatever happens on idchange), // we'll start dloading anyway. void Client::onPacket(const ED2KPacket::AcceptUploadReq &) try { logTrace(TRACE_CLIENT, boost::format("[%s] Received AcceptUploadReq.") % getIpPort() ); if (m_sourceInfo && m_sourceInfo->getPartMap()) { Download *d = m_sourceInfo->getReqFile(); CHECK_THROW(d); CHECK_THROW(DownloadList::instance().valid(d)); if (!m_sourceInfo->getReqFile()->getPartData()->isRunning()) { logTrace(TRACE_CLIENT, boost::format( "[%s] Client accepted transfer, but " "file is already paused." ) % getIpPort() ); *m_socket << ED2KPacket::CancelTransfer(); m_downloadInfo.reset(); return; } if (!m_downloadInfo) { PartData *pd = d->getPartData(); m_downloadInfo.reset( new Detail::DownloadInfo( this, pd, m_sourceInfo->getPartMap() ) ); sendChunkReqs(); } // this avoids dropping the client with error 'is source, // but file req couldn't be sent this session' once the // download session ends if (m_sessionState) { m_sessionState->m_sentReq = true; } } else { logTrace(TRACE_CLIENT, boost::format( "[%s] Client accepted download request, " "but what shall we download?" ) % getIpPort() ); } } catch (std::exception &e) { logDebug( boost::format("[%s] Starting download: %s") % getIpPort() % e.what() ); m_downloadInfo.reset(); } MSVC_ONLY(;) // Little helper method - we send chunk requests from several locations, so // localize this in this helper function. // If onlyNew is set true, we only send the back-most chunk request in the list. // While mules and edonkeys request chunk in a rotational way, (e.g. // [c1, c2, c3], [c2, c3, c4], [c3, c4, c5], it seems even they get confused // sometimes with this thing, and start sending chunks twice. Or it could be // we fail to do it exactly the way they expect it. Whatever the reason, it // seems way too error-prone and un-neccesery, so we'r just going to fall back // to requesting exactly the chunks we need, nothing more. void Client::sendChunkReqs(bool onlyNew) try { using ED2KPacket::ReqChunks; typedef std::list<Range32>::iterator Iter; CHECK_THROW(isConnected()); CHECK_THROW(m_downloadInfo); std::list<Range32> creqs = m_downloadInfo->getChunkReqs(); if (creqs.size()) { if (onlyNew) { while (creqs.size() > 1) { creqs.pop_front(); } } for (Iter i = creqs.begin(); i != creqs.end(); ++i) { boost::format fmt("[%s] Requesting chunk %d..%d"); fmt % getIpPort(); logTrace(TRACE_CLIENT, fmt % (*i).begin() % (*i).end()); } *m_socket << ReqChunks( m_sourceInfo->getReqFile()->getHash(), creqs ); } } catch (std::exception &e) { // Something went wrong internally... might be we failed to aquire more // locks in partdata, might be partdata was completed ... whatever the // reason, it's internal, and we might have previously requested chunks // that are still being downloaded, so don't self-destruct here just // yet. If PartData was completed, we get notified of it and will handle // it appropriately then. If we did fail to generate more locks, sooner // or later, the remote client will disconnect us, after it has sent // us everything we requested, and we'll handle it there. So don't do // anything here. logTrace(TRACE_CLIENT, boost::format("[%s] Exception while sending chunk reqests: %s") % getIpPort() % e.what() ); (void)e; } MSVC_ONLY(;) // Receiving data. If downloadInfo->write() returns true, it means we completed // a chunk, and need to send more chunk requests. void Client::onPacket(const ED2KPacket::DataChunk &p) { CHECK_THROW(m_downloadInfo); CHECK_THROW(isConnected()); if (!m_downloadInfo->getReqPD()->isRunning()) { logTrace(TRACE_CLIENT, boost::format( "[%s] Canceling transfer - file " "was paused/stopped." ) % getIpPort() ); *m_socket << ED2KPacket::CancelTransfer(); m_downloadInfo.reset(); return; } logTrace(TRACE_CLIENT, boost::format( COL_RECV "[%s] Received %d bytes data for `%s'"COL_NONE ) % getIpPort() % p.getData().size() % m_downloadInfo->getReqPD()->getDestination().leaf() ); Range32 r(p.getBegin(), p.getEnd() - 1); bool ret = m_downloadInfo->write(r, p.getData()); if (!m_credits && m_pubKey) { m_credits = CreditsDb::instance().create(m_pubKey, m_hash); } if (m_credits) { m_credits->addDownloaded(p.getData().size()); } if (ret) { sendChunkReqs(true); } } // Packed data - handled slightly differently from normal data. void Client::onPacket(const ED2KPacket::PackedChunk &p) { CHECK_THROW(m_downloadInfo); CHECK_THROW(isConnected()); if (!m_downloadInfo->getReqPD()->isRunning()) { logTrace(TRACE_CLIENT, boost::format( "[%s] Canceling transfer - file " "was paused/stopped." ) % getIpPort() ); *m_socket << ED2KPacket::CancelTransfer(); m_downloadInfo.reset(); return; } if (!m_downloadInfo->getReqPD()->isRunning()) { *m_socket << ED2KPacket::CancelTransfer(); m_downloadInfo.reset(); return; } logTrace(TRACE_CLIENT, boost::format( COL_RECV "[%s] Received %d bytes data for `%s' " COL_BYELLOW "(compressed)" COL_NONE ) % getIpPort() % p.getData().size() % m_downloadInfo->getReqPD()->getDestination().leaf() ); bool ret = m_downloadInfo->writePacked( p.getBegin(), p.getSize(),p.getData() ); if (!m_credits && m_pubKey) { m_credits = CreditsDb::instance().create(m_pubKey, m_hash); } if (m_credits) { m_credits->addDownloaded(p.getData().size()); } if (ret) { sendChunkReqs(true); } } void Client::onPacket(const ED2KPacket::SourceExchReq &p) { CHECK_THROW(m_socket); Download *d = DownloadList::instance().find(p.getHash()); if (d && d->getSourceCount() > 0 && d->getSourceCount() < 50) { ED2KPacket::AnswerSources packet(p.getHash(), d->getSources()); packet.setSwapIds(getSrcExchVer() >= 3); *m_socket << packet; logTrace(TRACE_SRCEXCH, boost::format( "[%s] SourceExchange: Sending %d sources for " "hash %s" ) % getIpPort() % packet.size() % p.getHash().decode() ); } } void Client::onPacket(const ED2KPacket::AnswerSources &p) try { bool fServers = Prefs::instance().read<bool>("/ed2k/FindServers", true); uint32_t cnt = 0; bool swapIds = getSrcExchVer() >= 3; ED2KPacket::AnswerSources::CIter it = p.begin(); while (it != p.end()) { IPV4Address src((*it).get<0>(), (*it).get<1>()); IPV4Address srv((*it).get<2>(), (*it).get<3>()); if (swapIds) { src.setAddr(SWAP32_ON_LE(src.getAddr())); } if (src) { cnt += Detail::foundSource(p.getHash(), src, srv, true); } if (srv && fServers) { Detail::foundServer(srv); } ++it; } logTrace(TRACE_SRCEXCH, boost::format( "[%s] SourceExchange: Received %d sources for hash " "%s (and %d duplicates)" ) % getIpPort() % cnt % p.getHash().decode() % (p.size() - cnt) ); } catch (std::exception &e) { logTrace(TRACE_SRCEXCH, boost::format("[%s] SourceExchange error: %s") % getIpPort() % e.what() ); (void)e; } void Client::onPacket(const ED2KPacket::ChangeId &p) { boost::format fmt("[%s] ChangeId: %d -> %d"); fmt % getIpPort(); if (::Donkey::isHighId(p.getOldId())) { fmt % Socket::getAddr(p.getOldId()); } else { fmt % p.getOldId(); } if (::Donkey::isHighId(p.getNewId())) { fmt % Socket::getAddr(p.getNewId()); } else { fmt % p.getNewId(); } logTrace(TRACE_CLIENT, fmt); Detail::changeId(this, p.getNewId()); } void Client::onPacket(const ED2KPacket::Message &p) { if (!Detail::checkMsgFilter(p.getMsg())) { logMsg( boost::format("Received message from %s: %s") % getIpPort() % p.getMsg() ); } } void Client::onPacket(const ED2KPacket::SecIdentState &p) { using namespace ED2KPacket; boost::format fmt( "[%s] Received SecIdentState %s (ch=%d)" ); fmt % getIpPort(); if (p.getState() == SI_SIGNEEDED) { logTrace(TRACE_SECIDENT, fmt % "NeedSign" % p.getChallenge()); } else if (p.getState() == SI_KEYANDSIGNEEDED) { logTrace(TRACE_SECIDENT, fmt%"NeedKeyAndSign"%p.getChallenge()); } else { logTrace(TRACE_SECIDENT, fmt % "Unknown" % p.getChallenge()); } m_reqChallenge = p.getChallenge(); if (!m_pubKey && !m_sentChallenge) { verifyIdent(); } if (p.getState() == SI_KEYANDSIGNEEDED) { sendPublicKey(); } if (m_pubKey) { sendSignature(); } } void Client::onPacket(const ED2KPacket::PublicKey &p) { logTrace(TRACE_SECIDENT, boost::format("[%s] Received PublicKey.") %getIpPort() ); if (m_pubKey && m_pubKey != p.getKey()) { logDebug( boost::format( "[%s] Client sent DIFFERENT public " "keys! Someone is doing something bad." ) % getIpPort() ); m_pubKey.clear(); m_credits = 0; // no credits anymore } else { m_pubKey = p.getKey(); if (m_reqChallenge) { sendSignature(); } } } void Client::onPacket(const ED2KPacket::Signature &p) { CHECK_RET(m_pubKey); CHECK_RET(m_sentChallenge); boost::format fmt( "[%s] Received Signature (iType=%s) (ch=%d)" ); fmt % getIpPort(); if (p.getIpType() == IP_REMOTE) { fmt % "Remote"; } else if (p.getIpType() == IP_LOCAL) { fmt % "Local"; } else { fmt % "Null"; } logTrace(TRACE_SECIDENT, fmt % m_sentChallenge); IpType iType = 0; uint32_t id = 0; if (getSecIdentVer() > 1 && p.getIpType()) { iType = p.getIpType(); if (iType == IP_REMOTE) { id = ED2K::instance().getId(); } else if (iType == IP_LOCAL) { id = m_socket->getPeer().getIp(); } } bool ret = false; try { ret = CreditsDb::verifySignature( m_pubKey, m_sentChallenge, p.getSign(), iType, id ); } catch (std::exception &e) { logTrace(TRACE_CLIENT, boost::format("[%s] Error verifying signature: %s") % getIpPort() % e.what() ); (void)e; } if (ret) { logTrace(TRACE_SECIDENT, boost::format("[%s] Ident succeeded.") % getIpPort() ); if (!m_credits) { m_credits = CreditsDb::instance().find(m_pubKey); } if (m_credits) { CHECK_THROW(m_pubKey == m_credits->getPubKey()); // save some ram - avoid storing PubKey twice // (it has refcounted implementation) m_pubKey = m_credits->getPubKey(); m_credits->setLastSeen(Utils::getTick() / 1000); logTrace(TRACE_SECIDENT, boost::format( "[%s] Found credits: %s up, %s down" ) % getIpPort() % Utils::bytesToString( m_credits->getUploaded() ) % Utils::bytesToString( m_credits->getDownloaded() ) ); } try { initTransfer(); } catch (std::exception &e) { logDebug( boost::format( "[%s] Failed to initTransfer(): %s" ) % getIpPort() % e.what() ); destroy(); // what else can we do here ? } } else { logTrace(TRACE_SECIDENT, boost::format( COL_BYELLOW "[%s] SecIdent failed!" COL_NONE ) % getIpPort() ); m_credits = 0; } m_sentChallenge = 0; } void Client::sendPublicKey() { CHECK_THROW(isConnected()); *m_socket<< ED2KPacket::PublicKey(CreditsDb::instance().getPublicKey()); } void Client::sendSignature() { CHECK_THROW(m_pubKey); // need client's public key to send signature! CHECK_THROW(m_reqChallenge); // challenge this sig responds to CHECK_THROW(isConnected()); logTrace(TRACE_SECIDENT, boost::format("[%s] Sending Signature (ch=%d)") % getIpPort() % m_reqChallenge ); IpType iType = 0; uint32_t ip = 0; if (getSecIdentVer() == 2) { // only v2 uses this, not v1 and not v3 if (::Donkey::isLowId(ED2K::instance().getId())) { iType = IP_REMOTE; ip = getId(); } else { iType = IP_LOCAL; ip = ED2K::instance().getId(); } } std::string sign( CreditsDb::createSignature(m_pubKey, m_reqChallenge, iType, ip) ); ED2KPacket::Signature packet(sign, iType); *m_socket << packet; m_reqChallenge = 0; } void Client::verifyIdent() { if (!getSecIdentVer() || m_sentChallenge) { return; } CHECK_THROW(isConnected()); boost::format fmt("[%s] Requesting %s"); SecIdentState state(SI_SIGNEEDED); if (!m_pubKey) { state = SI_KEYANDSIGNEEDED; fmt % getIpPort() % "KeyAndSign"; } else { fmt % getIpPort() % "Sign"; } logTrace(TRACE_SECIDENT, fmt); ED2KPacket::SecIdentState packet(state); m_sentChallenge = packet.getChallenge(); *m_socket << packet; } void Client::handshakeCompleted() try { if (getSecIdentVer() && !m_sentChallenge) { verifyIdent(); } else { initTransfer(); } } catch (std::exception &e) { logDebug( boost::format("[%s] Failed to initTransfer(): %s") % getIpPort() % e.what() ); destroy(); // what else can we do here ? } void Client::initTransfer() { if (m_uploadInfo) { m_queueInfo.reset(); startUpload(); } if (m_sourceInfo && !m_downloadInfo) { reqDownload(); } } // perform a reask for download // if our ID has changed since last reask (stored in m_lastReaskId member), // we force TCP reask, since with UDP reask, the remote client can't recognize // us. Also, if the remote client is LowID, or doesn't support UDP reasks, we // also perform TCP reask instead. In all other cases, we use UDP to save // bandwidth. // If we'r already connected to the client at the time of this function call, // just send normal reask packet via the current socket. void Client::reaskForDownload() { CHECK_THROW(m_sourceInfo); CHECK_THROW(!m_downloadInfo); // allow reask time to vary in 2-second timeframe; worst-case scenario // is that we do two reasks within 2-second timeframe, but this avoids // small variations in time calculations, where we skip a reask since // this handler was called 1 sec before the actual reask time. if (m_lastReaskTime + SOURCE_REASKTIME > Utils::getTick() + 2000) { logTrace(TRACE_CLIENT, boost::format( "[%s] Reask time, we already did that %.2f " "seconds ago. Ignoring this reask." ) % getIpPort() % ((Utils::getTick() - m_lastReaskTime) / 1000) ); return; } if (!isConnected() && ED2K::instance().isLowId() && isLowId()) { logTrace(TRACE_CLIENT, boost::format("[%s] Cannot do LowID<->LowID reask!") % getIpPort() ); destroy(); return; } if (isConnected()) { reqDownload(); } else if (m_lastReaskId && m_lastReaskId != ED2K::instance().getId()) { logTrace(TRACE_CLIENT, boost::format( "[%s] Our ID has changed since last reask, " "forcing TCP reask." ) % getIpPort() ); establishConnection(); } else if (isHighId() && getUdpPort() && getUdpVer()) try { Download *d = m_sourceInfo->getReqFile(); CHECK_THROW(d); CHECK_THROW(DownloadList::instance().valid(d)); const PartData *pd = d->getPartData(); CHECK_THROW(pd); Hash<ED2KHash> hash = d->getHash(); uint32_t srcCnt = d->getSourceCount(); const IPV4Address addr(getId(), getUdpPort()); ED2KPacket::ReaskFilePing packet(hash, pd, srcCnt, getUdpVer()); s_clientUdpSocket->send(packet, addr); getEventTable().postEvent(this, EVT_REASKTIMEOUT, UDP_TIMEOUT); m_reaskInProgress = true; m_lastReaskId = ED2K::instance().getId(); logTrace(TRACE_CLIENT, boost::format("[%s] UDP Reask in progress...") % getIpPort() ); } catch (SocketError &e) { logDebug( boost::format( "[%s] Fatal error performing UDP reask: %s" ) % getIpPort() % e.what() ); } else { logTrace(TRACE_CLIENT, boost::format("[%s] TCP Reask in progress...") % getIpPort() ); establishConnection(); } } // UDP file reasks handler // // If we do not have queueinfo when this packet is received, this indicates the // client isn't in our queue; this usually happens when we have just restarted, // and our queue has been lost, but clients come reasking. In that case, to be // fair to the remote clients, we passivly initiate the file upload request. // // However, we will send QR 0 in response in this function, because getting it // to send the right QR here means more breaking things apart, and keeping even // more state variables than we already have, so - sending QR0 to ppl for a // while after restart is acceptable loss, at least for now - internally we'r // still handling everything properly, so this only affects "visible" side on // the remote client anyway. void Client::onPacket(const ED2KPacket::ReaskFilePing &p) { // no queue-info - usually happens when we do a restart, and forget // our queue - add it to our queue by our normal queueing rules. if (!m_queueInfo) { logTrace(TRACE_CLIENT, boost::format( "[%s] UDP ReaskFilePing: Passivly initiating " "remote UploadReq." ) % getIpPort() ); onUploadReq(p.getHash()); Download *d = DownloadList::instance().find(p.getHash()); if (d) { addOffered(d); } } // can't send to LowId clients; or already uploading; or no queue info if (isLowId() || m_uploadInfo || !m_queueInfo) { return; } logTrace(TRACE_CLIENT, boost::format("[%s] Received ReaskFilePing.") % getIpPort() ); IPV4Address addr(getId(), getUdpPort()); if (p.getHash() != m_queueInfo->getReqHash()) { SharedFile *sf = MetaDb::instance().findSharedFile(p.getHash()); if (sf) { logTrace(TRACE_CLIENT, boost::format( "[%s] UDP SwapToAnotherFile performed." ) % getIpPort() ); m_queueInfo->setReqFile(sf, p.getHash()); } else try { logTrace(TRACE_CLIENT, boost::format( "[%s] UDP SwapToAnotherFile failed." ) % getIpPort() ); ED2KPacket::FileNotFound packet; s_clientUdpSocket->send(packet, addr); } catch (SocketError &e) { logDebug(boost::format( "[%s] Fatal error sending UDP packet: %s" ) % getIpPort() % e.what()); } } const PartData *pd = m_queueInfo->getReqFile()->getPartData(); uint16_t queueRank = m_queueInfo->getQR(); try { ED2KPacket::ReaskAck packet(pd, queueRank, getUdpVer()); s_clientUdpSocket->send(packet, addr); logTrace(TRACE_CLIENT, boost::format( "[%s] ReaskFilePing: Sending QueueRank %s" ) % getIpPort() % queueRank ); m_queueInfo->m_lastQueueReask = Utils::getTick(); } catch (SocketError &e) { logDebug( boost::format( "[%s] Fatal error sending ReaskFilePing: %s" ) % getIpPort() % e.what() ); } } void Client::onPacket(const ED2KPacket::ReaskAck &p) { CHECK_THROW(m_sourceInfo); m_reaskInProgress = false; m_failedUdpReasks = 0; logTrace(TRACE_CLIENT, boost::format( "[%s] UDP Reask: Received ReaskAck; " "We are queued on position %d for file %s" ) % getIpPort() % p.getQR() % m_sourceInfo->getReqFile()-> getPartData()->getDestination().leaf() ); m_sourceInfo->setPartMap(p.getPartMap()); m_sourceInfo->setQR(p.getQR()); getEventTable().postEvent(this, EVT_REASKFILEPING, SOURCE_REASKTIME); m_lastReaskTime = EventMain::instance().getTick(); } // We can only assume that the FileNotFound is about currently requested // file, because the packet doesn't contain hash. There might be a race // condition hidden here, when we swap to another file DURING the UDP callback, // in which case we incorrectly remove the wrong offered file from m_sourceInfo. void Client::onPacket(const ED2KPacket::FileNotFound &) { m_reaskInProgress = false; m_failedUdpReasks = 0; logTrace(TRACE_CLIENT, boost::format("[%s] UDP Reask: Received FileNotFound") % getIpPort() ); if (m_sourceInfo) { remOffered(m_sourceInfo->getReqFile()); } if (m_sourceInfo) { reaskForDownload(); // switch to another file performed } } void Client::onPacket(const ED2KPacket::QueueFull &) { m_reaskInProgress = false; m_failedUdpReasks = 0; logTrace(TRACE_CLIENT, boost::format("[%s] UDP Reask: Received QueueFull") % getIpPort() ); if (m_sourceInfo) { m_sourceInfo->setQR(0); } getEventTable().postEvent(this, EVT_REASKFILEPING, SOURCE_REASKTIME); m_lastReaskTime = EventMain::instance().getTick(); } void Client::removeFromQueue() { m_queueInfo.reset(); getEventTable().postEvent(this, EVT_CANCEL_UPLOADREQ); checkDestroy(); } } // end namespace Donkey
;;; Excercise the XDR language compiler. -*- Scheme -*- ;;; ;;; GNU Guile-RPC --- A Scheme implementation of ONC RPC. ;;; Copyright (C) 2008, 2010, 2012, 2014 Free Software Foundation, Inc. ;;; ;;; This file is part of GNU Guile-RPC. ;;; ;;; GNU Guile-RPC is free software; you can redistribute it and/or modify it ;;; under the terms of the GNU Lesser General Public License as published by ;;; the Free Software Foundation; either version 3 of the License, or (at ;;; your option) any later version. ;;; ;;; GNU Guile-RPC is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser ;;; General Public License for more details. ;;; ;;; You should have received a copy of the GNU Lesser General Public License ;;; along with this program. If not, see <http://www.gnu.org/licenses/>. (define-module (tests compiler) :use-module (rpc compiler) :use-module ((rpc compiler parser) #:select (*parser-options* location-line location-column)) :use-module (rpc xdr types) :use-module (rpc xdr) :use-module (rnrs bytevectors) :use-module (rnrs io ports) :use-module (srfi srfi-1) :use-module (srfi srfi-13) :use-module (srfi srfi-34) :use-module (srfi srfi-39) :use-module (srfi srfi-64)) ;;; ;;; Tools. ;;; (define (xdr-text . body) (open-input-string (string-join body (string #\newline)))) (define (xdr-encodable? type value) ;; Return true if was able to succesfully encode/decode VALUE in TYPE. (let* ((size (xdr-type-size type value)) (bv (make-bytevector size))) (xdr-encode! bv 0 type value) (equal? (xdr-decode type (open-bytevector-input-port bv)) value))) (define (every? pred . args) (not (not (apply every pred args)))) (define (valid-xdr-types? types value-alist) (define (failed name value) (format (current-error-port) "~a: failed to encode `~A'~%" name value) #f) (and (every? (lambda (value-alist) (let ((type-name (car value-alist))) (assoc type-name types))) value-alist) (every? (lambda (name+type) (let* ((name (car name+type)) (type (cdr name+type)) (values (assoc name value-alist))) (and (pair? values) (every? (lambda (value) (let ((ok? (xdr-encodable? type value))) (or ok? (failed name value)))) (cdr values))))) types))) (define (matches? pattern sexp) ;; Return true if SEXP matches PATTERN. PATTERN is a regular S-exp, with ;; `_' as the match-all thing. (let loop ((pattern pattern) (sexp sexp)) (cond ((eq? pattern '_) #t) ((list? pattern) (and (list? sexp) (or (and (pair? pattern) (pair? sexp) (loop (car pattern) (car sexp)) (loop (cdr pattern) (cdr sexp))) (and (null? pattern) (null? sexp))))) (else (equal? pattern sexp))))) ;;; ;;; Compiler. ;;; (test-begin "xdr-compiler") ;;; ;;; Code generation compiler back-end. ;;; (test-equal "simple types & constants" '((define the-constant 2) (define the-struct (make-xdr-struct-type (list xdr-integer xdr-float))) (define the-enum (make-xdr-enumeration 'the-enum `((one . 1) (two . ,the-constant))))) (rpc-language->scheme-client (xdr-text "const the_constant = 2;" "struct the_struct { int x; float y; };" "typedef enum { one = 1, two = the_constant } " " the_enum;") #t #t)) (test-equal "unions" '((define foo xdr-integer) (define the-enum (make-xdr-enumeration 'the-enum `((zero . 0) (one . 1) (two . 2)))) (define the-union (make-xdr-union-type xdr-integer `((0 . ,foo) (1 . ,foo) (2 . ,xdr-float)) #f)) (define the-union-with-default (make-xdr-union-type the-enum `((zero . ,foo) (one . ,foo) (two . ,xdr-void)) the-enum))) (rpc-language->scheme-client (xdr-text "typedef int foo;" "enum the_enum { zero = 0, one = 1, two = 2 };" "union the_union switch (int discr) {" " case 0: case 1: foo the_foo;" " case 2: float the_float;" "};" "union the_union_with_default switch (the_enum e) {" " case zero: case one: foo the_foo;" " case two: void;" " default: the_enum chbouib;" "};") #t #t)) (test-eq "union with anonymous types" #t (matches? '((define foo (make-xdr-union-type (make-xdr-enumeration _ `((a . 0) (b . 1))) `((a . ,(make-xdr-struct-type (list xdr-integer xdr-double)))) xdr-integer))) (rpc-language->scheme-client (xdr-text "union foo" " switch (enum { a = 0, b = 1 } d) {" " case a: struct { int x; double y; } chbouib;" " default: int bar;" " };") #t #t))) (test-eq "arrays of anonymous types" #t (matches? '((define foo (make-xdr-struct-type (make-list 10 (make-xdr-struct-type (list (make-xdr-struct-type (list xdr-integer xdr-double)) xdr-double))))) (define bar (make-xdr-vector-type (make-xdr-union-type xdr-integer `((0 . ,xdr-boolean)) (make-xdr-struct-type (make-list 10 (make-xdr-enumeration _ `((a . 0)))))) #f))) (rpc-language->scheme-client (xdr-text "typedef struct {" " struct { int x; double y; } x; double y;" "} foo[10];" "typedef union switch (int d) {" " case 0: bool b;" " default: enum { a = 0 } a[10];" "} bar<>;") #t #t))) (test-equal "optional data unions" '((define the-union (make-xdr-union-type xdr-boolean `((TRUE . ,xdr-integer) (FALSE . ,xdr-void)) #f))) (rpc-language->scheme-client (xdr-text "typedef int *the_union;") #t #t)) (test-equal "fixed-length arrays" '((define the-array (make-xdr-struct-type (make-list 10 xdr-integer))) (define the-opaque-array (make-xdr-fixed-length-opaque-array 8))) (rpc-language->scheme-client (xdr-text "typedef int the_array[10];" "typedef opaque the_opaque_array[010];") #t #t)) (test-equal "variable-length arrays" '((define the-array (make-xdr-vector-type xdr-float 10)) (define the-opaque-array (make-xdr-variable-length-opaque-array #f))) (rpc-language->scheme-client (xdr-text "typedef float the_array<10>;" "typedef opaque the_opaque_array<>;") #t #t)) (test-equal "constant as array size" '((define LEN 10) (define foo (make-xdr-string LEN)) (define bar (make-xdr-vector-type xdr-integer LEN)) (define chbouib (make-xdr-struct-type (make-list LEN xdr-double)))) (rpc-language->scheme-client (xdr-text "const LEN = 10;" "typedef string foo<LEN>;" "typedef int bar<LEN>;" "typedef double chbouib[LEN];") #t #t)) (test-equal "struct with array and string members" '((define MAX 10) (define s (make-xdr-struct-type (list (make-xdr-string MAX) (make-xdr-fixed-length-opaque-array 9) (make-xdr-vector-type xdr-integer 8))))) (rpc-language->scheme-client (xdr-text "const MAX = 10;" "struct s { string foo<MAX>; opaque bar[9];" " int chbouib<8>; };") #t #t)) (test-equal "unknown type" '(1 13 "foo") (guard (c ((compiler-unknown-type-error? c) (let ((name (compiler-unknown-type-error:type-name c)) (loc (compiler-error:location c))) (list (location-line loc) (location-column loc) name)))) (rpc-language->scheme-client (xdr-text "typedef foo bar;") #t #t) #f)) (test-equal "unknown constant" '(1 9 "MAX") (guard (c ((compiler-unknown-constant-error? c) (let ((name (compiler-unknown-constant-error:constant-name c)) (loc (compiler-error:location c))) (list (location-line loc) (location-column loc) name)))) (rpc-language->scheme-client (xdr-text "typedef opaque chbouib<MAX>;") #t #t))) (test-equal "union with struct and array members" '((define u (make-xdr-union-type xdr-boolean `((TRUE . ,(make-xdr-struct-type (list xdr-integer xdr-double))) (FALSE . ,(make-xdr-vector-type xdr-integer 10))) #f))) (rpc-language->scheme-client (xdr-text "union u switch (bool b) {" " case TRUE: struct { int x; double y; } foo;" " case FALSE: int bar<10>;" "};") #t #t)) (test-equal "recursive types" '((define list-of-ints (make-xdr-struct-type (list xdr-integer (make-xdr-union-type xdr-boolean `((TRUE . ,(lambda () list-of-ints)) (FALSE . ,xdr-void)) #f)))) (define another-list (make-xdr-struct-type (list xdr-integer (make-xdr-vector-type (lambda () another-list) 1))))) (rpc-language->scheme-client (xdr-text "struct list_of_ints { int x; list_of_ints *next; };" "struct another_list {" " int x; another_list next<1>;" "};") #t #t)) (test-equal "mutually recursive types" '((define mountbody (make-xdr-struct-type (list xdr-integer (lambda () mountlist)))) (define mountlist (make-xdr-union-type xdr-boolean `((TRUE . ,(lambda () mountbody)) (FALSE . ,xdr-void)) #f))) (parameterize ((*parser-options* '(allow-struct-type-specifier))) (rpc-language->scheme-client ;; Example adapted from Sun's `mount.x'. (xdr-text "typedef struct mountbody *mountlist;" "struct mountbody {" " int x;" " mountlist next;" "};") #t #t))) (test-equal "4 mutually recursive types" '((define d (make-xdr-struct-type (list xdr-integer (lambda () c)))) (define c (make-xdr-struct-type (list xdr-integer (lambda () b)))) (define b (make-xdr-struct-type (list xdr-integer (lambda () a)))) (define a (make-xdr-union-type xdr-boolean `((TRUE . ,(lambda () d)) (FALSE . ,xdr-void)) #f))) (rpc-language->scheme-client (xdr-text "typedef d *a;" "struct b { int x; a list; };" "struct c { int x; b list; };" "struct d { int x; c list; };") #t #t)) (test-equal "complex mutually recursive types" '((define exportnode (make-xdr-struct-type (list (make-xdr-string 10) (lambda () groups) (lambda () exports)))) (define groupnode (make-xdr-struct-type (list (make-xdr-string 10) (lambda () groups)))) (define exports (make-xdr-union-type xdr-boolean `((TRUE . ,(lambda () exportnode)) (FALSE . ,xdr-void)) #f)) (define groups (make-xdr-union-type xdr-boolean `((TRUE . ,(lambda () groupnode)) (FALSE . ,xdr-void)) #f))) (parameterize ((*parser-options* '(allow-struct-type-specifier))) (rpc-language->scheme-client ;; Example adapted from Sun's `mount.x'. (xdr-text "typedef struct groupnode *groups;" "struct groupnode {" " string gr_name<10>;" " groups gr_next;" "};" "typedef struct exportnode *exports;" "struct exportnode {" " string ex_dir<10>;" " groups ex_groups;" " exports ex_next;" "};") #t #t))) (test-equal "forward type refs" '((define foo (make-xdr-struct-type (list xdr-integer xdr-double))) (define bar (make-xdr-union-type xdr-boolean `((TRUE . ,foo) (FALSE . ,xdr-void)) #f))) (rpc-language->scheme-client (xdr-text "typedef foo *bar;" "struct foo { int x; double y; };") #t #t)) (test-equal "duplicate identifier" '("chbouib" (2 13) (1 7)) (guard (c ((compiler-duplicate-identifier-error? c) (let ((loc (compiler-error:location c)) (name (compiler-duplicate-identifier-error:name c)) (ploc (compiler-duplicate-identifier-error:previous-location c))) (list name (list (location-line loc) (location-column loc)) (list (location-line ploc) (location-column ploc)))))) (rpc-language->scheme-client (xdr-text "const chbouib = 7;" "typedef int chbouib;") #t #t))) (test-equal "duplicate identifier with program" '("chbouib" (2 9) (1 13)) (guard (c ((compiler-duplicate-identifier-error? c) (let ((loc (compiler-error:location c)) (name (compiler-duplicate-identifier-error:name c)) (ploc (compiler-duplicate-identifier-error:previous-location c))) (list name (list (location-line loc) (location-column loc)) (list (location-line ploc) (location-column ploc)))))) (rpc-language->scheme-client (xdr-text "typedef int chbouib;" "program chbouib {" " version v {" " int foo (int) = 0;" " } = 0;" "} = 0;") #t #t))) (test-equal "client RPC programs" '((define foo-t xdr-integer) (define prog-hello (make-synchronous-rpc-call 77 0 0 xdr-void xdr-integer)) (define prog-greetings-world (make-synchronous-rpc-call 77 0 1 (make-xdr-struct-type (list foo-t (make-xdr-struct-type (list xdr-integer xdr-integer)))) xdr-boolean))) (rpc-language->scheme-client (xdr-text "typedef int foo_t;" "program prog {" " version zero {" " int hello (void) = 0;" " bool greetings_world (foo_t," " struct { int x; int y;}) = 1;" " } = 0;" "} = 77;") #t #t)) (test-equal "client RPC programs with string parameter" '((define prog-hello (make-synchronous-rpc-call 77 0 0 xdr-string xdr-integer))) (parameterize ((*parser-options* '(allow-string-param-type-specifier))) (rpc-language->scheme-client (xdr-text "program prog {" " version zero {" " int hello (string) = 0;" " } = 0;" "} = 77;") #t #f))) (test-equal "client RPC program with forward type ref" '((define foo-t xdr-integer) (define prog-hello (make-synchronous-rpc-call 77 0 0 xdr-void xdr-integer)) (define prog-greetings-world (make-synchronous-rpc-call 77 0 1 (make-xdr-struct-type (list foo-t (make-xdr-struct-type (list xdr-integer xdr-integer)))) xdr-boolean))) (rpc-language->scheme-client (xdr-text "program prog {" " version zero {" " int hello (void) = 0;" " bool greetings_world (foo_t," " struct { int x; int y;}) = 1;" " } = 0;" "} = 77;" "typedef int foo_t;") #t #t)) (test-equal "client RPC program with mutually recursive type refs" ;; The difficulty here is that `exports' and `groups' are ;; mutually recursive (so they are added as forward type ;; references), and the RPC program depends on one of them (so ;; it's also a forward type reference). '((define exportnode (make-xdr-struct-type (list (make-xdr-string 10) (lambda () groups) (lambda () exports)))) (define groupnode (make-xdr-struct-type (list (make-xdr-string 10) (lambda () groups)))) (define exports (make-xdr-union-type xdr-boolean `((TRUE . ,(lambda () exportnode)) (FALSE . ,xdr-void)) #f)) (define groups (make-xdr-union-type xdr-boolean `((TRUE . ,(lambda () groupnode)) (FALSE . ,xdr-void)) #f)) (define MOUNTPROG-MOUNTPROC-EXPORT (make-synchronous-rpc-call 100005 1 5 xdr-void exports))) (parameterize ((*parser-options* '(allow-struct-type-specifier))) (rpc-language->scheme-client ;; Example adapted from Sun's `mount.x'. (xdr-text "typedef struct groupnode *groups;" "struct groupnode {" " string gr_name<10>;" " groups gr_next;" "};" "typedef struct exportnode *exports;" "struct exportnode {" " string ex_dir<10>;" " groups ex_groups;" " exports ex_next;" "};" "program MOUNTPROG {" " version MOUNTVERS {" " exports MOUNTPROC_EXPORT(void) = 5;" " } = 1;" "} = 100005;") #t #t))) ;;; ;;; Run-time compiler back-end. ;;; ;; Note: We can't compare XDR type objects with `equal?' because they contain ;; closures. Thus we perform only some basic checks. (test-eq "simple types & constants [run-time]" #t (let ((types (rpc-language->xdr-types (xdr-text "const the_constant = 2;" "struct the_struct { int x; float y; };" "typedef enum { one = 1, two = the_constant } " " the_enum;")))) (valid-xdr-types? types '(("the_struct" (42 3.0) (-1 0.0)) ("the_enum" one two))))) (test-eq "unions [run-time]" #t (let ((types (rpc-language->xdr-types (xdr-text "typedef int foo;" "enum the_enum { zero = 0, one = 1, two = 2 };" "union the_union switch (int discr) {" " case 0: case 1: foo the_foo;" " case 2: float the_float;" "};" "union the_union_with_default switch (the_enum e) {" " case one: foo the_foo;" " case two: void;" " default: the_enum chbouib;" "};")))) (valid-xdr-types? types `(("foo" -1 0 1 2 3 4) ("the_enum" zero one two) ("the_union" (0 . 1) (1 . -2) (2 . 0.0)) ("the_union_with_default" (one . 1) (two . ,%void) (zero . one) (zero . two)))))) (test-eq "fixed-length arrays [run-time]" #t (let ((types (rpc-language->xdr-types (xdr-text "typedef int the_array[10];" "typedef opaque the_opaque_array[010];")))) (valid-xdr-types? types `(("the_array" ,(iota 10)) ("the_opaque_array" ,(iota 8)))))) (test-eq "variable-length arrays [run-time]" #t (let ((types (rpc-language->xdr-types (xdr-text "typedef float the_array<10>;" "typedef opaque the_opaque_array<>;"))) (fiota (lambda (max) (list->vector (map exact->inexact (iota max)))))) (valid-xdr-types? types `(("the_array" #(1.0 2.0) ,(fiota 10)) ("the_opaque_array" ,(list->vector (iota 7)) ,(list->vector (iota 236))))))) (test-eq "recursive types [run-time]" #t (let ((types (rpc-language->xdr-types (xdr-text "struct list_of_ints {" " int x; list_of_ints *next;" "};" "struct another_list {" " int x; another_list next<1>;" "};")))) (valid-xdr-types? types `(("list_of_ints" (1 (TRUE . (2 (TRUE . (3 (FALSE . ,%void)))))) (1 (TRUE . (2 (FALSE . ,%void)))) (1 (FALSE . ,%void))) ("another_list" (1 #((2 #((3 #()))))) (1 #((2 #()))) (1 #())))))) (test-equal "mutually recursive types [run-time]" #t (parameterize ((*parser-options* '(allow-struct-type-specifier))) (let ((types (rpc-language->xdr-types ;; Example adapted from Sun's `mount.x'. (xdr-text "typedef struct mountbody *mountlist;" "struct mountbody {" " int x;" " mountlist next;" "};")))) (valid-xdr-types? types `(("mountbody" (1 (TRUE . (2 (TRUE . (3 (FALSE . ,%void)))))) (1 (TRUE . (2 (FALSE . ,%void)))) (1 (FALSE . ,%void))) ("mountlist" (TRUE . (2 (TRUE . (3 (FALSE . ,%void))))) (TRUE . (2 (FALSE . ,%void))) (FALSE . ,%void))))))) (test-equal "4 mutually recursive types [run-time]" #t (let ((types (rpc-language->xdr-types (xdr-text "typedef d *a;" "struct b { int x; a list; };" "struct c { int x; b list; };" "struct d { int x; c list; };")))) (valid-xdr-types? types `(("a" (TRUE . (1 (2 (3 (TRUE . (4 (5 (6 (FALSE . ,%void))))))))) (TRUE . (1 (2 (3 (FALSE . ,%void))))) (FALSE . ,%void)) ("b" (1 (TRUE . (2 (3 (4 (TRUE . (5 (6 (7 (FALSE . ,%void)))))))))) (1 (TRUE . (2 (3 (4 (FALSE . ,%void)))))) (1 (FALSE . ,%void))) ("c" (1 (2 (TRUE . (3 (4 (5 (TRUE . (6 (7 (8 (FALSE . ,%void))))))))))) (1 (2 (TRUE . (3 (4 (5 (FALSE . ,%void))))))) (1 (2 (FALSE . ,%void)))) ("d" (1 (2 (3 (TRUE . (4 (5 (6 (TRUE . (7 (8 (9 (FALSE . ,%void)))))))))))) (1 (2 (3 (TRUE . (4 (5 (6 (FALSE . ,%void)))))))) (1 (2 (3 (FALSE . ,%void))))))))) (test-equal "complex mutually recursive types [run-time]" #t (let ((types (parameterize ((*parser-options* '(allow-struct-type-specifier))) (rpc-language->xdr-types ;; Example adapted from Sun's `mount.x'. (xdr-text "typedef struct groupnode *groups;" "struct groupnode {" " string gr_name<10>;" " groups gr_next;" "};" "typedef struct exportnode *exports;" "struct exportnode {" " string ex_dir<10>;" " groups ex_groups;" " exports ex_next;" "};")))) (| (lambda (str) (list->vector (map char->integer (string->list str)))))) (valid-xdr-types? types `(("groups" (TRUE . (,(| "gr_name") (TRUE . (,(| "gr_name") (FALSE . ,%void))))) (TRUE . (,(| "gr_name") (FALSE . ,%void))) (FALSE . ,%void)) ("groupnode" (,(| "gr_name") (TRUE . (,(| "gr_name") (FALSE . ,%void)))) (,(| "gr_name") (FALSE . ,%void))) ("exports" (TRUE . (,(| "ex_dir") (TRUE . (,(| "gr_name") (FALSE . ,%void))) ;; groups (TRUE . (,(| "ex_dir") ;; ex_next (TRUE . (,(| "gr_name") (FALSE . ,%void))) (FALSE . ,%void))))) (TRUE . (,(| "ex_dir") (FALSE . ,%void) (FALSE . ,%void))) (FALSE . ,%void) ) ("exportnode" (,(| "ex_dir") (TRUE . (,(| "gr_name") (FALSE . ,%void))) ;; groups (TRUE . (,(| "ex_dir") ;; ex_next (TRUE . (,(| "gr_name") (FALSE . ,%void))) (FALSE . ,%void)))) (,(| "ex_dir") (FALSE . ,%void) (FALSE . ,%void))) )))) (test-end "xdr-compiler") (exit (= (test-runner-fail-count (test-runner-current)) 0))
import { PrismaClient } from '@prisma/client'; import { Request, Response } from 'express'; import { validate } from 'uuid'; import express from 'express'; const router = express.Router(); const prisma = new PrismaClient(); router.post('/', async (req: Request, res: Response) => { const { full_name, mob_num, pan_num, manager_id } = req.body; if (!full_name) { return res.status(400).json({ error: 'Full name is required' }); } // Validate mob_num const mobNumRegex = /^[0-9]{10}$/; if (!mobNumRegex.test(mob_num)) { return res.status(400).json({ error: 'Invalid mobile number' }); } // Validate pan_num const panNumRegex = /^[A-Z]{5}[0-9]{4}[A-Z]$/; if (!panNumRegex.test(pan_num)) { return res.status(400).json({ error: 'Invalid PAN number' }); } let managerExists = true; let isManagerActive = true; // Validate manager_id if present if (manager_id) { if (!validate(manager_id)) { return res.status(400).json({ error: 'Invalid manager ID' }); } // Check if manager exists in the Manager table const manager = await prisma.manager.findUnique({ where: { id: manager_id }, }); if (!manager) { managerExists = false; } // Check if manager is active (add isActive field to Manager model) if (manager && !manager.active) { isManagerActive = false; } } // If manager_id is provided and manager does not exist or is not active, return error if (manager_id && (!managerExists || !isManagerActive)) { return res.status(400).json({ error: 'Invalid manager ID or manager is not active' }); } try { // Insert user data into the database const user = await prisma.user.create({ data: { full_name, mob_num, pan_num: pan_num.toUpperCase(), manager_id, }, }); // Return success message res.status(201).json({ message: 'User created successfully', user }); } catch (error) { console.error('Error creating user:', error); res.status(500).json({ error: 'Internal server error' }); } }) export default router;
# Определение категории новостей по содержанию с помощью классификации с нулевым сэмплированием Этот проект предоставляет приложение для определения категории новостей по содержанию с помощью классификации с нулевым сэмплированием с использованием предобученных моделей из библиотеки Hugging Face Transformers. ## Содержание - [Описание](#Описание) - [Файлы](#Файлы) - [Использование](#Использование) - [Тестирование](#Тестирование) ## Описание Этот проект состоит из набора Python-скриптов для классификации с нулевым сэмплированием: - `functions.py`: Содержит функции для инициализации классификатора и выполнения предсказаний. - `main.py`: Точка входа для запуска приложения из консоли для ручного тестирования. - `streamlit_run.py`: Точка входа для запуска веб-приложения Streamlit, использующего модель классификатора. - `tests.py`: Юнит-тесты для функций классификатора в файле `functions.py`. ## Файлы - **functions.py**: - `initialize_classifier(model_name: str)`: Инициализирует классификатор для дальнейшего использования. Принимает название модели в качестве входного параметра и возвращает классификатор. - `predict(texts: Union[str, List[str]], labels: List[str])`: Основной метод модуля. Используется для классификации текста. Принимает входной текст или список текстов и список категорий. - **main.py**: - Точка входа для запуска приложения из консоли для ручного тестирования. - Использование: `python main.py`. - **streamlit_run.py**: - Точка входа для запуска веб-приложения Streamlit, использующего модель классификатора. - Использование: `streamlit run streamlit_run.py`. - **tests.py**: - Содержит юнит-тесты для функций классификатора в `functions.py`. - Использование: `python -m unittest tests.py`. ## Использование Чтобы использовать приложение, следуйте этим шагам: 1. Убедитесь, что у вас установлен Python на вашей системе. 2. Установите необходимые зависимости, используя `pip install -r requirements.txt`. 3. Запустите приложение с помощью одной из точек входа: - Для ручного тестирования: `python main.py`. - Для запуска веб-приложения Streamlit: `streamlit run streamlit_run.py`. ## Тестирование Чтобы запустить юнит-тесты, выполните `python -m unittest tests.py` в вашем терминале.
@extends('layouts.auth') @section('content') <div class="p-6 bg-indigo-900 min-h-screen flex justify-center items-center"> <div class="w-full max-w-md"> <div class="flex justify-center text-white mb-6 text-5xl font-bold"> <img class="w-48" alt="addy.io Logo" src="/svg/logo.svg"> </div> <div class="flex flex-col break-words bg-white border-2 rounded-lg shadow-lg overflow-hidden"> <form method="POST" action="{{ route('password.email') }}"> @csrf <div class="px-6 py-8 md:p-10"> <h1 class="text-center font-bold text-3xl"> {{ __('Reset Password') }} </h1> <div class="mx-auto mt-6 w-24 border-b-2 border-grey-200"></div> @if (session('status')) <div class="text-sm border-t-8 rounded text-green-700 border-green-600 bg-green-100 px-3 py-4 mt-4" role="alert"> {{ session('status') }} </div> @endif <div class="mt-8 mb-6"> <div class="flex items-center justify-between mb-2"> <label for="username" class="block text-grey-700 text-sm font-medium leading-6"> {{ __('Username') }} </label> <div class="text-sm"> <a class="whitespace-nowrap no-underline font-medium text-indigo-600 hover:text-indigo-500" tabindex="-1" href="{{ route('username.reminder.show') }}"> {{ __('Forgot Username?') }} </a> </div> </div> <input id="username" type="text" class="appearance-none bg-grey-100 rounded w-full p-3 text-grey-700 focus:ring{{ $errors->has('username') ? ' border-red-500' : '' }}" name="username" value="{{ old('username') }}" placeholder="johndoe" required> <p class="text-xs mt-1 text-grey-600">Note: your username is <b>not</b> your email address.</p> @if ($errors->has('username')) <p class="text-red-500 text-xs italic mt-4"> {{ $errors->first('username') }} </p> @endif </div> <div class="flex flex-wrap mb-4 items-center"> <label for="captcha" class="block w-full text-grey-700 text-sm"> Human Verification (click image to refresh) </label> <div class="flex grow flex-wrap"> <img src="{{captcha_src('mini')}}" onclick="this.src='/captcha/mini?'+Math.random()" class="cursor-pointer shrink-0 h-12 w-16 mr-2 mt-2" title="Click to refresh image" alt="captcha"> <input id="captcha" type="text" class="grow mt-2 appearance-none bg-grey-100 rounded p-3 text-grey-700 focus:ring{{ $errors->has('captcha') ? ' border-red-500' : '' }}" name="captcha" placeholder="Enter the text you see" required> </div> @if ($errors->has('captcha')) <p class="text-red-500 text-xs italic mt-4"> {{ $errors->first('captcha') }} </p> @endif </div> </div> <div class="px-6 md:px-10 py-4 bg-grey-50 border-t border-grey-100 flex flex-wrap items-center justify-center"> <button type="submit" class="bg-cyan-400 w-full hover:bg-cyan-300 text-cyan-900 font-bold py-3 px-4 rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"> {{ __('Send Password Reset Link') }} </button> </div> </form> </div> <p class="w-full text-xs text-center mt-6"> <a class="text-white hover:text-indigo-50 no-underline" href="{{ route('login') }}"> Back to login </a> </p> </div> </div> @endsection
import React, { useState, useEffect } from 'react' import Swal from 'sweetalert2/dist/sweetalert2.js' import { getCoworkers } from '../services/users.service' import Searchbar from '../components/Searchbar' import Card from '../components/Card' import styles from '../assets/styles/views/Coworkers.module.scss' export default function Coworkers() { const [coworkers, setCoworkers] = useState() const [search, setSearch] = useState('') // string dans l'input const [searchType, setSearchType] = useState('') // select du type de la recherche const [category, setCategory] = useState('') // select du service const [unset, setUnset] = useState(0) const [filtered, setFiltered] = useState([]) // tableau filtré useEffect( () => { getCoworkers().then( element => setCoworkers(element) ).catch( error => console.log(error.response) ) }, [unset]) useEffect( () => { const searchString = '/^' + search + '.*$/' if( searchType == 'name' ) { setFiltered(coworkers?.filter( element => ( ( element.firstname.toLowerCase().match(searchString.toLowerCase()) || element.firstname.toLowerCase().match(search.toLowerCase()) || element.lastname.toLowerCase().match(searchString.toLowerCase()) || element.lastname.toLowerCase().match(search.toLowerCase()) ) && element.service.toLowerCase().match(category.toLowerCase()) )) ) } else if( searchType == 'city') { setFiltered(coworkers?.filter( element => ( ( element.city.toLowerCase().match(searchString.toLowerCase()) || element.city.toLowerCase().match(search.toLowerCase()) ) && element.service.toLowerCase().match(category.toLowerCase()) )) ) } }, [search, searchType, category] /* chaque fois que le string dans l'input change */ ) return ( <main className="main"> <section className={`container ${styles.coworkers}`}> <div className={`row ${styles.searchbar}`}> <Searchbar setSearch={ setSearch } setSearchType={ setSearchType } setCategory={ setCategory } /> </div> <div className="row"> <div className={`${ styles.wrapper } mx-auto row justify-content-between justify-content-xl-start`}> { (search === '' && category === '') ? // si le champ texte est vide et pas de service sélectionné <> { coworkers && coworkers?.map( (element, index) => { return <Card key={ index } data={ element } setUnset={ setUnset } unset={ unset } /> }) } </> : <> { filtered && filtered?.map( (element, index) => { return <Card key={ index } data={ element } setUnset={ setUnset } unset={ unset } /> }) } </> } </div> </div> </section> </main> ) }
package com.jslhrd.testa; abstract class Person { String name; boolean gender; int age; Person(String name, boolean gender, int age) { this.name = name; this.gender = gender; this.age = age; } abstract void namePrint(); abstract String getGender(); } class ExamPerson extends Person { ExamPerson(String name, boolean gender, int age){ super(name,gender,age); } @Override void namePrint() { System.out.println("이름: "+name); }@Override String getGender() { /* if(gender) { return "남자"; }else { return "여자"; }*/ String gender = (this.gender)?"남자":"여자"; return gender; } } public class Exam_03 { public static void main(String[] args) { Person p = new ExamPerson("이학생", false, 34); p.namePrint(); String gender = p.getGender(); System.out.println("이학생은 " + gender + " 입니다"); } }
from AST import * from Visitor import * from Utils import Utils from StaticError import * class TypePlaceholder: count = 0 def __init__(self): self.t = None self.type_id = TypePlaceholder.count TypePlaceholder.count += 1 def setType(self, t): self.t = t def getType(self): return self.t def __str__(self): return f"${self.type_id}" class FnType(Type): def __init__(self, arg_types, return_type): self.argTypes = arg_types self.returnType = return_type class TypeEnvironment: def __init__(self): self.scopes = [] self.functions = {} self.beginScope() def declare(self, name, var_type): """Declare a variable name whose type is var_type.""" scope = self.scopes[-1] scope[name] = var_type def declareFn(self, fn_name, fn_type): """Declare a function.""" self.functions[fn_name] = fn_type def isInCurrentScope(self, name): return name in self.scopes[-1] def getType(self, name): """Get type of the variable.""" for scope in reversed(self.scopes): try: return scope[name] except KeyError: continue return None def setType(self, name, var_type): """Set type of the variable.""" for scope in reversed(self.scopes): if name in scope: scope[name] = var_type return def setReturnType(self, fn_name, return_type): """Set return type of the function.""" self.functions[fn_name].returnType = return_type def getFnType(self, fn_name): try: return self.functions[fn_name] except KeyError: return None def beginScope(self): self.scopes.append(dict()) def endScope(self): self.scopes.pop() def compatibleTypes(lhs_type, rhs_type): # Type variable can be any type if isinstance(lhs_type, TypePlaceholder): return True if lhs_type.getType() is None else compatibleTypes(lhs_type.getType(), rhs_type) if not (type(lhs_type) is type(rhs_type)): return False if isinstance(lhs_type, ArrayType): return (type(lhs_type.eleType) is type(rhs_type.eleType) and len(lhs_type.size) == len(rhs_type.size) and all([i == j for i, j in zip(lhs_type.size, rhs_type.size)])) return True def getOperandType(op): if op in ['+', '-', '*', '/', '%', '>', '<', '>=', '<=', '=', '!=']: return NumberType() if op in ['and', 'or', 'not']: return BoolType() return StringType() def getResultType(op): if op in ['+', '-', '*', '/', '%']: return NumberType() if op in ['and', 'or', 'not', '=', '==', '!=', '>=', '<=', '>', '<']: return BoolType() return StringType() class IllegalArrayLiteral(Exception): def __init__(self, ast): self.ast = ast def __str__(self): return f"IllegalArrayLiteral({self.ast})" class StaticChecker(BaseVisitor, Utils): """Static checker is used to check if the input program satisfies all semantic constraints defined by the ZCode programming language. While checking, it also has to infer types of all unknown-type variables. For instance: ========== Example snippet ========== dynamic x number y x <- y ========== Example snippet ========== In the above example, the static checker has to infer the type of 'x'. From the declaration of 'y' and the assignment statement, so the checker can conclude that the type of 'x' must be number. The strategy used by the checker is as follows: It uses a stack represented by a list to store all the constraints for expressions. Whenever the checker visits an expression, it peeks the top constraint in the stack, and compare the return type of the expression (which can be deduced from the operator, e.g, result of an addition expression must have return a number) with the constraint. If the constraint is satisfied, it proceeds to add the constraints for the expression's operands and visit these operands. If all of the constraints for operands are satisfied, the visit function returns True to indicate that the expression satisfies the constraint. For example, in this expression: number x <- a + b In this context, types of a and b haven't been deduced yet. The visitor visits the declaration and add the type constraint: [number] This means that, the initialization expression must return a number. Next, it proceeds to visit the initialization expression. It compares the return type of '+' with the top constraint in the stack: number = number So, the return type constraint is satisfied. Note that, if the return type constraint were not satisfied in this case, then the visitor would return false. The operands' types of '+' must be numbers, so the checker pushes a constraint to the stack: [number, number] Then, it visits each operand. the type of x hasn't been inferred yet, so we use the return type constraint to infer its type. The type of 'x' must be number. The checker does the same thing for 'b', and it infers that b's type must be number too. For some cases, we cannot infer the type of a variable from the expression. For example: ========== Example snippet ========== dynamic x number y <- x[10] ========== Example snippet ========== This case is ambiguous. Although we know that x is an array of numbers, but what about its size? The checker raises an exception if it encounters such cases. """ def __init__(self, prog: Program): self.prog = prog self.typeEnv = TypeEnvironment() # Used to check the current position of the checker in the AST. self.loopCount = 0 self.inArray = 0 # Used to check if there is a function without definition. self.funcDecls = {} self.currentFnName = "" self.typeConstraints = [] self.builtin_functions = { "readNumber": FnType(return_type=NumberType(), arg_types=[]), "writeNumber": FnType(return_type=VoidType(), arg_types=[NumberType()]), "readBool": FnType(return_type=BoolType(), arg_types=[]), "writeBool": FnType(return_type=VoidType(), arg_types=[BoolType()]), "readString": FnType(return_type=StringType(), arg_types=[]), "writeString": FnType(return_type=VoidType(), arg_types=[StringType()]) } for fn_name, fn_type in self.builtin_functions.items(): self.typeEnv.declareFn(fn_name, fn_type) def check(self): if self.prog.decl == []: raise NoEntryPoint() self.prog.accept(self, None) # Check for no-function-definition error for fn_name, fn_decl in self.funcDecls.items(): if not fn_decl.body: raise NoDefinition(fn_name) if 'main' not in self.funcDecls: raise NoEntryPoint() main_fn_type = self.typeEnv.getFnType('main') if not (main_fn_type and isinstance(main_fn_type, FnType) and isinstance(main_fn_type.returnType, VoidType) and main_fn_type.argTypes == []): raise NoEntryPoint() def setCurrentFnName(self, name: str): self.currentFnName = name def getCurrentFnName(self) -> str: return self.currentFnName def isFunctionRedeclaration(self, ast: FuncDecl): fn_name = ast.name.name if fn_name in self.builtin_functions.keys(): return True fn_type = self.typeEnv.getFnType(fn_name) if not fn_type: return False # we need to use function declaration instead of function type in this case because we # also need to check if the previous declaration has a body. prev_decl = self.funcDecls[fn_name] if(prev_decl.body or not ast.body or len(prev_decl.param) != len(ast.param)): return True return not all([compatibleTypes(pair[0].varType, pair[1].varType) for pair in zip(prev_decl.param, ast.param)]) def beginScope(self): self.typeEnv.beginScope() def endScope(self): self.typeEnv.endScope() def visitProgram(self, ast: Program, param): for decl in ast.decl: decl.accept(self, None) def visitFuncDecl(self, ast: FuncDecl, param): fn_name = ast.name.name if self.isFunctionRedeclaration(ast): raise Redeclared(Function(), fn_name) self.funcDecls[fn_name] = ast fn_type = self.typeEnv.getFnType(fn_name) if not fn_type: fn_type = FnType( arg_types=[decl.varType for decl in ast.param], return_type=None ) self.typeEnv.declareFn(fn_name, fn_type) assert isinstance(fn_type, FnType) self.funcDecls[fn_name] = ast self.setCurrentFnName(fn_name) # scope for parameters self.beginScope() for param_decl in ast.param: try: param_decl.accept(self, None) except Redeclared as exception: exception.kind = Parameter() raise exception if ast.body: ast.body.accept(self, None) if not fn_type.returnType: fn_type.returnType = VoidType() self.endScope() def visitVarDecl(self, ast: VarDecl, param): var_name = ast.name.name if self.typeEnv.isInCurrentScope(var_name): raise Redeclared(Variable(), var_name) var_type = ast.varType if ast.varType else TypePlaceholder() self.typeConstraints.append(var_type) try: if ast.varInit and not ast.varInit.accept(self, None): raise TypeMismatchInStatement(ast) except TypeCannotBeInferred: raise TypeCannotBeInferred(ast) except TypeMismatchInStatement: raise TypeMismatchInStatement(ast) self.typeConstraints.pop() if isinstance(var_type, TypePlaceholder) and var_type.getType() is not None: var_type = var_type.getType() self.typeEnv.declare(var_name, var_type) def visitAssign(self, ast: Assign, param): self.typeConstraints.append(TypePlaceholder()) try: ast.rhs.accept(self, None) except TypeCannotBeInferred as exception: if (exception.stmt == ast.rhs and not (isinstance(exception.stmt, Id) or isinstance(exception.stmt, CallExpr))): raise TypeCannotBeInferred(ast) # empty the type placeholder, for cases that it is mofified by the visitor self.typeConstraints[-1] = TypePlaceholder() if self.typeConstraints[-1].getType(): self.typeConstraints[-1] = self.typeConstraints[-1].getType() try: if not ast.lhs.accept(self, None): raise TypeMismatchInStatement(ast) except TypeCannotBeInferred: raise TypeCannotBeInferred(ast) else: # rhs's type is not inferred. Proceed to infer the lhs's type. # if the type of lhs still cannot be inferred, raise the exception. try: ast.lhs.accept(self, None) # if not self.typeConstraints[-1].getType(): # raise TypeCannotBeInferred(ast) except TypeCannotBeInferred as e: e.stmt = ast raise e self.typeConstraints[-1] = self.typeConstraints[-1].getType() try: if not ast.rhs.accept(self, None): raise TypeMismatchInStatement(ast) except TypeCannotBeInferred: raise TypeCannotBeInferred(ast) self.typeConstraints.pop() def visitBinaryOp(self, ast: BinaryOp, param): type_constraint = self.typeConstraints[-1] if not compatibleTypes(type_constraint, getResultType(ast.op)): return False if isinstance(type_constraint, TypePlaceholder) and type_constraint.getType() is None: type_constraint.setType(getResultType(ast.op)) self.typeConstraints.append(getOperandType(ast.op)) if not (ast.left.accept(self, None) and ast.right.accept(self, None)): raise TypeMismatchInExpression(ast) self.typeConstraints.pop() return True def visitUnaryOp(self, ast: UnaryOp, param): type_constraint = self.typeConstraints[-1] if not compatibleTypes(type_constraint, getResultType(ast.op)): return False if isinstance(type_constraint, TypePlaceholder) and type_constraint.getType() is None: type_constraint.setType(getResultType(ast.op)) self.typeConstraints.append(getOperandType(ast.op)) if not ast.operand.accept(self, None): raise TypeMismatchInExpression(ast) self.typeConstraints.pop() return True def visitBreak(self, ast, param): if self.loopCount == 0: raise MustInLoop(ast) def visitContinue(self, ast, param): if self.loopCount == 0: raise MustInLoop(ast) def visitArrayCell(self, ast: ArrayCell, param): self.typeConstraints.append(NumberType()) for idx in ast.idx: satisfied_constr = idx.accept(self, None) if not satisfied_constr: raise TypeMismatchInExpression(ast) self.typeConstraints.pop() # We cannot conclude that a variable of unknown type is an array if the variable is used # in an index expression. # for example, this case is ambiguous: # dynamic x # number y <- x[1, 2, 3] # Although we can infer the type of x[1, 2, 3], but what about x? It is for sure an array of # number, but what is its size? [4, 4, 4]? [10, 10, 10]? # # So, we cannot infer the type of the array in this case. An 'invalid array' (its size is # empty) is pushed to the list of constraints so the checker can use it to determine if it # is able to infer the type of a variable or the return type of a function. self.typeConstraints.append(ArrayType(eleType=self.typeConstraints[-1], size=[])) if not ast.arr.accept(self, None): # Determine whether the type mismatch occurred in the index expression, or in the # upper expression if isinstance(ast.arr, Id): arr_name = ast.arr.name if not isinstance(self.typeEnv.getType(arr_name), ArrayType): raise TypeMismatchInExpression(ast) elif isinstance(ast.arr, CallExpr): fn_name = ast.arr.name.name fn_type = self.typeEnv.getFnType(fn_name) if not isinstance(fn_type.returnType, ArrayType): raise TypeMismatchInExpression(ast) self.typeConstraints.pop() return False self.typeConstraints.pop() return True def visitCallStmt(self, ast: CallStmt, param): fn_name = ast.name.name fn_type = self.typeEnv.getFnType(fn_name) if not fn_type: raise Undeclared(Function(), fn_name) if (not isinstance(fn_type, FnType) or len(ast.args) != len(fn_type.argTypes) or not (fn_type.returnType is None or isinstance(fn_type.returnType, VoidType))): raise TypeMismatchInStatement(ast) if not fn_type.returnType: fn_type.returnType = VoidType() for arg_type, arg_expr in zip(fn_type.argTypes, ast.args): if not isinstance(arg_type, ArrayType): self.typeConstraints.append(arg_type) if not arg_expr.accept(self, None): raise TypeMismatchInStatement(ast) self.typeConstraints.pop() else: self.typeConstraints.append(TypePlaceholder()) arg_expr.accept(self, None) passed_param_type = self.typeConstraints.pop().getType() if not isinstance(passed_param_type, ArrayType) or passed_param_type.size != arg_type.size: raise TypeMismatchInStatement(ast) def visitCallExpr(self, ast: CallExpr, param): fn_name = ast.name.name fn_type = self.typeEnv.getFnType(fn_name) if not fn_type: raise Undeclared(Function(), fn_name) if (len(ast.args) != len(fn_type.argTypes) or isinstance(fn_type.returnType, VoidType)): raise TypeMismatchInExpression(ast) for arg_type, arg_expr in zip(fn_type.argTypes, ast.args): if not isinstance(arg_type, ArrayType): self.typeConstraints.append(arg_type) if not arg_expr.accept(self, None): raise TypeMismatchInExpression(ast) self.typeConstraints.pop() else: self.typeConstraints.append(TypePlaceholder()) arg_expr.accept(self, None) passed_param_type = self.typeConstraints.pop().getType() if not isinstance(passed_param_type, ArrayType) or passed_param_type.size != arg_type.size: raise TypeMismatchInExpression(ast) return_type_constr = self.typeConstraints[-1] if not fn_type.returnType: # infer function's return type if (isinstance(return_type_constr, ArrayType) and return_type_constr.size == []): # invalid array type raise TypeCannotBeInferred(ast) if isinstance(return_type_constr, TypePlaceholder) and not return_type_constr.getType(): raise TypeCannotBeInferred(ast) fn_type.returnType = return_type_constr if isinstance(return_type_constr, TypePlaceholder): return_type_constr.setType(fn_type.returnType) if isinstance(return_type_constr, ArrayType) and return_type_constr.size == [] and isinstance(fn_type.returnType, ArrayType): if isinstance(return_type_constr.eleType, TypePlaceholder): return_type_constr.eleType.setType(fn_type.returnType.eleType) return compatibleTypes(return_type_constr.eleType, fn_type.returnType.eleType) return compatibleTypes(return_type_constr, fn_type.returnType) def visitBlock(self, ast: Block, param): self.beginScope() for stmt in ast.stmt: stmt.accept(self, None) self.endScope() def visitIf(self, ast: If, param): self.typeConstraints.append(BoolType()) try: if not ast.expr.accept(self, None): raise TypeMismatchInStatement(ast) except TypeCannotBeInferred: raise TypeCannotBeInferred(ast) self.beginScope() ast.thenStmt.accept(self, None) self.endScope() for cond, stmt in ast.elifStmt: try: if not cond.accept(self, None): raise TypeMismatchInStatement(ast) except TypeCannotBeInferred: raise TypeCannotBeInferred(ast) self.beginScope() stmt.accept(self, None) self.endScope() if ast.elseStmt: self.beginScope() ast.elseStmt.accept(self, None) self.endScope() self.typeConstraints.pop() def visitFor(self, ast: For, param): self.loopCount += 1 try: self.typeConstraints.append(NumberType()) if not ast.name.accept(self, None): raise TypeMismatchInStatement(ast) self.typeConstraints.append(BoolType()) if not ast.condExpr.accept(self, None): raise TypeMismatchInStatement(ast) self.typeConstraints.append(NumberType()) if not ast.updExpr.accept(self, None): raise TypeMismatchInStatement(ast) except TypeCannotBeInferred: raise TypeCannotBeInferred(ast) self.typeConstraints = self.typeConstraints[:-3] ast.body.accept(self, None) self.loopCount -= 1 def visitReturn(self, ast: Return, param): fn_name = self.getCurrentFnName() fn_type = self.typeEnv.getFnType(fn_name) assert isinstance(fn_type, FnType) if not ast.expr: if not fn_type.returnType: fn_type.returnType = VoidType() elif not isinstance(fn_type, VoidType): raise TypeMismatchInStatement(ast) else: self.typeConstraints.append(fn_type.returnType or TypePlaceholder()) try: if not ast.expr.accept(self, None): raise TypeMismatchInStatement(ast) except TypeCannotBeInferred: raise TypeCannotBeInferred(ast) return_type = self.typeConstraints.pop() if isinstance(return_type, TypePlaceholder): fn_type.returnType = return_type.getType() def visitArrayLiteral(self, ast: ArrayLiteral, param): assert ast.value != [] # print("===") # print(ast) # for constr in self.typeConstraints: # print(str(constr)) # print("===") type_constr = self.typeConstraints[-1] if not isinstance(type_constr, (ArrayType, TypePlaceholder)): return False if (isinstance(type_constr, TypePlaceholder) and not isinstance(type_constr.getType(), (ArrayType, type(None)))): return False if isinstance(type_constr, TypePlaceholder): # an example of unknown-type array literal: # var x <- [1, 2, 3, 4, 5] return self.visitUnknownTypeArrLit(ast, None) else: # an example of known-type array literal: # number x[5] <- [1, 2, 3, 4, 5] return self.visitKnownTypeArrLit(ast, None) def visitUnknownTypeArrLit(self, ast: ArrayLiteral, param): assert isinstance(self.typeConstraints[-1], TypePlaceholder) # constraint applied for this array arr_type_constr = self.typeConstraints[-1] self.typeConstraints.append(TypePlaceholder()) ast.value[0].accept(self, None) first_ele_type = self.typeConstraints.pop() first_ele_type = first_ele_type.getType() self.typeConstraints.append(first_ele_type) for expr in ast.value[1:]: if not expr.accept(self, None): raise TypeMismatchInExpression(ast) ele_type_constr = self.typeConstraints.pop() if isinstance(ele_type_constr, TypePlaceholder): ele_type_constr = ele_type_constr.getType() # Infer type of 'this' array arr_type = None if isinstance(ele_type_constr, ArrayType): arr_type = ArrayType([float(len(ast.value))] + ele_type_constr.size, ele_type_constr.eleType) else: # element type must be scalar type in this case arr_type = ArrayType([float(len(ast.value))], ele_type_constr) if not arr_type_constr.getType(): arr_type_constr.setType(arr_type) else: # If this array has an constraint applied to itself # this case can happen for subarrays arr_type_constr = arr_type_constr.getType() assert isinstance(arr_type_constr, ArrayType) if len(arr_type_constr.size) != len(arr_type.size) or not compatibleTypes(arr_type_constr.eleType, arr_type.eleType): return False inferred_size = list(map(lambda pair: max(pair), zip(arr_type_constr.size, arr_type.size))) arr_type_constr.size = inferred_size return True def visitKnownTypeArrLit(self, ast: ArrayLiteral, param): assert isinstance(self.typeConstraints[-1], ArrayType) type_constr = self.typeConstraints[-1] # length of the array literal must be exactly equal to the length of the array type if len(ast.value) != type_constr.size[0]: return False ele_type_constr = None if len(type_constr.size) != 1: ele_type_constr = ArrayType(eleType=type_constr.eleType, size=type_constr.size[1:]) else: ele_type_constr = type_constr.eleType self.typeConstraints.append(ele_type_constr) # infer first element's type current_constr_count = len(self.typeConstraints) try: self.typeConstraints.append(TypePlaceholder()) ast.value[0].accept(self, None) self.typeConstraints[-1] = self.typeConstraints[-1].getType() except TypeCannotBeInferred as e: self.typeConstraints = self.typeConstraints[:current_constr_count + 1] self.typeConstraints[-1] = ele_type_constr # print(str(self.typeConstraints[-1])) ast.value[0].accept(self, None) for expr in ast.value[1:]: satisfied_constr = expr.accept(self, None) if not satisfied_constr: raise TypeMismatchInExpression(ast) type_constr_1 = self.typeConstraints.pop() # constraint got from the first element type_constr_2 = self.typeConstraints.pop() # constraint got from the constraint applied to this array if not compatibleTypes(type_constr_1, type_constr_2): if len(self.typeConstraints) == 1: raise TypeMismatchInStatement(ast) else: return False return True def visitId(self, ast: Id, param): id_name = ast.name # if identifier refers to a function, retrieve its return type id_type = self.typeEnv.getType(id_name) if not id_type: raise Undeclared(Identifier(), id_name) if isinstance(id_type, TypePlaceholder): # Infer type of the identifier if (self.typeConstraints == [] or isinstance(self.typeConstraints[-1], TypePlaceholder)): raise TypeCannotBeInferred(ast) # Invalid array constraint is pushed when the index expression is visited. if isinstance(self.typeConstraints[-1], ArrayType) and self.typeConstraints[-1].size == []: raise TypeCannotBeInferred(ast) self.typeEnv.setType(id_name, self.typeConstraints[-1]) return True if self.typeConstraints == []: return True type_constr = self.typeConstraints[-1] if isinstance(type_constr, ArrayType) and isinstance(id_type, ArrayType) and type_constr.size == []: # this code is used for cases that we only need to ensure that a function call or # identifier just returns an array, regardless of its size. if isinstance(type_constr.eleType, TypePlaceholder): # resolve the type constraint of the index expression type_constr.eleType.setType(id_type.eleType) return compatibleTypes(type_constr.eleType, id_type.eleType) if isinstance(type_constr, TypePlaceholder): type_constr.setType(id_type) return compatibleTypes(self.typeConstraints[-1], id_type) def visitNumberLiteral(self, ast, param): type_constraint = self.typeConstraints[-1] if isinstance(type_constraint, TypePlaceholder): type_constraint.setType(NumberType()) return compatibleTypes(type_constraint, NumberType()) def visitBooleanLiteral(self, ast, param): type_constraint = self.typeConstraints[-1] if isinstance(type_constraint, TypePlaceholder): type_constraint.setType(BoolType()) return compatibleTypes(type_constraint, BoolType()) def visitStringLiteral(self, ast, param): type_constraint = self.typeConstraints[-1] if isinstance(type_constraint, TypePlaceholder): type_constraint.setType(StringType()) return compatibleTypes(type_constraint, StringType())
import { Count, CountSchema, Filter, FilterExcludingWhere, repository, Where, } from '@loopback/repository'; import { post, param, get, getModelSchemaRef, patch, put, del, requestBody, response, } from '@loopback/rest'; import {Request} from '../models'; import {RequestRepository} from '../repositories'; export class RequestController { constructor( @repository(RequestRepository) public requestRepository : RequestRepository, ) {} @post('/requests') @response(200, { description: 'Request model instance', content: {'application/json': {schema: getModelSchemaRef(Request)}}, }) async create( @requestBody({ content: { 'application/json': { schema: getModelSchemaRef(Request, { title: 'NewRequest', exclude: ['id'], }), }, }, }) request: Omit<Request, 'id'>, ): Promise<Request> { return this.requestRepository.create(request); } @get('/requests/count') @response(200, { description: 'Request model count', content: {'application/json': {schema: CountSchema}}, }) async count( @param.where(Request) where?: Where<Request>, ): Promise<Count> { return this.requestRepository.count(where); } @get('/requests') @response(200, { description: 'Array of Request model instances', content: { 'application/json': { schema: { type: 'array', items: getModelSchemaRef(Request, {includeRelations: true}), }, }, }, }) async find( @param.filter(Request) filter?: Filter<Request>, ): Promise<Request[]> { return this.requestRepository.find(filter); } @patch('/requests') @response(200, { description: 'Request PATCH success count', content: {'application/json': {schema: CountSchema}}, }) async updateAll( @requestBody({ content: { 'application/json': { schema: getModelSchemaRef(Request, {partial: true}), }, }, }) request: Request, @param.where(Request) where?: Where<Request>, ): Promise<Count> { return this.requestRepository.updateAll(request, where); } @get('/requests/{id}') @response(200, { description: 'Request model instance', content: { 'application/json': { schema: getModelSchemaRef(Request, {includeRelations: true}), }, }, }) async findById( @param.path.number('id') id: number, @param.filter(Request, {exclude: 'where'}) filter?: FilterExcludingWhere<Request> ): Promise<Request> { return this.requestRepository.findById(id, filter); } @patch('/requests/{id}') @response(204, { description: 'Request PATCH success', }) async updateById( @param.path.number('id') id: number, @requestBody({ content: { 'application/json': { schema: getModelSchemaRef(Request, {partial: true}), }, }, }) request: Request, ): Promise<void> { await this.requestRepository.updateById(id, request); } @put('/requests/{id}') @response(204, { description: 'Request PUT success', }) async replaceById( @param.path.number('id') id: number, @requestBody() request: Request, ): Promise<void> { await this.requestRepository.replaceById(id, request); } @del('/requests/{id}') @response(204, { description: 'Request DELETE success', }) async deleteById(@param.path.number('id') id: number): Promise<void> { await this.requestRepository.deleteById(id); } }
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.WeatherReport; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import static android.R.attr.onClick; /** * {@link NewsAdapter} is an {@link ArrayAdapter} that can provide the layout for each list item * based on a data source, which is a list of {@link News} objects. */ public class NewsAdapter extends ArrayAdapter<News> { /** Resource ID for the background color for this list of words */ //private int mColorResourceId; /** * Create a new {@link NewsAdapter} object. * * @param context is the current context (i.e. Activity) that the adapter is being created in. * @param scoop is the list of {@link News} to be displayed. */ public NewsAdapter(Context context, ArrayList<News> scoop) { super(context, 0, scoop); } @Override public View getView(int position, View convertView, ViewGroup parent) { // Check if an existing view is being reused, otherwise inflate the view View listItemView = convertView; if (listItemView == null) { listItemView = LayoutInflater.from(getContext()).inflate( R.layout.weather_list_item, parent, false); } // Get the {@link food} object located at this position in the list News currentES= getItem(position); // Find the TextView in the list_item.xml layout with the ID miwok_text_view. TextView artView = (TextView) listItemView.findViewById(R.id.art); // Get the mag from the currentES object and set this text on // the magView artView.setText( currentES.getCat() + "| " + currentES.getTitle()); // Find the TextView in the list_item.xml layout with the ID default_text_view. TextView date = (TextView) listItemView.findViewById(R.id.dat); // Get the location from the currentES object and set this text on // the locView. String ct = currentES.getDate(); date.setText(ct); TextView url = (TextView) listItemView.findViewById(R.id.curl); String u = currentES.getUrlLink(); url.setText(u); //TextView maxtView = (TextView) listItemView.findViewById(R.id.maxt); // Get the date from the currentES object and set this text on // the dateView. // String cmxt = currentES.getCat() + "°"; // maxtView.setText(cmxt); // TextView mintView = (TextView) listItemView.findViewById(R.id.mint); // Get the date from the currentES object and set this text on // the dateView. //String urlT = currentES.getUrlLink(); // mintView.setText(urlT); //get text from zip code input // Set the theme color for the list item //View textContainer = listItemView.findViewById(R.id.text_container); // Find the color that the resource ID maps to //int color = ContextCompat.getColor(getContext(), mColorResourceId); // Set the background color of the text container View //textContainer.setBackgroundColor(color); // Return the whole list item layout (containing 2 TextViews) so that it can be shown in // the ListView. return listItemView; } }
package org.example.results; import jakarta.persistence.ElementCollection; import jakarta.persistence.Entity; import jakarta.persistence.OneToMany; import jakarta.persistence.OneToOne; import org.example.questions.AbstractQuestion; import org.example.questions.MultipleChoiceQuestion; import org.example.questions.Question; import org.ibex.nestedvm.util.Seekable; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.data.general.DefaultPieDataset; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; @Entity public class PieChart extends AbstractResult implements Result{ @ElementCollection private Map<String, Integer> answerCount; private String question; private Integer questionID; private int numAnswers; /** * Constructor that takes in the question and initializes map. * * @param question * */ public PieChart(MultipleChoiceQuestion question) { this.question = question.getQuestion(); this.questionID = question.getId(); this.numAnswers = 0; this.answerCount = new HashMap<>(); for (String s : question.getChoices()) { answerCount.put(s, 0); } } /** * Default Constructor * */ public PieChart() { this.answerCount = new HashMap<>(); } /** * Adds a response to the map of String s * * @param s * */ @Override public void addResponse(String s) { answerCount.put(s, answerCount.get(s) + 1); } /** * Getter for the question associated with the result * * @return String * */ public String getQuestion() { return question; } /** * Setter for the question associated with the result * * @param question * */ public void setQuestion(Question question) { this.question = question.toString(); } /** * Getter for the map holding the count for each result * * @return Map of answers mapped to the amount of time that option was chosen * */ public Map<String, Integer> getAnswerCount() { return this.answerCount; } public String createChart() { DefaultPieDataset pieDataset = new DefaultPieDataset(); for (Map.Entry<String, Integer> entry: answerCount.entrySet()) { pieDataset.setValue(entry.getKey(), entry.getValue()); } JFreeChart pieChart = ChartFactory.createPieChart(question, pieDataset); pieChart.setBackgroundPaint(Color.WHITE); File file = new File("src/main/resources/public/" + questionID + "_PieChart.png"); BufferedImage bufferedImage = pieChart.createBufferedImage(1000, 1000); try { ImageIO.write(bufferedImage, "png", file); } catch (Exception exception) { exception.printStackTrace(); return ""; } System.out.println(questionID + "_PieChart.png saved"); return questionID + "_PieChart.png"; } }
defmodule App.KnnIndex do use GenServer @moduledoc """ A GenServer to load and handle the Index file for HNSWLib. It loads the index from the FileSystem if existing or from the table HnswlibIndex. It creates an new one if no Index file is found in the FileSystem and if the table HnswlibIndex is empty. It holds the index and the App.Image singleton table in the state. """ require Logger @dim 384 @max_elements 200 @upload_dir Application.app_dir(:app, ["priv", "static", "uploads"]) @saved_index if Application.compile_env(:app, :knnindex_indices_test, false), do: Path.join(@upload_dir, "indexes_test.bin"), else: Path.join(@upload_dir, "indexes.bin") # Client API ------------------ def start_link(args) do :ok = File.mkdir_p!(@upload_dir) GenServer.start_link(__MODULE__, args, name: __MODULE__) end def index_path do @saved_index end def save_index_to_db do GenServer.call(__MODULE__, :save_index_to_db) end def get_count do GenServer.call(__MODULE__, :get_count) end def add_item(embedding) do GenServer.call(__MODULE__, {:add_item, embedding}) end def knn_search(input) do GenServer.call(__MODULE__, {:knn_search, input}) end def not_empty_index do GenServer.call(__MODULE__, :not_empty) end # --------------------------------------------------- @impl true def init(args) do # Trying to load the index file index_path = Keyword.fetch!(args, :index) space = Keyword.fetch!(args, :space) case File.exists?(index_path) do # If the index file doesn't exist in the FileSystem, # we try to load it from the database. false -> {:ok, index, index_schema} = App.HnswlibIndex.maybe_load_index_from_db(space, @dim, @max_elements) {:ok, {index, index_schema, space}} # If the index file exists in the FileSystem, # we compare it the existing DB table and check for incoherences. true -> Logger.info("ℹ️ Index file found on disk. Let's compare it with the database...") App.Repo.get_by(App.HnswlibIndex, id: 1) |> case do nil -> {:stop, {:error, "Error comparing the index file with the one on the database. Incoherence on table."}} schema -> check_integrity(index_path, schema, space) end end end defp check_integrity(path, schema, space) do # We check the count of the images in the database and the total count of the index. with db_count <- App.Repo.all(App.Image) |> length(), {:ok, index} <- HNSWLib.Index.load_index(space, @dim, path), {:ok, index_count} <- HNSWLib.Index.get_current_count(index), true <- index_count == db_count do Logger.info("ℹ️ Integrity: ✅") {:ok, {index, schema, space}} # If it fails, we return an error. else false -> {:stop, {:error, "Integrity error. The count of images from index differs from the database."}} {:error, msg} -> Logger.error("⚠️ #{msg}") {:stop, {:error, msg}} end end @impl true def handle_call(:save_index_to_db, _, {index, index_schema, space} = state) do # We read the index file and try to update the index on the table as well. File.read(@saved_index) |> case do {:ok, file} -> {:ok, updated_schema} = index_schema |> App.HnswlibIndex.changeset(%{file: file}) |> App.Repo.update() {:reply, {:ok, updated_schema}, {index, updated_schema, space}} {:error, msg} -> {:reply, {:error, msg}, state} end end def handle_call(:get_count, _, {index, _, _} = state) do {:ok, count} = HNSWLib.Index.get_current_count(index) {:reply, count, state} end def handle_call({:add_item, embedding}, _, {index, _, _} = state) do # We add the new item to the index and update it. with :ok <- HNSWLib.Index.add_items(index, embedding), {:ok, idx} <- HNSWLib.Index.get_current_count(index), :ok <- HNSWLib.Index.save_index(index, @saved_index) do {:reply, {:ok, idx}, state} else {:error, msg} -> {:reply, {:error, msg}, state} end end def handle_call({:knn_search, nil}, _, state) do {:reply, {:error, "No index found"}, state} end def handle_call({:knn_search, input}, _, {index, _, _} = state) do # We search for the nearest neighbors of the input embedding. case HNSWLib.Index.knn_query(index, input, k: 1) do {:ok, labels, _distances} -> response = labels[0] |> Nx.to_flat_list() |> hd() |> then(fn idx -> App.Repo.get_by(App.Image, %{idx: idx + 1}) end) # TODO: add threshold on "distances" {:reply, response, state} {:error, msg} -> {:reply, {:error, msg}, state} end end def handle_call(:not_empty, _, {index, _, _} = state) do case HNSWLib.Index.get_current_count(index) do {:ok, 0} -> Logger.warning("⚠️ Empty index.") {:reply, :error, state} {:ok, _} -> {:reply, :ok, state} end end end
#include <iostream> using namespace std; class TimeHrMn { friend ostream& operator<<(ostream& output, const TimeHrMn &thm); public: TimeHrMn(int timeHours = 0, int timeMinutes = 0); void Print() const; TimeHrMn operator+(TimeHrMn rhs) ; private: int hours; int minutes; }; // Overload + operator for TimeHrMn TimeHrMn TimeHrMn::operator+(TimeHrMn rhs) { TimeHrMn timeTotal; timeTotal.hours = hours + rhs.hours; timeTotal.minutes = minutes + rhs.minutes; if (timeTotal.minutes >= 60) { timeTotal.hours = timeTotal.hours + 1; timeTotal.minutes = timeTotal.minutes - 60; } return timeTotal; } ostream& operator<<(ostream& output, const TimeHrMn &thm) { output << "H: " << thm.hours << ", " << "M: " << thm.minutes; return output; } TimeHrMn::TimeHrMn(int timeHours, int timeMinutes) { hours = timeHours; minutes = timeMinutes; } void TimeHrMn::Print() const { cout << "H:" << hours << ", " << "M:" << minutes << endl; } int main() { TimeHrMn time1(3, 22); TimeHrMn time2(2, 50); TimeHrMn timeTot; timeTot = time1 + time2; timeTot.Print(); cout << time1 << " + " << time2 << " = " << timeTot << endl; return 0; }
<?php namespace App\Exports; use Maatwebsite\Excel\Concerns\FromCollection; use Maatwebsite\Excel\Concerns\ShouldAutoSize; use Maatwebsite\Excel\Concerns\WithHeadings; use Maatwebsite\Excel\Concerns\WithStyles; use Maatwebsite\Excel\Concerns\WithTitle; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class ProjectReportBudgetSheet implements ShouldAutoSize, FromCollection, WithTitle, WithHeadings, WithStyles { /** * @return \Illuminate\Support\Collection */ protected $budgets; public function __construct($budgets) { $this->budgets = $budgets; } public function collection() { return collect($this->budgets); } public function title(): string { return 'Dự trù kinh phí'; } public function headings(): array { return [ 'Tên hạng mục', 'Số lượng', 'Đơn vị tính', 'Thành tiền', 'Trạng thái', ]; } public function styles(Worksheet $sheet) { return [ 1 => ['font' => ['bold' => true]], ]; } }
///Reverse String class Solution344 { void reverseString(List<String> s) { for (int i = 0; i < s.length ~/ 2; i++) { var temp = s[i]; s[i] = s[s.length - i - 1]; s[s.length - i - 1] = temp; } } ///BETTER WAY void reverseStringV2(List<String> s) { int left = 0, right = s.length - 1; //left is point on first element, right is on the last while (left < right) { String tmp = s[left]; //var is for storing value before changing s[left] = s[right]; s[right] = tmp; left++; right--; } } }
import type {QUnit} from '../../../helpers/QUnit'; import {CoreObject} from './../../../../src/core/geometry/Object'; import {GeoObjNode} from '../../../../src/engine/nodes/obj/Geo'; import {ObjectsLayoutSopNode} from '../../../../src/engine/nodes/sop/ObjectsLayout'; export function testenginenodessopObjectsLayout(qUnit: QUnit) { function createObject(geo1: GeoObjNode, x: number, y: number) { const box1 = geo1.createNode('box'); const transform1 = geo1.createNode('transform'); transform1.setInput(0, box1); transform1.p.s.x.set(x); transform1.p.s.y.set(y); return transform1; } async function getPositions(objectLayout1: ObjectsLayoutSopNode) { const container = await objectLayout1.compute(); const computedObjects = container.coreContent()!.threejsObjects(); return computedObjects.map((object) => object.position.toArray()); } async function getAttributes(objectLayout1: ObjectsLayoutSopNode, attribName: string): Promise<number[]> { const container = await objectLayout1.compute(); const computedObjects = container.coreContent()!.threejsObjects(); return computedObjects.map((object) => CoreObject.attribValue(object, attribName) as number); } qUnit.test('sop/objectsLayout simple', async (assert) => { const geo1 = window.geo1; const obj1 = createObject(geo1, 1, 1); const obj2 = createObject(geo1, 2, 1); const obj3 = createObject(geo1, 4, 1); const objects = [obj1, obj2, obj3]; const merge1 = geo1.createNode('merge'); for (let i = 0; i < objects.length; i++) { merge1.setInput(i, objects[i]); } const objectsLayout1 = geo1.createNode('objectsLayout'); objectsLayout1.setInput(0, merge1); assert.deepEqual(await getPositions(objectsLayout1), [ [-3, 0, 0], [-1.5, 0, 0], [1.5, 0, 0], ]); objectsLayout1.p.maxLayoutWidth.set(3); assert.deepEqual(await getPositions(objectsLayout1), [ [-1.5, 0.5, 0], [0, 0.5, 0], [0, -0.5, 0], ]); }); qUnit.test('sop/objectsLayout with attributes', async (assert) => { const geo1 = window.geo1; const obj1 = createObject(geo1, 1, 1); const obj2 = createObject(geo1, 2, 1); const obj3 = createObject(geo1, 4, 1); const objects = [obj1, obj2, obj3]; const merge1 = geo1.createNode('merge'); for (let i = 0; i < objects.length; i++) { merge1.setInput(i, objects[i]); } const objectsLayout1 = geo1.createNode('objectsLayout'); objectsLayout1.setInput(0, merge1); objectsLayout1.p.addAttribs.set(true); objectsLayout1.p.addRowAttrib.set(true); objectsLayout1.p.addRowWidthInner.set(true); objectsLayout1.p.addRowWidthOuter.set(true); assert.deepEqual(await getAttributes(objectsLayout1, 'row'), [0, 0, 0]); assert.deepEqual(await getAttributes(objectsLayout1, 'rowWidthInner'), [4.5, 4.5, 4.5]); assert.deepEqual(await getAttributes(objectsLayout1, 'rowWidthOuter'), [7, 7, 7]); objectsLayout1.p.maxLayoutWidth.set(3); assert.deepEqual(await getAttributes(objectsLayout1, 'row'), [0, 0, 1]); assert.deepEqual(await getAttributes(objectsLayout1, 'rowWidthInner'), [1.5, 1.5, 0]); assert.deepEqual(await getAttributes(objectsLayout1, 'rowWidthOuter'), [3, 3, 4]); }); }
/* eslint-disable @typescript-eslint/naming-convention, camelcase */ import { Adresse, ConditionAcces, ConditionsAcces, Contact, Id, LabelNational, LabelsNationaux, LieuMediationNumerique, Localisation, ModaliteAccompagnement, ModalitesAccompagnement, Nom, Pivot, PublicAccueilli, PublicsAccueillis, Service, Services, ServicesError, Typologie, Typologies, Url } from '../../../models'; import { SchemaServiceDataInclusion, SchemaStructureDataInclusion } from '../schema-data-inclusion'; import { fromSchemaDataInclusion } from './from-schema-data-inclusion'; import { MandatorySiretOrRnaError } from './errors/mandatory-siret-or-rna.error'; describe('from schema data inclusion', (): void => { it("should get a minimal lieu de mediation numerique form a minimal structure d'inclusion and a minimal service d'inclusion", (): void => { const structure: SchemaStructureDataInclusion = { adresse: '12 BIS RUE DE LECLERCQ', code_postal: '51100', commune: 'Reims', date_maj: new Date('2022-10-10').toISOString(), id: 'structure-1', nom: 'Anonymal', siret: '43493312300029' }; const service: SchemaServiceDataInclusion = { id: 'structure-1-mediation-numerique', nom: 'Médiation numérique', source: 'Hubik', structure_id: 'structure-1', thematiques: ['numerique--devenir-autonome-dans-les-demarches-administratives'] }; const minimalLieuMediationNumerique: LieuMediationNumerique = fromSchemaDataInclusion([service], structure); expect(minimalLieuMediationNumerique).toStrictEqual<LieuMediationNumerique>({ id: Id('structure-1'), nom: Nom('Anonymal'), pivot: Pivot('43493312300029'), adresse: Adresse({ code_postal: '51100', commune: 'Reims', voie: '12 BIS RUE DE LECLERCQ' }), services: Services([Service.DevenirAutonomeDansLesDemarchesAdministratives]), date_maj: new Date('2022-10-10') }); }); it("should get a complete lieu de mediation numerique form a complete structure d'inclusion and a complete service d'inclusion", (): void => { const structure: SchemaStructureDataInclusion = { adresse: '12 BIS RUE DE LECLERCQ', code_postal: '51100', code_insee: '51454', complement_adresse: 'Le patio du bois de l’Aulne', commune: 'Reims', date_maj: new Date('2022-10-10').toISOString(), id: 'structure-1', nom: 'Anonymal', siret: '43493312300029', source: 'Hubik', accessibilite: 'https://acceslibre.beta.gouv.fr/app/29-lampaul-plouarzel/a/bibliotheque-mediatheque/erp/mediatheque-13/', courriel: '[email protected]', telephone: '+33180059880', site_web: 'https://www.laquincaillerie.tl/;https://m.facebook.com/laquincaillerienumerique/', horaires_ouverture: 'Mo-Fr 09:00-12:00,14:00-18:30; Sa 08:30-12:00', labels_nationaux: ['france-service', 'aptic'], labels_autres: ['SudLabs', 'Nièvre médiation numérique'], latitude: 43.52609, longitude: 5.41423, presentation_detail: 'Notre parcours d’initiation permet l’acquisition de compétences numériques de base. Nous proposons également un accompagnement à destination des personnes déjà initiées qui souhaiteraient approfondir leurs connaissances. Du matériel informatique est en libre accès pour nos adhérents tous les après-midis. En plus de d’accueillir les personnes dans notre lieu en semaine (sur rendez-vous), nous assurons une permanence le samedi matin dans la médiathèque XX.', presentation_resume: 'Notre association propose des formations aux outils numériques à destination des personnes âgées.', structure_parente: 'Pôle emploi', typologie: Typologie.TIERS_LIEUX }; const service: SchemaServiceDataInclusion = { id: 'structure-1-mediation-numerique', nom: 'Médiation numérique', source: 'Hubik', structure_id: 'structure-1', thematiques: [ 'numerique', 'numerique--devenir-autonome-dans-les-demarches-administratives', 'numerique--realiser-des-demarches-administratives-avec-un-accompagnement', 'numerique--prendre-en-main-un-smartphone-ou-une-tablette', 'numerique--prendre-en-main-un-ordinateur', 'numerique--utiliser-le-numerique-au-quotidien', 'numerique--approfondir-ma-culture-numerique', 'numerique--favoriser-mon-insertion-professionnelle', 'numerique--acceder-a-une-connexion-internet', 'numerique--acceder-a-du-materiel', 'numerique--s-equiper-en-materiel-informatique', 'numerique--creer-et-developper-mon-entreprise', 'numerique--creer-avec-le-numerique', 'numerique--accompagner-les-demarches-de-sante', 'numerique--promouvoir-la-citoyennete-numerique', 'numerique--soutenir-la-parentalite-et-l-education-avec-le-numerique' ], frais: ['gratuit-sous-conditions'], types: ['autonomie', 'delegation', 'accompagnement', 'atelier'], prise_rdv: 'https://www.rdv-solidarites.fr/', profils: [ 'seniors-65', 'familles-enfants', 'adultes', 'jeunes-16-26', 'public-langues-etrangeres', 'deficience-visuelle', 'surdite', 'handicaps-psychiques', 'handicaps-mentaux', 'femmes', 'personnes-en-situation-illettrisme' ] }; const lieuMediationNumerique: LieuMediationNumerique = fromSchemaDataInclusion([service], structure); expect(lieuMediationNumerique).toStrictEqual<LieuMediationNumerique>({ id: Id('structure-1'), nom: Nom('Anonymal'), pivot: Pivot('43493312300029'), adresse: Adresse({ code_postal: '51100', code_insee: '51454', commune: 'Reims', voie: '12 BIS RUE DE LECLERCQ', complement_adresse: 'Le patio du bois de l’Aulne' }), services: Services([ Service.DevenirAutonomeDansLesDemarchesAdministratives, Service.RealiserDesDemarchesAdministratives, Service.PrendreEnMainUnSmartphoneOuUneTablette, Service.PrendreEnMainUnOrdinateur, Service.UtiliserLeNumerique, Service.ApprofondirMaCultureNumerique, Service.FavoriserMonInsertionProfessionnelle, Service.AccederAUneConnexionInternet, Service.AccederADuMateriel, Service.EquiperEnMaterielInformatique, Service.CreerEtDevelopperMonEntreprise, Service.CreerAvecLeNumerique, Service.AccompagnerLesDemarchesDeSante, Service.PromouvoirLaCitoyenneteNumerique, Service.SoutenirLaParentalite ]), date_maj: new Date('2022-10-10'), localisation: Localisation({ latitude: 43.52609, longitude: 5.41423 }), typologies: Typologies([Typologie.TIERS_LIEUX]), contact: Contact({ telephone: '+33180059880', courriel: '[email protected]', site_web: [Url('https://www.laquincaillerie.tl/'), Url('https://m.facebook.com/laquincaillerienumerique/')] }), horaires: 'Mo-Fr 09:00-12:00,14:00-18:30; Sa 08:30-12:00', presentation: { resume: 'Notre association propose des formations aux outils numériques à destination des personnes âgées.', detail: 'Notre parcours d’initiation permet l’acquisition de compétences numériques de base. Nous proposons également un accompagnement à destination des personnes déjà initiées qui souhaiteraient approfondir leurs connaissances. Du matériel informatique est en libre accès pour nos adhérents tous les après-midis. En plus de d’accueillir les personnes dans notre lieu en semaine (sur rendez-vous), nous assurons une permanence le samedi matin dans la médiathèque XX.' }, source: 'Hubik', structure_parente: 'Pôle emploi', publics_accueillis: PublicsAccueillis([ PublicAccueilli.Seniors, PublicAccueilli.FamillesEnfants, PublicAccueilli.Adultes, PublicAccueilli.Jeunes, PublicAccueilli.LanguesEtrangeres, PublicAccueilli.DeficienceVisuelle, PublicAccueilli.Surdite, PublicAccueilli.HandicapsPsychiques, PublicAccueilli.HandicapsMentaux, PublicAccueilli.UniquementFemmes, PublicAccueilli.Illettrisme ]), conditions_acces: ConditionsAcces([ConditionAcces.GratuitSousCondition]), labels_nationaux: LabelsNationaux([LabelNational.FranceServices, LabelNational.APTIC]), labels_autres: ['SudLabs', 'Nièvre médiation numérique'], modalites_accompagnement: ModalitesAccompagnement([ ModaliteAccompagnement.Seul, ModaliteAccompagnement.AMaPlace, ModaliteAccompagnement.AvecDeLAide, ModaliteAccompagnement.DansUnAtelier ]), accessibilite: Url( 'https://acceslibre.beta.gouv.fr/app/29-lampaul-plouarzel/a/bibliotheque-mediatheque/erp/mediatheque-13/' ), prise_rdv: Url('https://www.rdv-solidarites.fr/') }); }); it('should fail when there is no allowed thematiques in data inclusion service', (): void => { const structure: SchemaStructureDataInclusion = { adresse: '12 BIS RUE DE LECLERCQ', code_postal: '51100', commune: 'Reims', date_maj: new Date('2022-10-10').toISOString(), id: 'structure-1', nom: 'Anonymal', siret: '43493312300029' }; const service: SchemaServiceDataInclusion = { id: 'structure-1-mediation-numerique', nom: 'Médiation numérique', source: 'Hubik', structure_id: 'structure-1' }; expect((): void => { fromSchemaDataInclusion([service], structure); }).toThrow(new ServicesError('service indéfini')); }); it('should fail when there is no siret or rna', (): void => { const structure: SchemaStructureDataInclusion = { adresse: '12 BIS RUE DE LECLERCQ', code_postal: '51100', commune: 'Reims', date_maj: new Date('2022-10-10').toISOString(), id: 'structure-1', nom: 'Anonymal' }; const service: SchemaServiceDataInclusion = { id: 'structure-1-mediation-numerique', nom: 'Médiation numérique', source: 'Hubik', structure_id: 'structure-1' }; expect((): void => { fromSchemaDataInclusion([service], structure); }).toThrow(new MandatorySiretOrRnaError()); }); it('should use RNA instead of siret when available', (): void => { const structure: SchemaStructureDataInclusion = { adresse: '12 BIS RUE DE LECLERCQ', code_postal: '51100', commune: 'Reims', date_maj: new Date('2022-10-10').toISOString(), id: 'structure-1', nom: 'Anonymal', rna: 'W9R2003255' }; const service: SchemaServiceDataInclusion = { id: 'structure-1-mediation-numerique', nom: 'Médiation numérique', source: 'Hubik', structure_id: 'structure-1', thematiques: ['numerique--devenir-autonome-dans-les-demarches-administratives'] }; const minimalLieuMediationNumerique: LieuMediationNumerique = fromSchemaDataInclusion([service], structure); expect(minimalLieuMediationNumerique).toStrictEqual<LieuMediationNumerique>({ id: Id('structure-1'), nom: Nom('Anonymal'), pivot: Pivot('W9R2003255'), adresse: Adresse({ code_postal: '51100', commune: 'Reims', voie: '12 BIS RUE DE LECLERCQ' }), services: Services([Service.DevenirAutonomeDansLesDemarchesAdministratives]), date_maj: new Date('2022-10-10') }); }); it('should geocoded insee code as default value', (): void => { const structure: SchemaStructureDataInclusion = { adresse: '12 BIS RUE DE LECLERCQ', code_postal: '51100', commune: 'Reims', date_maj: new Date('2022-10-10').toISOString(), id: 'structure-1', nom: 'Anonymal', siret: '43493312300029', _di_geocodage_code_insee: '51105' }; const service: SchemaServiceDataInclusion = { id: 'structure-1-mediation-numerique', nom: 'Médiation numérique', source: 'Hubik', structure_id: 'structure-1', thematiques: ['numerique--devenir-autonome-dans-les-demarches-administratives'] }; const minimalLieuMediationNumerique: LieuMediationNumerique = fromSchemaDataInclusion([service], structure); expect(minimalLieuMediationNumerique).toStrictEqual<LieuMediationNumerique>({ id: Id('structure-1'), nom: Nom('Anonymal'), pivot: Pivot('43493312300029'), adresse: Adresse({ code_postal: '51100', code_insee: '51105', commune: 'Reims', voie: '12 BIS RUE DE LECLERCQ' }), services: Services([Service.DevenirAutonomeDansLesDemarchesAdministratives]), date_maj: new Date('2022-10-10') }); }); it('should fail when there is no service associated with the structure', (): void => { const structure: SchemaStructureDataInclusion = { adresse: '12 BIS RUE DE LECLERCQ', code_postal: '51100', commune: 'Reims', date_maj: new Date('2022-10-10').toISOString(), id: 'structure-1', nom: 'Anonymal', rna: 'W9R2003255' }; expect((): void => { fromSchemaDataInclusion([], structure); }).toThrow(new ServicesError('service indéfini')); }); it('should merge two minimal services', (): void => { const structure: SchemaStructureDataInclusion = { adresse: '12 BIS RUE DE LECLERCQ', code_postal: '51100', commune: 'Reims', date_maj: new Date('2022-10-10').toISOString(), id: 'structure-1', nom: 'Anonymal', rna: 'W9R2003255' }; const service1: SchemaServiceDataInclusion = { id: 'structure-1-mediation-numerique', nom: 'Médiation numérique', source: 'Hubik', structure_id: 'structure-1', thematiques: ['numerique--devenir-autonome-dans-les-demarches-administratives'] }; const service2: SchemaServiceDataInclusion = { id: 'structure-1-mediation-numerique', nom: 'Médiation numérique', source: 'Hubik', structure_id: 'structure-1', thematiques: ['numerique--acceder-a-une-connexion-internet'] }; const minimalLieuMediationNumerique: LieuMediationNumerique = fromSchemaDataInclusion([service1, service2], structure); expect(minimalLieuMediationNumerique).toStrictEqual<LieuMediationNumerique>({ id: Id('structure-1'), nom: Nom('Anonymal'), pivot: Pivot('W9R2003255'), adresse: Adresse({ code_postal: '51100', commune: 'Reims', voie: '12 BIS RUE DE LECLERCQ' }), services: Services([Service.DevenirAutonomeDansLesDemarchesAdministratives, Service.AccederAUneConnexionInternet]), date_maj: new Date('2022-10-10') }); }); it('should merge two services with multiple values for frais', (): void => { const structure: SchemaStructureDataInclusion = { adresse: '12 BIS RUE DE LECLERCQ', code_postal: '51100', commune: 'Reims', date_maj: new Date('2022-10-10').toISOString(), id: 'structure-1', nom: 'Anonymal', rna: 'W9R2003255' }; const service1: SchemaServiceDataInclusion = { id: 'structure-1-mediation-numerique', nom: 'Médiation numérique', source: 'Hubik', structure_id: 'structure-1', thematiques: ['numerique--devenir-autonome-dans-les-demarches-administratives'], frais: ['payant'] }; const service2: SchemaServiceDataInclusion = { id: 'structure-1-mediation-numerique', nom: 'Médiation numérique', source: 'Hubik', structure_id: 'structure-1', thematiques: ['numerique--acceder-a-une-connexion-internet'], frais: ['gratuit'] }; const minimalLieuMediationNumerique: LieuMediationNumerique = fromSchemaDataInclusion([service1, service2], structure); expect(minimalLieuMediationNumerique).toStrictEqual<LieuMediationNumerique>({ id: Id('structure-1'), nom: Nom('Anonymal'), pivot: Pivot('W9R2003255'), adresse: Adresse({ code_postal: '51100', commune: 'Reims', voie: '12 BIS RUE DE LECLERCQ' }), services: Services([Service.DevenirAutonomeDansLesDemarchesAdministratives, Service.AccederAUneConnexionInternet]), date_maj: new Date('2022-10-10'), conditions_acces: ConditionsAcces([ConditionAcces.Payant, ConditionAcces.Gratuit]) }); }); it("should merge two complete services d'inclusion", (): void => { const structure: SchemaStructureDataInclusion = { adresse: '12 BIS RUE DE LECLERCQ', code_postal: '51100', commune: 'Reims', date_maj: new Date('2022-10-10').toISOString(), id: 'structure-1', nom: 'Anonymal', siret: '43493312300029' }; const service1: SchemaServiceDataInclusion = { id: 'structure-1-mediation-numerique', nom: 'Médiation numérique', source: 'Hubik', structure_id: 'structure-1', thematiques: [ 'numerique', 'numerique--devenir-autonome-dans-les-demarches-administratives', 'numerique--realiser-des-demarches-administratives-avec-un-accompagnement', 'numerique--prendre-en-main-un-smartphone-ou-une-tablette', 'numerique--prendre-en-main-un-ordinateur' ], frais: ['adhesion'], types: ['accompagnement', 'atelier'], prise_rdv: 'https://www.rdv-solidarites.fr/service1', profils: ['seniors-65', 'familles-enfants', 'adultes', 'jeunes-16-26'] }; const service2: SchemaServiceDataInclusion = { id: 'structure-1-mediation-numerique', nom: 'Médiation numérique', source: 'Hubik', structure_id: 'structure-1', thematiques: ['numerique--prendre-en-main-un-ordinateur', 'numerique--prendre-en-main-un-smartphone-ou-une-tablette'], frais: ['pass-numerique'], types: ['delegation', 'accompagnement', 'atelier'], prise_rdv: 'https://www.rdv-solidarites.fr/service2', profils: ['seniors-65', 'adultes', 'jeunes-16-26'] }; const minimalLieuMediationNumerique: LieuMediationNumerique = fromSchemaDataInclusion([service1, service2], structure); expect(minimalLieuMediationNumerique).toStrictEqual<LieuMediationNumerique>({ id: Id('structure-1'), nom: Nom('Anonymal'), pivot: Pivot('43493312300029'), adresse: Adresse({ code_postal: '51100', commune: 'Reims', voie: '12 BIS RUE DE LECLERCQ' }), services: Services([ Service.DevenirAutonomeDansLesDemarchesAdministratives, Service.RealiserDesDemarchesAdministratives, Service.PrendreEnMainUnSmartphoneOuUneTablette, Service.PrendreEnMainUnOrdinateur ]), date_maj: new Date('2022-10-10'), publics_accueillis: PublicsAccueillis([ PublicAccueilli.Seniors, PublicAccueilli.FamillesEnfants, PublicAccueilli.Adultes, PublicAccueilli.Jeunes ]), conditions_acces: ConditionsAcces([ConditionAcces.Adhesion, ConditionAcces.AccepteLePassNumerique]), modalites_accompagnement: ModalitesAccompagnement([ ModaliteAccompagnement.AvecDeLAide, ModaliteAccompagnement.DansUnAtelier, ModaliteAccompagnement.AMaPlace ]), prise_rdv: Url('https://www.rdv-solidarites.fr/service2') }); }); });
const { DataTypes } = require("sequelize"); // Exportamos una funcion que define el modelo // Luego le injectamos la conexion a sequelize. module.exports = (sequelize) => { // defino el modelo sequelize.define( "videogame", { id: { type: DataTypes.UUID, //TIPO UUID primaryKey: true, defaultValue: DataTypes.UUIDV4, //SE VAN A CREAR AUTOMATICAME }, name: { type: DataTypes.STRING, allowNull: false, unique: true, }, description: { type: DataTypes.TEXT, }, platforms: { type: DataTypes.ARRAY(DataTypes.STRING), }, background_image: { type: DataTypes.STRING, }, updated: { type: DataTypes.STRING, }, rating: { type: DataTypes.FLOAT, }, created: { type: DataTypes.BOOLEAN, defaultValue: true, }, }, { timestamps: false, } ); };
import { Injectable, OnDestroy } from '@angular/core'; import * as moment from 'moment'; import 'rxjs/add/operator/first'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { Observable } from 'rxjs/Observable'; import { Budget } from '../../../../core/models/budget.model'; import { Sale } from '../../../../core/models/sale.model'; import { ObservableResourceList } from '../../../../core/observable-resource-list'; import { BudgetService } from '../../../../core/services/budget.service'; import { SocketApiService } from '../../../../core/socket-api.service'; import { ActiveProjectService } from '../../../active-project.service'; @Injectable() export class CustomBudgetListService extends ObservableResourceList implements OnDestroy { readonly budgets: Observable<Budget[]> = this.subject.asObservable(); protected limit = 5; protected paginator: BehaviorSubject<number> = new BehaviorSubject(this.limit); protected cursor = Math.floor(new Date().getTime() / 1000).toString(); constructor(private sockets: SocketApiService, private activeProject: ActiveProjectService, private budgetService: BudgetService) { super(); this.activeProject.project.first().subscribe(project => { this.paginator.subscribe(limit => { this.pagination(this.budgetService.paginate(project.id, limit, this.cursor)).subscribe(budgets => this.add(budgets)); }); this.sockets.listenForProject(project.id, { 'sale_registered': sale => this.addSale(sale), 'sale_deleted': sale => this.removeSale(sale), 'custom_budget_created': budget => this.addBudget(budget), 'custom_budget_updated': budget => this.updateBudget(budget) }, this); }); } ngOnDestroy(): void { this.sockets.stopListening(this); super.ngOnDestroy(); } protected updateFromSnapshot() { this.snapshot = this.sort(this.snapshot); super.updateFromSnapshot(); } protected sort(budgets: Budget[]): Budget[] { return budgets.sort((previous, budget) => { if (moment(budget.endsAt).isBefore(previous.endsAt)) { return -1; } else if (moment(budget.endsAt).isAfter(previous.endsAt)) { return 1; } else { return 0; } }); } private addSale(sale: Sale) { this.snapshot.filter(budget => { return moment(sale.soldAt).isBetween(moment(budget.startsAt), moment(budget.endsAt)); }).forEach(budget => { const goal = budget.goals.find(innerGoal => innerGoal.teamMemberId === sale.teamMemberId); if (goal) { if (sale.value) { goal.progress += sale.value; } else { goal.progress += 1; } this.updateFromSnapshot(); } }); } private removeSale(sale: Sale) { this.snapshot.filter(budget => { return moment(sale.soldAt).isBetween(moment(budget.startsAt), moment(budget.endsAt)); }).forEach(budget => { const goal = budget.goals.find(innerGoal => innerGoal.teamMemberId === sale.teamMemberId); if (goal) { if (sale.value) { goal.progress -= sale.value; } else { goal.progress -= 1; } this.updateFromSnapshot(); } }); } private addBudget(budget: Budget) { this.snapshot.push(budget); this.updateFromSnapshot(); } private updateBudget(budget: Budget) { for (const key in this.snapshot) { if (this.snapshot[key].id === budget.id) { this.snapshot[key] = budget; } } this.updateFromSnapshot(); } }
import { Component } from '@angular/core'; import { DialogModule } from 'primeng/dialog'; import { ButtonModule } from 'primeng/button'; import emailjs, { EmailJSResponseStatus } from '@emailjs/browser'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { ReactiveFormsModule } from '@angular/forms'; import { UserService } from '../../service/auth.service'; import { MessageService } from 'primeng/api'; import { ToastModule } from 'primeng/toast'; import { JwtHelperService } from '@auth0/angular-jwt'; import { PasswordModule } from 'primeng/password'; import { DividerModule } from 'primeng/divider'; import { Route, Router } from '@angular/router'; @Component({ selector: 'app-forgot-password', standalone: true, imports: [ DialogModule, ButtonModule, CommonModule, FormsModule, ReactiveFormsModule, ToastModule, PasswordModule, DividerModule, ], templateUrl: './forgot-password.component.html', providers: [MessageService], }) export class ForgotPasswordComponent { visible: boolean = false; visibleModal: boolean = false; emailForm: FormGroup; codeValue: string = ''; data: any = {}; passNew: string = ''; passNewRepeat: string = ''; private jwtHelper = new JwtHelperService(); constructor( private formBuilder: FormBuilder, private useService: UserService, private messageService: MessageService, private router: Router ) { this.emailForm = formBuilder.group({ email: ['', [Validators.required, Validators.pattern(/^\S+@\S+\.\S+$/)]], }); } onSubmit() { if (this.emailForm.valid) { this.useService.sendMail(this.emailForm.value).subscribe( (data) => { this.messageService.add({ severity: 'info', summary: 'Info', detail: `Mã code đã được gửi đến gmail ${this.emailForm.value.email}`, }); this.data = data; setTimeout(() => { this.visible = true; }, 800); }, (error) => { console.log(error); this.messageService.add({ severity: 'error', summary: 'Error', detail: error.error.name, }); } ); } else { console.log('Form not valid. Please check the fields.'); } } handleCodeEmmail() { const isExpired = this.jwtHelper.isTokenExpired(this.data?.accessTokenCode); if (isExpired) { this.messageService.add({ severity: 'error', summary: 'Error', detail: 'Mã code đã hết thời hạn nhập !', }); } else { const decodedToken = this.jwtHelper.decodeToken( this.data?.accessTokenCode ); const soNguyen = parseInt(decodedToken.code.replace(/\s/g, ''), 10); if (soNguyen === Number(this.codeValue)) { this.visible = false; this.visibleModal = true; } else { this.messageService.add({ severity: 'error', summary: 'Error', detail: 'Mã code không chính xác !', }); } } } deleteCookie(cookieName: string) { document.cookie = cookieName + '=; expires = Thu, 01 Jan 1970 00:00:00 GMT'; } handleUpdatePassWord() { if (this.passNewRepeat.trim() === this.passNew.trim()) { const email = this.emailForm.value.email; const passNew = this.passNew; const data = { email, passNew }; this.useService.updateUser(data).subscribe( (data) => { this.messageService.add({ severity: 'success', summary: 'Success', detail: 'Cập nhật mật khẩu thành công', }); setTimeout(() => { this.router.navigate(['/login']); }, 800); this.deleteCookie('jwt'); }, (err) => { this.messageService.add({ severity: 'error', summary: 'Error', detail: 'Lỗi cập nhật mật khảu !', }); } ); } else { this.messageService.add({ severity: 'error', summary: 'Error', detail: 'Nhập lại mật khẩu không đúng !', }); } } closeDialog() { this.visible = false; } get email() { return this.emailForm.get('email'); } }
import React, { useState, useEffect } from 'react'; import { IconButton } from '@mui/material'; import { KeyboardArrowDown } from '@mui/icons-material'; import { styled } from '@mui/system'; const StyledScrollButton = styled(IconButton)({ position: 'fixed', bottom: 30, right: 1158, opacity: 0, transition: 'opacity 0.3s ease', zIndex: 9999, '&.show': { opacity: 1, }, }); const ScrollArrow = () => { const [showArrow, setShowArrow] = useState(false); useEffect(() => { const handleScroll = () => { const isBelowThreshold = window.scrollY > 10; setShowArrow(isBelowThreshold); }; window.addEventListener('scroll', handleScroll); return () => { window.removeEventListener('scroll', handleScroll); }; }, []); const scrollToTop = () => { window.scrollTo({ top: 0, behavior: 'smooth' }); }; return ( <StyledScrollButton aria-label='Scroll down' color='primary' size='large' onClick={scrollToTop} className={showArrow ? 'show' : ''} > <KeyboardArrowDown sx={{ fontSize: 60, color: '#D3D3D3' }} /> </StyledScrollButton> ); }; export default ScrollArrow;
import { Component, Input, OnInit } from '@angular/core'; import { createChart, CrosshairMode, IChartApi, IPriceLine, LineData, LineStyle, PriceLineOptions, Time } from 'lightweight-charts'; import { Ikline } from 'src/app/interfaces/pivotlevel/Ikline'; import { ILevel, LEVEL_TYPE, TYPE } from 'src/app/interfaces/pivotlevel/ILevel'; import { PivotlevelService } from 'src/app/services/pivotlevel/pivotlevel.service'; @Component({ selector: 'app-chart', templateUrl: './chart.component.html', styleUrls: ['./chart.component.less'] }) export class ChartComponent implements OnInit { klines: Ikline[] = []; levels: ILevel[] = []; chart: IChartApi = {} as IChartApi; candlestickSeries: any = null; filter = { symbol: 'BTCUSDT', interval: '1d', limit: 1000, }; methodTypeDefault = TYPE.fractal; lineLevelOptions: PriceLineOptions[] = []; priceLineLevels: IPriceLine[] = []; supportType = LEVEL_TYPE.support; @Input() symbol: string = ''; @Input() interval: string = ''; @Input() graphId: string = ''; @Input() indicators: boolean = false; LINE_COLOR = { red: 'rgba(255, 0, 0, 1)', green: 'rgba(0, 255, 0, 1)', blue: 'rgba(0, 0, 255, 1)' } constructor( private pivotlevelService: PivotlevelService ) { } ngOnInit(): void { this.filter.symbol = this.symbol; this.filter.interval = this.interval; if (this.symbol) { this.getKlines(this.indicators); this.getLevels(); } } reloadData() { this.getKlines(this.indicators); this.getLevels(); this.updateWatermark(); } ngAfterViewInit(): void { const graph: HTMLElement = document.getElementById(this.graphId) as HTMLElement; this.chart = createChart(graph, { width: graph.clientWidth, height: window.innerHeight - 50, layout: { textColor: '#d1d4dc', backgroundColor: '#000000', }, grid: { horzLines: {visible:false}, vertLines: {visible:false} }, crosshair: { mode: CrosshairMode.Normal, }, watermark: { visible: true, fontSize: 34, horzAlign: 'center', vertAlign: 'center', color: 'rgba(255, 255, 255, 0.4)', text: `${this.filter.symbol} ${this.filter.interval}`, }, }); this.candlestickSeries = this.chart.addCandlestickSeries(); this.chart.timeScale().fitContent(); } clearLineLevels() { if (this.priceLineLevels.length > 0) { let aux = this.priceLineLevels; aux.forEach((line) => { this.candlestickSeries.removePriceLine(line); }); this.priceLineLevels = []; this.lineLevelOptions = []; } } loadLineLevels() { this.lineLevelOptions.forEach((line) => { const aux = this.candlestickSeries.createPriceLine(line); this.priceLineLevels.push(aux); }); } getLevels(): void { this.clearLineLevels(); this.pivotlevelService .getLevels( this.filter.symbol, this.filter.interval, this.filter.limit, this.methodTypeDefault ) .subscribe((resp) => { this.levels = resp.data; this.levels.forEach((level) => { level.time = new Date(level.time as string).getTime() as Time; }); if (this.levels.length > 0) { this.levels.forEach((level) => { const line: PriceLineOptions = { price: level.value, color: '#fff', lineWidth: 1, lineStyle: LineStyle.Dotted, axisLabelVisible: true, title: '', lineVisible: true, }; this.lineLevelOptions.push(line); }); this.loadLineLevels(); } }); } updateWatermark() { this.chart.options().watermark.text = `${this.filter.symbol} ${this.filter.interval}`; } getKlines(indicators: boolean): void { this.pivotlevelService .getKlines(this.filter.symbol, this.filter.interval, this.filter.limit, indicators) .subscribe((resp) => { this.klines = resp.data; if (this.klines.length > 0) { if (indicators) { let sma200List = this.klines.map((kline) => {return { 'time': kline.time, 'value': kline.sma_200}}) as LineData[]; let sma50List = this.klines.map((kline) => {return { 'time': kline.time, 'value': kline.sma_50}}) as LineData[]; let ema13List = this.klines.map((kline) => {return { 'time': kline.time, 'value': kline.ema_13}}) as LineData[]; const sma200Line = this.chart.addLineSeries({ color: this.LINE_COLOR.red, lineWidth: 2 }); sma200Line.setData(sma200List); const sma50Line = this.chart.addLineSeries({ color: this.LINE_COLOR.blue, lineWidth: 2 }); sma50Line.setData(sma50List); const ema13Line = this.chart.addLineSeries({ color: this.LINE_COLOR.green, lineWidth: 2 }); ema13Line.setData(ema13List); } if (this.filter.interval === '5m') { let vwapList = this.klines.map((kline) => {return { 'time': kline.time, 'value': kline.vwap}}) as LineData[]; const vwapLine = this.chart.addLineSeries({ color: this.LINE_COLOR.blue, lineWidth: 2 }); vwapLine.setData(vwapList); this.klines.forEach((kline) => { // kline.time = this.subtractTimeFromDate(new Date(kline.time as string), 3).getTime() as Time; console.log(new Date(kline.time as string), kline.open); }); } try { this.candlestickSeries.setData(this.klines); } catch (error) { console.log(error); } } }); } subtractTimeFromDate(objDate: Date, intHours: number) { const numberOfMlSeconds = objDate.getTime(); let addMlSeconds = (intHours * 60) * 60000; return new Date(numberOfMlSeconds - addMlSeconds); } }
from tkinter import * from PIL import Image, ImageTk from tkinter import messagebox import cv2 import os import numpy as np class Train: def __init__(self,root) -> None: self.root = root self.root.geometry("1920x1020+0+0") self.root.title("Trainingthe Dataset") self.root.configure(background='lightblue') self.root.configure(bg='lightblue') name_lbl=Label(self.root,text="TRAIN DATA",font=('Times New Roman',36,'bold'),fg='#154c79',bg='lightblue') name_lbl.place(relx=0.5, rely=0.05, anchor='center') train_button = Image.open(r"images\train.jpg") train_button = train_button.resize((440,440)) self.phototrain_button = ImageTk.PhotoImage(train_button) train_button_1= Button(self.root,image = self.phototrain_button,cursor="hand2") train_button_1.place(relx=0.5, rely=0.4, anchor='center',width=440,height=440) train_button_2 = Button(self.root,text="TRAIN THE DATA ",command=self.train_classifier,cursor="hand2",font=('Quicksand',15),bg='Black',fg='white') train_button_2.place(relx=0.5, rely=0.65, anchor='center',width=720,height=40) close_button_2 = Button(self.root,command=self.exit,text="Close",cursor="hand2",font=('Quicksand',15),bg='black',fg='white',borderwidth=5) close_button_2.place(relx=0.5, rely=0.9, anchor='center',width=220,height=40) def exit(self): self.root.destroy() def train_classifier(self): data = ('data') path = [os.path.join(data,file) for file in os.listdir(data)] faces = [] ids = [] for image in path: img = Image.open(image).convert('L') imagenp = np.array(img,'uint8') id=int(os.path.split(image)[1].split('.')[1]) faces.append(imagenp) ids.append(id) cv2.imshow('Training',imagenp) cv2.waitKey(1)==13 ids=np.array(ids) #training classifier clf = cv2.face.LBPHFaceRecognizer_create() clf.train(faces,ids) clf.write("classifier1.xml") cv2.destroyAllWindows() messagebox.showinfo("Result","Training Successful",parent=self.root) if __name__ =="__main__": root=Tk() app = Train(root) root.mainloop()
import 'package:flutter/material.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:get/get.dart'; import 'package:nourishnet/donate/screens/donate_page.dart'; import 'package:nourishnet/features/community/screens/community_page.dart'; import 'package:nourishnet/features/donate/screens/donate_page.dart'; import 'package:nourishnet/features/donorhome/screens/home_page.dart'; import 'package:nourishnet/features/donorprofile/screens/profile_page.dart'; import 'package:nourishnet/features/maps/screens/location_page.dart'; import 'package:nourishnet/features/userhome/screens/home_page.dart'; import 'package:nourishnet/features/userprofile/screens/profile_page.dart'; import 'package:nourishnet/firebase_options.dart'; import 'package:nourishnet/repository/Authentication_Repository/authentication_repository.dart'; import 'package:nourishnet/repository/Donation_Repository/donation_repository.dart'; import 'package:nourishnet/widgets/splash_screen.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); try { await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform); Get.put<DonationRepository>(DonationRepository()); Get.put(AuthenticationRepository()); } catch (error) { print("Error initializing Firebase: $error"); } runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return GetMaterialApp( debugShowCheckedModeBanner: false, title: 'NourishNet', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Color.fromARGB(255, 0, 0, 0)), useMaterial3: true, ), initialRoute: '/', routes: { '/': (context) => SplashScreen(), '/homedonor': (context) => DonorHomePage(), '/homeuser': (context) => UserHomePage(), '/donate': (context) => DonatePage(), '/post': (context) => PostPage(), '/profiledonor': (context) => DonorProfilePage(), '/profileuser': (context) => UserProfilePage(), '/community': (context) => CommunityPage(), '/maps': (context)=> LocationPage(), }, ); } }
<script> import { mapActions, mapState, mapGetters } from 'vuex'; import { GlButton, GlLoadingIcon, GlIntersectionObserver, GlModal } from '@gitlab/ui'; import { n__, __, sprintf } from '~/locale'; import ProviderRepoTableRow from './provider_repo_table_row.vue'; export default { name: 'ImportProjectsTable', components: { ProviderRepoTableRow, GlLoadingIcon, GlButton, GlModal, GlIntersectionObserver, }, props: { providerTitle: { type: String, required: true, }, filterable: { type: Boolean, required: false, default: true, }, paginatable: { type: Boolean, required: false, default: false, }, }, computed: { ...mapState(['filter', 'repositories', 'namespaces', 'defaultTargetNamespace']), ...mapGetters([ 'isLoading', 'isImportingAnyRepo', 'hasImportableRepos', 'hasIncompatibleRepos', 'importAllCount', ]), pagePaginationStateKey() { return `${this.filter}-${this.repositories.length}`; }, availableNamespaces() { const serializedNamespaces = this.namespaces.map(({ fullPath }) => ({ id: fullPath, text: fullPath, })); return [ { text: __('Groups'), children: serializedNamespaces }, { text: __('Users'), children: [{ id: this.defaultTargetNamespace, text: this.defaultTargetNamespace }], }, ]; }, importAllButtonText() { return this.hasIncompatibleRepos ? n__( 'Import %d compatible repository', 'Import %d compatible repositories', this.importAllCount, ) : n__('Import %d repository', 'Import %d repositories', this.importAllCount); }, emptyStateText() { return sprintf(__('No %{providerTitle} repositories found'), { providerTitle: this.providerTitle, }); }, fromHeaderText() { return sprintf(__('From %{providerTitle}'), { providerTitle: this.providerTitle }); }, }, mounted() { this.fetchNamespaces(); this.fetchJobs(); if (!this.paginatable) { this.fetchRepos(); } }, beforeDestroy() { this.stopJobsPolling(); this.clearJobsEtagPoll(); }, methods: { ...mapActions([ 'fetchRepos', 'fetchJobs', 'fetchNamespaces', 'stopJobsPolling', 'clearJobsEtagPoll', 'setFilter', 'importAll', ]), }, }; </script> <template> <div> <p class="light text-nowrap mt-2"> {{ s__('ImportProjects|Select the repositories you want to import') }} </p> <template v-if="hasIncompatibleRepos"> <slot name="incompatible-repos-warning"></slot> </template> <div class="d-flex justify-content-between align-items-end flex-wrap mb-3"> <gl-button variant="success" :loading="isImportingAnyRepo" :disabled="!hasImportableRepos" type="button" @click="$refs.importAllModal.show()" >{{ importAllButtonText }}</gl-button > <gl-modal ref="importAllModal" modal-id="import-all-modal" :title="s__('ImportProjects|Import repositories')" :ok-title="__('Import')" @ok="importAll" > {{ n__( 'Are you sure you want to import %d repository?', 'Are you sure you want to import %d repositories?', importAllCount, ) }} </gl-modal> <slot name="actions"></slot> <form v-if="filterable" class="gl-ml-auto" novalidate @submit.prevent> <input data-qa-selector="githubish_import_filter_field" class="form-control" name="filter" :placeholder="__('Filter your repositories by name')" autofocus size="40" @keyup.enter="setFilter($event.target.value)" /> </form> </div> <div v-if="repositories.length" class="table-responsive"> <table class="table import-table"> <thead> <th class="import-jobs-from-col">{{ fromHeaderText }}</th> <th class="import-jobs-to-col">{{ __('To GitLab') }}</th> <th class="import-jobs-status-col">{{ __('Status') }}</th> <th class="import-jobs-cta-col"></th> </thead> <tbody> <template v-for="repo in repositories"> <provider-repo-table-row :key="repo.importSource.providerLink" :repo="repo" :available-namespaces="availableNamespaces" /> </template> </tbody> </table> </div> <gl-intersection-observer v-if="paginatable" :key="pagePaginationStateKey" @appear="fetchRepos" /> <gl-loading-icon v-if="isLoading" class="js-loading-button-icon import-projects-loading-icon" size="md" /> <div v-if="!isLoading && repositories.length === 0" class="text-center"> <strong>{{ emptyStateText }}</strong> </div> </div> </template>
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package co.elastic.apm.agent.opentelemetry; import co.elastic.apm.agent.testutils.TestClassWithDependencyRunner; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import java.util.List; public class OpenTelemetryVersionIT { @ParameterizedTest @ValueSource(strings = { "1.4.0", "1.4.1", "1.5.0", "1.6.0", "1.7.1", "1.9.0", "1.10.1", "1.11.0", "1.12.0", "1.13.0", "1.14.0", "1.15.0", "1.16.0", "1.17.0", "1.18.0", "1.19.0", "1.20.0", "1.21.0" }) void testTracingVersion(String version) throws Exception { List<String> dependencies = List.of( "io.opentelemetry:opentelemetry-api:" + version, "io.opentelemetry:opentelemetry-context:" + version, "io.opentelemetry:opentelemetry-semconv:" + version + "-alpha"); TestClassWithDependencyRunner runner = new TestClassWithDependencyRunner(dependencies, "co.elastic.apm.agent.opentelemetry.tracing.ElasticOpenTelemetryTest", "co.elastic.apm.agent.opentelemetry.tracing.AbstractOpenTelemetryTest", "co.elastic.apm.agent.opentelemetry.SemAttributes", "co.elastic.apm.agent.opentelemetry.tracing.ElasticOpenTelemetryTest$MapGetter"); runner.run(); } @ParameterizedTest @CsvSource(value = { "1.10.0|io.opentelemetry:opentelemetry-semconv:1.10.0-alpha", "1.14.0|io.opentelemetry:opentelemetry-semconv:1.14.0-alpha", "1.15.0|io.opentelemetry:opentelemetry-semconv:1.15.0-alpha", "1.21.0|io.opentelemetry:opentelemetry-semconv:1.21.0-alpha", "1.31.0|io.opentelemetry.semconv:opentelemetry-semconv:1.22.0-alpha", }, delimiterString = "|") void testAgentProvidedMetricsSdkForApiVersion(String version, String semConvDep) throws Exception { List<String> dependencies = List.of( "io.opentelemetry:opentelemetry-api:" + version, "io.opentelemetry:opentelemetry-context:" + version, semConvDep); TestClassWithDependencyRunner runner = new TestClassWithDependencyRunner(dependencies, "co.elastic.apm.agent.opentelemetry.metrics.AgentProvidedSdkOtelMetricsTest", "co.elastic.apm.agent.otelmetricsdk.AbstractOtelMetricsTest", "co.elastic.apm.agent.otelmetricsdk.AbstractOtelMetricsTest$1", "co.elastic.apm.agent.opentelemetry.OtelTestUtils"); runner.run(); } @ParameterizedTest @CsvSource(value = { "1.16.0|io.opentelemetry:opentelemetry-semconv:1.16.0-alpha", "1.21.0|io.opentelemetry:opentelemetry-semconv:1.21.0-alpha", "1.31.0|io.opentelemetry.semconv:opentelemetry-semconv:1.22.0-alpha", }, delimiterString = "|") void testUserProvidedMetricsSdkVersion(String version, String semConvDep) throws Exception { List<String> dependencies = List.of( "io.opentelemetry:opentelemetry-api:" + version, "io.opentelemetry:opentelemetry-sdk-metrics:" + version, "io.opentelemetry:opentelemetry-extension-incubator:" + version+"-alpha", "io.opentelemetry:opentelemetry-sdk-common:" + version, "io.opentelemetry:opentelemetry-context:" + version, semConvDep); TestClassWithDependencyRunner runner = new TestClassWithDependencyRunner(dependencies, "co.elastic.apm.agent.otelmetricsdk.PrivateUserSdkOtelMetricsTest", "co.elastic.apm.agent.otelmetricsdk.AbstractOtelMetricsTest", "co.elastic.apm.agent.otelmetricsdk.AbstractOtelMetricsTest$1", "co.elastic.apm.agent.otelmetricsdk.DummyMetricReader"); runner.run(); } @ParameterizedTest @CsvSource(value = { "1.10.0|1.10.0-alpha", "1.11.0|1.11.0-alpha", "1.12.0|1.12.0-alpha", "1.13.0|1.13.0-alpha", "1.14.0|1.14.0", "1.15.0|1.15.0", }, delimiterString = "|") void testUnsupportedMetricsSdkVersionsIgnored(String apiVersion, String sdkVersion) throws Exception { List<String> dependencies = List.of( "io.opentelemetry:opentelemetry-api:" + apiVersion, "io.opentelemetry:opentelemetry-sdk-metrics:" + sdkVersion, "io.opentelemetry:opentelemetry-sdk-common:" + apiVersion, "io.opentelemetry:opentelemetry-context:" + apiVersion, "io.opentelemetry:opentelemetry-semconv:" + apiVersion + "-alpha"); TestClassWithDependencyRunner runner = new TestClassWithDependencyRunner(dependencies, "co.elastic.apm.agent.otelmetricsdk.UnsupportedSdkVersionIgnoredTest", "co.elastic.apm.agent.otelmetricsdk.DummyMetricReader"); runner.run(); } @ParameterizedTest @ValueSource(strings = { "1.20.0", }) void testOpentelemetryAnnotationsVersion(String version) throws Exception { List<String> dependencies = List.of( "io.opentelemetry:opentelemetry-api:" + version, "io.opentelemetry:opentelemetry-context:" + version, "io.opentelemetry.instrumentation:opentelemetry-instrumentation-annotations:" + version); TestClassWithDependencyRunner runner = new TestClassWithDependencyRunner(dependencies, "co.elastic.apm.agent.opentelemetry.tracing.ElasticOpenTelemetryAnnotationsTest", "co.elastic.apm.agent.opentelemetry.tracing.AbstractOpenTelemetryTest"); runner.run(); } }
% % latexstring = mbSymbolic2Latex (string, sym, fontsize, output) % % This function provides functionality to generate latex output from % symbolic expressions. The output can either be a string or also be % plotted in a figure. % % Inputs: % pos Position of 'string' argument as prefix or suffix % string Additional latex strings for rendering % sym Sumbolic expression to be converted to latex % fontsize Font size of test visualization % outputmode Set the output to either create plot figure or to % return string data as raw or latex. % % Return: % latexstring String with either raw latex or fixed wth '$$ $$' % characters. % % Notes on Use: % % 1. If a symbolic variables is prefixed with a 'D' character, it % will be interpreted as an absolute derivative w.r.t. time and will % be rendered with a '\dot' accent. Example: % % syms Dx_f -> \dot{x}_{f} % % 2. Greek lower case and higher case are handled automatically as % long as the latinized spelling is correct. % % 3. Support for automatically recognizing multi-character subscripts % exists. Example: % % Dx_foobar -> \dot{x}_{foobar} % % % % Authors: Martin Waser (ezsym original author) % Vassilios Tsounis, [email protected] (fixes, extensions) % % Date: June 2016 % % Copyrigth(C) 2016, Vassilios Tsounis % function latexstring = mbSymbolic2Latex(pos, string, sym, fontsize, outputmode) % Check if sum argument is a symbolic expression if ~isa(sym,'sym') error('Input must be a symbolic expression'); end % Check font size if isempty(fontsize) fontsize = 18; end % Table of greek symbols greeks = { 'alpha', 'beta', 'gamma', 'Gamma', 'delta', ... 'Delta', 'epsilon', 'Zeta', 'zeta', 'theta', 'Theta', ... 'eta', 'iota', 'kappa', 'lambda', 'Lambda', ... 'mu', 'nu', 'xi', 'Xi', 'pi', ... 'Pi', 'rho', 'sigma', 'Sigma', 'tau', ... 'upsilon', 'Upsilon', 'phi', 'Phi', 'chi' ... 'psi', 'Psi', 'omega', 'Omega'}; % Parsing corrections parsing_corrections = {'{\b{\eta}}', '{\th{\eta}}', '{\Th{\eta}}', '{\u{\psilon}}', '{\U{\psilon}}', '{\Z{\eta}}', '{\z{\eta}}', '{\e{\psilon}}' ; '{\beta}', '{\theta}', '{\Theta}', '{\upsilon}', '{\Upsilon}', '{Z}' , '{\zeta}' , '{\epsilon}'}; % Latin symbols small_latins = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; large_latins = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; charlist = {small_latins{1,:},large_latins{1,:}}; % Arabic numerals numbers = {'0','1','2','3','4','5','6','7','8','9'}; % Variable name and expression delimiters delims = {'(',')','{','}','\',',',' ','_','^','/','*','.'}; % Get the raw conversion to latex latexexprin = latex(sym); % Modify for multi-character subscripts symvars = symvar(sym); for i = 1:numel(symvars) symrawstring{i} = char(symvars(i)); foundsubscript = false; % Find start of subscript for j = 1:numel(symrawstring{i}) if symrawstring{i}(j) == '_'; subscriptstart = j+1; foundsubscript = true; break; end end if foundsubscript == true symstringparts{i,1} = symrawstring{i}(1:subscriptstart-2); symstringparts{i,2} = symrawstring{i}(subscriptstart); symstringparts{i,3} = symrawstring{i}(subscriptstart+1:end); if numel(symstringparts{i,1}) > 1 if numel(symstringparts{i,3}) > 1 searchterm = strcat('\mathrm{',symstringparts{i,1},'}_{',symstringparts{i,2},'}\mathrm{',symstringparts{i,3},'}'); elseif numel(symstringparts{i,3}) == 1 searchterm = strcat('\mathrm{',symstringparts{i,1},'}_{',symstringparts{i,2},'}',symstringparts{i,3}); elseif numel(symstringparts{i,3}) == 0 searchterm = strcat('\mathrm{',symstringparts{i,1},'}_{',symstringparts{i,2},'}'); end replaceterm = strcat('\mathrm{',symstringparts{i,1},'}_{',symstringparts{i,2},symstringparts{i,3},'}'); elseif numel(symstringparts{i,1}) == 1 if numel(symstringparts{i,3}) > 1 searchterm = strcat(symstringparts{i,1},'_{',symstringparts{i,2},'}\mathrm{',symstringparts{i,3},'}'); elseif numel(symstringparts{i,3}) == 1 searchterm = strcat(symstringparts{i,1},'_{',symstringparts{i,2},'}',symstringparts{i,3}); elseif numel(symstringparts{i,3}) == 0 searchterm = strcat(symstringparts{i,1},'_{',symstringparts{i,2},'}'); end replaceterm = strcat(symstringparts{i,1},'_{',symstringparts{i,2},symstringparts{i,3},'}'); end latexexprin = strrep(latexexprin, searchterm, replaceterm); end end % Replace special subscripts latexexprin = strrep(latexexprin, '_{tm1}', '_{t-1}'); latexexprin = strrep(latexexprin, '_{tp1}', '_{t+1}'); % Replace "hat_" prefix with "\hat{}" % TODO % Replace diff() time derivatives with D operator % TODO % Modify to substitute the "D" prefix with an time derivative "dot" symvars = symvar(sym); for i = 1:numel(symvars) symrawstring{i} = char(symvars(i)); found_diff = false; found_double_diff = false; strlength = numel(symrawstring{i}); if strlength >= 5 if (strcmp(symrawstring{i}(1:5), 'Delta')) isdelta = true; else isdelta = false; end else isdelta = false; end % Find starting diff operator 'D' if (numel(symrawstring{i}) > 1) && (~isdelta) if (strcmp(symrawstring{i}(1),'D')) && (~strcmp(symrawstring{i}(1:2),'DD')) && (~strcmp(symrawstring{i}(1:3),'DDD')) for j = 2:numel(symrawstring{i}) for k = 1:numel(delims) if ((symrawstring{i}(j) == delims{k}) || (j == numel(symrawstring{i}))) && (j >= 2) if numel(symrawstring{i}) == 2 symvarname{i} = symrawstring{i}(2); else if symrawstring{i}(j) == delims{k} symvarname{i} = symrawstring{i}(2:j-1); elseif j == numel(symrawstring{i}) symvarname{i} = symrawstring{i}(2:j); end end found_diff = true; break; end end if found_diff == true break; end end elseif (strcmp(symrawstring{i}(1:2),'DD')) && (~strcmp(symrawstring{i}(1:3),'DDD')) for j = 3:numel(symrawstring{i}) for k = 1:numel(delims) if ((symrawstring{i}(j) == delims{k}) || (j == numel(symrawstring{i}))) && (j >= 3) if numel(symrawstring{i}) == 3 symvarname{i} = symrawstring{i}(3); else if symrawstring{i}(j) == delims{k} symvarname{i} = symrawstring{i}(3:j-1); elseif j == numel(symrawstring{i}) symvarname{i} = symrawstring{i}(3:j); end end found_double_diff = true; break; end end if found_double_diff == true break; end end end end if found_diff == true if numel(symrawstring{i}) == 2 searchterm = strcat('D',symvarname{i}); else searchterm = strcat('\mathrm{D',symvarname{i},'}'); end replaceterm = strcat('\dot{',symvarname{i},'}'); latexexprin = strrep(latexexprin, searchterm, replaceterm); elseif found_double_diff == true if numel(symrawstring{i}) == 3 searchterm = strcat('DD',symvarname{i}); else searchterm = strcat('\mathrm{DD',symvarname{i},'}'); end replaceterm = strcat('\ddot{',symvarname{i},'}'); latexexprin = strrep(latexexprin, searchterm, replaceterm); end end for k=1:numel(greeks) latexexprin = strrep(latexexprin, greeks{k}, ['{\',greeks{k},'}']); %latexexprin = strrep(latexexprin, greeks{k}, ['\',greeks{k}]); end for k=1:numel(parsing_corrections)/2 latexexprin = strrep(latexexprin, parsing_corrections{1,k}, parsing_corrections{2,k}); end for k=1:numel(greeks) latexexprin = strrep(latexexprin, ['\\',greeks{k}], ['{\',greeks{k},'}']); end % Check font size if ~isempty(string) % Default to prefix for string argument if isempty(pos) pos = 'prefix'; end switch pos case 'prefix' latexexprin = strcat(string,latexexprin); case 'suffix' latexexprin = strcat(latexexprin,string); otherwise error('error: mbSymbolic2Latex: incorrect type specified for "pos" argument.'); end end % Add the inline-latex markers\ if ~isempty(outputmode) && (strcmp(outputmode,'latex') || strcmp(outputmode,'plot')) latexexprin = ['$$ ',latexexprin,' $$']; latexstring = latexexprin; elseif ~isempty(outputmode) && strcmp(outputmode,'raw') latexstring = latexexprin; else error('error: mbSymbolic2Latex: incorrect output mode specified.'); end if ~isempty(outputmode) && strcmp(outputmode,'plot') % Write output to a text-only test-figure %figure('Color','white','Menu','none','units','normalized','outerposition',[0 0 1 1]); figure('Color','white','units','normalized','outerposition',[0 0 1 1]); text(0.5, 0.5, latexstring, 'FontSize',fontsize, 'Color','k','HorizontalAlignment','Center', ... 'VerticalAlignment','Middle', 'Interpreter','latex'); axis off; end end
<div class="container"> <div class="container-table"> <h1 class="title">Subject Situation</h1> <p class="subject-name" *ngIf="subject !== undefined">{{subject.name + ' ' + subject.studyGroup.number + subject.studyGroup.name}}</p> <div class="situation-navbar"> <div [ngClass]="{ 'current-tab': mode === 'grades' }" (click)="mode = 'grades'" class="situation-navbar-element">Grades</div> <div [ngClass]="mode === 'nonAttendances' ? 'current-tab' : ''"(click)="mode = 'nonAttendances'" class="situation-navbar-element">Non Attendances</div> </div> <table *ngIf="mode == 'grades'" mat-table [dataSource]="situation!" class="table mat-elevation-z8"> <ng-container matColumnDef="name"> <th mat-header-cell *matHeaderCellDef>Student <div> <mat-form-field> <input matInput class="form-field" [formControl]="nameFilter" [placeholder]="filterNameMessage"> </mat-form-field> </div> </th> <td mat-cell *matCellDef="let element">{{element.user.firstName + ' ' + element.user.lastName}}</td> </ng-container> <ng-container matColumnDef="pin"> <th mat-header-cell *matHeaderCellDef>PIN <div> <mat-form-field> <input matInput class="form-field" [formControl]="pinFilter" [placeholder]="filterPinMessage"> </mat-form-field> </div> </th> <td mat-cell *matCellDef="let element">{{element.user.pin}}</td> </ng-container> <ng-container matColumnDef="grades"> <th mat-header-cell *matHeaderCellDef>Grades</th> <td mat-cell *matCellDef="let element; let i=index"> <div class="row-container"> <div (click)="openEditGrade(grade, i)" [ngClass]="{ 'grade': isTeachingSubject() }" *ngFor="let grade of element.grades"> {{grade.grade}} </div> </div> </td> </ng-container> <ng-container matColumnDef="averageScore"> <th mat-header-cell *matHeaderCellDef>Average Score</th> <td mat-cell *matCellDef="let element"> <div class="average-container"> <div [ngClass]="{ 'not-passing': element.averageScore < 5 }" class="averageScore" *ngIf="element.averageScore !== null"> {{element.averageScore}} </div> </div> </td> </ng-container> <ng-container *ngIf="isTeachingSubject()" matColumnDef="add"> <th mat-header-cell *matHeaderCellDef>Add</th> <td mat-cell *matCellDef="let element"> <button mat-icon-button class="default-btn" (click)="openAddGrade(element.user)" title="Add"> <mat-icon aria-hidden="false" aria-label="Add">note_add</mat-icon> </button> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedGradeColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedGradeColumns;"></tr> </table> <table *ngIf="mode === 'nonAttendances'" mat-table [dataSource]="situation!" class="table mat-elevation-z8"> <ng-container matColumnDef="name"> <th mat-header-cell *matHeaderCellDef>Student <div> <mat-form-field> <input matInput class="form-field" [formControl]="nameFilter" [placeholder]="filterNameMessage"> </mat-form-field> </div> </th> <td mat-cell *matCellDef="let element">{{element.user.firstName + ' ' + element.user.lastName}}</td> </ng-container> <ng-container matColumnDef="pin"> <th mat-header-cell *matHeaderCellDef>PIN <div> <mat-form-field> <input matInput class="form-field" [formControl]="pinFilter" [placeholder]="filterPinMessage"> </mat-form-field> </div> </th> <td mat-cell *matCellDef="let element">{{element.user.pin}}</td> </ng-container> <ng-container matColumnDef="nonAttendances"> <th mat-header-cell *matHeaderCellDef>Non Attendances</th> <td mat-cell *matCellDef="let element"> <div class="row-container"> <div [ngClass]="{ 'motivated': nonAttendance.motivated, 'non-attendance': hasMotivateNonAttendanceAccess() }" *ngFor="let nonAttendance of element.nonAttendances" (click)="openMotivateNonAttendanceModal(nonAttendance)"> {{convertTimestampToLocaleDate(nonAttendance.date)}} </div> </div> </td> </ng-container> <ng-container *ngIf="isTeachingSubject()" matColumnDef="add"> <th mat-header-cell *matHeaderCellDef>Add</th> <td mat-cell *matCellDef="let element"> <button mat-icon-button class="default-btn" (click)="openNonAttendanceModal(element.user)" title="Add"> <mat-icon aria-hidden="false" aria-label="Add">note_add</mat-icon> </button> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedNonAttendanceColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedNonAttendanceColumns;"></tr> </table> <div *ngIf="mode === 'grades'" class="result"> Total average score: {{totalAverageScore}} </div> <div *ngIf="mode === 'nonAttendances'" class="result"> <div>Total non-attendances: {{totalNonAttendances}}</div> <div>Total unmotivated non-attendanes: {{totalUnmotivatedNonAttendances}}</div> </div> </div> </div> <div class="pre-modal" *ngIf="showModal"> <div *ngIf="showModal" class="modal"> <h1 class="title">{{modalMode}} grade</h1> <form *ngIf="mode === 'grades'" id="grade-form" [formGroup]="gradeForm"> <div class="input-field"> <label class="label-field" for="grade">Grade</label> <input class="input" formControlName="grade" id="grade" type="number" placeholder="Grade"> <div *ngIf="gradeForm.get('grade')!.invalid && gradeForm.get('grade')!.errors && (gradeForm.get('grade')!.dirty || gradeForm.get('grade')!.touched)"> <small class="text-danger" *ngIf="gradeForm.get('grade')!.hasError('required')"> {{requiredMessage}} </small> <small class="text-danger" *ngIf="gradeForm.get('grade')!.hasError('min') || gradeForm.get('grade')!.hasError('max')"> {{invalidGradeMessage}} </small> </div> </div> </form> <div class="buttons"> <button style="width: 28%;" class="cancel-btn" type="button" (click)="cancelModal()"> Cancel </button> <button *ngIf="modalMode==='Edit'" style="width: 28%;" class="remove-btn" type="button" (click)="cancelModal(); openDeleteModal()"> Delete </button> <button style="width: 28%;" class="submit-btn" type="button" (click)="submit()" [disabled]="!gradeForm.valid"> Submit </button> </div> </div> </div> <div class="pre-modal" *ngIf="showDeleteModal"> <div *ngIf="showDeleteModal" class="modal"> <h1 class="title">Delete confirmation</h1> <p class="subtitle">Are you sure you want to delete this item?</p> <div class="buttons"> <button class="cancel-btn" type="button" (click)="cancelDeleteModal()"> No </button> <button class="submit-btn" type="button" (click)="deleteGrade()"> Yes </button> </div> </div> </div> <div class="pre-modal" *ngIf="showNonAttendanceModal"> <div *ngIf="showNonAttendanceModal" class="modal"> <h1 class="title">Nonattendance confirmation</h1> <p class="subtitle">Are you sure you want to add the nonattendance?<br></p> <div class="buttons"> <button class="cancel-btn" type="button" (click)="cancelNonAttendanceModal()"> No </button> <button class="submit-btn" type="button" (click)="addNonAttendance()"> Yes </button> </div> </div> </div> <div class="pre-modal" *ngIf="showMotivateNonAttendanceModal"> <div *ngIf="showMotivateNonAttendanceModal" class="modal"> <h1 class="title">Nonattendance confirmation</h1> <p class="subtitle">Are you sure you want to change the nonattendance status?<br></p> <div class="buttons"> <button class="cancel-btn" type="button" (click)="cancelMotivateNonAttendanceModal()"> No </button> <button class="submit-btn" type="button" (click)="updateNonAttendanceMotivatedStatus()"> Yes </button> </div> </div> </div>
package lms.user.management.exception; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(LMSResourceNotFoundException.class) public ResponseEntity<ErrorResponse> handleResourceNotFoundException(LMSResourceNotFoundException ex, WebRequest request) { ErrorResponse errorResponse = new ErrorResponse( HttpStatus.NOT_FOUND.value(), ex.getMessage(), System.currentTimeMillis() ); return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND); } @ExceptionHandler(LMSBadRequestException.class) public ResponseEntity<ErrorResponse> handleResourceNotFoundException(LMSBadRequestException ex, WebRequest request) { ErrorResponse errorResponse = new ErrorResponse( HttpStatus.BAD_REQUEST.value(), ex.getMessage(), System.currentTimeMillis() ); return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST); } @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<ErrorResponse> handleValidationErrors(MethodArgumentNotValidException ex) { List<String> errors = ex.getBindingResult().getFieldErrors() .stream().map(FieldError::getDefaultMessage).collect(Collectors.toList()); ErrorResponse errorResponse = new ErrorResponse( HttpStatus.BAD_REQUEST.value(), String.join(",", errors), System.currentTimeMillis() ); return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST); } }
## Luckysheet > `Luckysheet` 是一款纯前端类似excel的在线表格,功能强大、配置简单、完全开源。 > > > github:https://github.com/dream-num/Luckysheet > > > 官方文档地址:https://dream-num.github.io/LuckysheetDocs/zh/ > > 目前 `Luckysheet` 已经有了 `15.3K` 的 `star` 可以说是一个前端的明星项目。 ##### 特性 > ### **01:支持 格式设置** > > - **样式** (修改字体样式,字号,颜色或者其他通用的样式) > > - **条件格式** (突出显示所关注的单元格或单元格区域;强调异常值;使用数据栏、色阶和图标集(与数据中的特定变体对应)直观地显示数据) > > - **文本对齐及旋转** > > - **支持文本的截断、溢出、自动换行** > > - **数据类型** > > - - **货币, 百分比, 数字, 日期** > - **Custom** (和excel保持一致,例如:`##,###0.00` , `$1,234.56$##,###0.00_);[Red]($##,###0.00)`, `_($* ##,###0.00_);_(...($* "-"_);_(@_)`, `08-05 PM 01:30MM-dd AM/PM hh:mm` ) > > - **单元格内多样式** (Alt+Enter单元格内换行、上标、下标、单元格内可定义每个文字的不同样式) > > ### **02:支持 单元格配置** > > - **拖拽选取来修改单元格** (对选区进行操作,可以拖动四边来移动选区,也可以在右下角对选区进行下拉填充操作) > - **选区下拉填充** (对于一个1,2,3,4,5的序列,将会按照间隔为1进行下拉填充,而对2,4,6,8将会以2作为间隔。支持等差数列,等比数列,日期,周,天,月,年,中文数字填充) > - **自动填充选项** (下拉填充后,会出现填充选项的菜单,支持选择复制,序列,仅格式,只填充格式,天,月,年的选择) > - **多选区操作** (可以按住Ctrl键进行单元格多选操作,支持多选区的复制粘贴) > - **查找和替换** (对内容进行查找替换,支持正则表达式,整词,大小写敏感) > - **定位** (可以根据单元格的数据类型进行自动定位并选中,选中后可以批量进行格式等操作) > - **合并单元格** > - **数据验证(表单功能)** (支持Checkbox, drop-down list, datePicker) > > ### **03:支持 行和列自定义操作** > > - **隐藏,插入,删除行或列** > - **冻结行或列** (支持冻结首行和首列,冻结到选区,冻结调节杆可以进行拖动操作) > - **文本分列** (可以把文本根据不同符号进行拆分,和excel的分列功能类似) > > ### **04:支持 快捷操作** > > - **撤销/重做** > - **复制/粘贴/剪切操作** (支持Luckysheet到excel和excel到Luckysheet带格式的互相拷贝) > - **快捷键支持** (快捷键操作保持与excel一致,如果有不同或者缺失请反馈给我们) > - **格式刷** (与google sheet类似) > - **任意选区拖拽** (选择单元格,输入公式,插入图表,会与选区相关,可以通过任意拖动和放大缩小选区来改变与之关联的参数) > > ### **05:支持 嵌入公式和函数** > > - **内置公式** > > - - 数学 (SUMIFS, AVERAGEIFS, SUMIF, SUM, etc.) > - 文本 (CONCATENATE, REGEXMATCH, MID) > - 日期 (DATEVALUE, DATEDIF, NOW, WEEKDAY, etc.) > - 财务 (PV, FV, IRR, NPV, etc.) > - 逻辑 (IF, AND, OR, IFERROR, etc.) > - 查找和引用 (VLOOKUP, HLOOkUP, INDIRECT, OFFSET, etc.) > - 动态数组 (Excel2019新函数,SORT,FILTER,UNIQUE,RANDARRAY,SEQUENCE) > > - **公式支持数组** (={1,2,3,4,5,6}, Crtl+Shift+Enter) > > - **远程公式** (DM_TEXT_TFIDF, DM_TEXT_TEXTRANK,DATA_CN_STOCK_CLOSE etc. Need remote interface, can realize complex calculation) > > - **自定义公式** (根据身份证识别年龄,性别,生日,省份,城市等. AGE_BY_IDCARD, SEX_BY_IDCARD, BIRTHDAY_BY_IDCARD, PROVINCE_BY_IDCARD, CITY_BY_IDCARD, etc. 可以任意加入自己的公式哦) > > ### **06:支持 表格操作** > > - **筛选** (支持颜色、数字、字符、日期的筛选) > - **排序** (同时加入多个字段进行排序) > > ### **07:支持 数据透视表** > > - **字段拖拽** (操作方式与excel类似,拖动字段到行、列、数值、筛选等4个区域) > - **聚合方式** (支持汇总、计数、去重计数、平均、最大、最小、中位数、协方差、标准差、方差等计算) > - **筛选数据** (可对字段进行筛选后再进行汇总) > - **数据透视表下钻** (双击数据透视表中的数据,可以下钻查看到明细,操作方式与excel一致) > - **根据数据透视表新建图表** (数据透视表产生的数据也可以进行图表的制作) > > ### **08:支持 图表** > > - **支持的图表类型** (目前折线图、柱状图、面积图、条形图、饼图可以使用,散点图、雷达图、仪表盘、漏斗图正在接入,其他图表正在陆续开发中,请大家给予建议) > - **关于图表插件** (图表使用了一个中间插件ChartMix (opens new window)(MIT协议): 目前支持ECharts,正在逐步接入Highcharts、阿里G2、amCharts、googleChart、chart.js) > - **Sparklines小图** (以公式的形式进行设置和展示,目前支持:折线图、面积图、柱状图、累积图、条形图、离散图、三态图、饼图、箱线图等) > > ### **09:支持 协作和评论** > > - **评论** (评论的删除、添加、修改、隐藏) > - **共享编辑** (支持多用户共享编辑,内置API) > > ### **10:支持 插入静态资源** > > - **插入图片** (支持JPG,PNG,SVG的插入、修改和删除,并且随表格的变动而产生变化) > > ### **11:其他特殊操作** > > - **矩阵计算** (通过右键菜单进行支持:对选区内的数据进行转置、旋转、数值计算) > - **截图** (把选区的内容进行截图展示) > - **复制到其他格式** (右键菜单的"复制为", 支持复制为json、array、对角线数据、去重等) > - **EXCEL导入及导出** (专为Luckysheet打造的导入导出插件,支持密码、水印、公式等的本地导入导出,导出正在开发) ##### 使用方式
#include <iostream> #include <vector> #include <algorithm> bool login_admin = false; bool login_user = false; using namespace std; class product { public: int product_Id; string name; double price; int quantity; void setProduct(string name, int product_id, double price) { this->name = name; this->product_Id = product_id; this->price = price; } void setQuantity(int q) { this->quantity = q; } }; class ProductList { public: vector<product *> Products; void addProductToList(product *pr) { Products.push_back(pr); } void removeProductFromList(int pID) { for (auto i : Products) { if (i->product_Id == pID) { auto it = find(Products.begin(), Products.end(), i); Products.erase(it); delete i; return; } } cout << "Your Product is not in the list" << endl; } void showList() { for (auto pr : Products) { cout << "Name : " << pr->name << endl; cout << "ID : " << pr->product_Id << endl; cout << "Price : " << pr->price << endl; cout << "---------------------------------------------------\n"; } } product *getProduct(int id) { for (auto i : Products) { if (i->product_Id == id) { return i; } } return nullptr; } }; class ShoppingCart { vector<product *> cartProducts; public: void addProduct(product *pr) { product *cartProduct = new product; // Create a new product for the cart cartProduct->setProduct(pr->name, pr->product_Id, pr->price); // Copy details from the list product cartProduct->setQuantity(pr->quantity); // Set the quantity cartProducts.push_back(cartProduct); } void removeProduct(int pID) { for (auto i : cartProducts) { if (i->product_Id == pID) { auto it = find(cartProducts.begin(), cartProducts.end(), i); cartProducts.erase(it); delete i; return; } } cout << "Product is not in your cart" << endl; } void calculateTotalPrice() { this->displayCart(); double totalPrice = 0.0; for (auto pr : cartProducts) { double price = pr->price * static_cast<double>(pr->quantity); totalPrice += price; } cout << "Total Bill: " << totalPrice << "\n-------------------------------------\n"; } void displayCart() { for (auto pr : cartProducts) { cout << "Name : " << pr->name << endl; cout << "ID : " << pr->product_Id << endl; cout << "Price : " << pr->price << endl; cout << "Quantity : " << pr->quantity << endl; cout << "---------------------------------------------------\n"; } } }; void admin(ProductList &list) { system("cls"); int n; cout << "1. Add to list\n2. Delete from list\n3. Show list\nChoice: "; int choice; cin >> choice; switch (choice) { case 1: cout << "How many products you want to add?: "; cin >> n; for (int i = 0; i < n; i++) { product *pr = new product; string name; double price; int Id; cout << "Name: "; cin >> name; cout << "Price: "; cin >> price; cout << "ID: "; cin >> Id; cout << "---------------------------------------------\n"; pr->setProduct(name, Id, price); list.addProductToList(pr); } break; case 2: cout << "How many products you want to delete?: "; cin >> n; list.showList(); for (int i = 0; i < n; i++) { int Id; cout << "ID: "; cin >> Id; list.removeProductFromList(Id); } break; case 3: list.showList(); break; default: cout << "Invalid choice..." << endl; break; } } void user(ProductList &list, ShoppingCart &cart) { system("cls"); int n; cout << "1. Add to Cart\n2. Delete from cart\n3. Show cart\n4. Total bill\nChoice: "; int choice; cin >> choice; switch (choice) { case 1: list.showList(); cout << "How many products you want to add?: "; cin >> n; for (int i = 0; i < n; i++) { int Id; int q; cout << "ID: "; cin >> Id; cout << "Quantity: "; cin >> q; cout << "---------------------------------------------\n"; product *pr = list.getProduct(Id); if (pr != nullptr) { pr->setQuantity(q); cart.addProduct(pr); } else { cout << "Product not found in the list." << endl; } } break; case 2: cout << "How many products you want to delete?: "; cin >> n; cart.displayCart(); for (int i = 0; i < n; i++) { int Id; cout << "ID: "; cin >> Id; cart.removeProduct(Id); } break; case 3: cart.displayCart(); break; case 4: cart.calculateTotalPrice(); break; default: cout << "Invalid choice..." << endl; break; } } int main() { ProductList list; ShoppingCart cart; bool login = false; int q = 2; do { switch (q) { case 1: system("cls"); if (login_admin) admin(list); else user(list, cart); break; case 2: system("cls"); while (!login) { cout << "Login as \n1. Shopkeeper\n2. User\nChoice: "; int choice; cin >> choice; switch (choice) { case 1: admin(list); login_admin = true; login_user = false; login = true; break; case 2: user(list, cart); login_user = true; login_admin = false; login = true; break; default: break; } } login = false; break; case 3: return 0; default: cout << "Invalid choice...\n"; break; } cout << "1.Want to continue...\n2.Go to login page\n3.exit\nChoice: "; cin >> q; } while (q != 3); }
from django.shortcuts import render, redirect, HttpResponse from .models import Galaxy, System, Planet from .forms import AddGalaxy, AddSystem, AddPlanet # Create your views here. def index(request): ctx = { 'planets': Planet.objects.all(), 'systems': System.objects.all(), 'galaxies': Galaxy.objects.all() } return render(request, 'forms/index.html', ctx) def planet(request, id): planet = Planet.objects.get(pk=id) if request.POST: form = AddPlanet(request.POST) if form.is_valid(): planet.radius = form.cleaned_data['radius'] planet.name = form.cleaned_data['name'] planet.system = form.cleaned_data['system'] planet.save(update_fields=['radius', 'name', 'system']) else: return HttpResponse('Форма введена с ошибкой') form = AddPlanet() ctx = { 'planet': planet, 'form': form } return render(request, 'forms/planet.html', ctx) def system(request, id): system = System.objects.get(pk=id) if request.POST: form = AddSystem(request.POST) if form.is_valid(): system.name = form.cleaned_data['name'] system.galaxy = form.cleaned_data['galaxy'] system.proximity_to_center = form.cleaned_data['proximity_to_center'] system.save(update_fields=['name', 'galaxy', 'proximity_to_center']) else: return HttpResponse('Форма введена с ошибкой') form = AddSystem() ctx = { 'system': system, 'form': form } return render(request, 'forms/system.html', ctx) def add_galaxy(request): if request.POST: form = AddGalaxy(request.POST) if form.is_valid(): form.save() return redirect('home') else: return HttpResponse('Форма введена с ошибкой') else: form = AddGalaxy() ctx = { 'form': form } return render(request, 'forms/add_galaxy.html', ctx) def add_system(request): if request.POST: form = AddSystem(request.POST) if form.is_valid(): form.save() return redirect('home') else: return HttpResponse('Форма введена с ошибкой') else: form = AddSystem() ctx = { 'form': form } return render(request, 'forms/add_system.html', ctx) def add_planet(request): if request.POST: form = AddPlanet(request.POST) if form.is_valid(): form.save() return redirect('home') else: return HttpResponse('Форма введена с ошибкой') else: form = AddPlanet() ctx = { 'form': form } return render(request, 'forms/add_planet.html', ctx)
import { ToastrService } from 'ngx-toastr'; import { Component, OnInit } from '@angular/core'; import { EcommDataService } from '../ecomm-data.service'; import { Product } from '../product'; import { CartService } from '../cart.service'; import { WishlistService } from '../wishlist.service'; @Component({ selector: 'app-products', templateUrl: './products.component.html', styleUrls: ['./products.component.scss'] }) export class ProductsComponent implements OnInit { inputValue:string ='' allProducts:Product[]= [] pageSize:number =0; currentPage:number=0; total:number=0 wishListData:string[]=[] constructor(private _EcommDataService:EcommDataService,private _CartService:CartService,private _ToastrService:ToastrService,private _WishlistService:WishlistService){} ngOnInit(): void { this._EcommDataService.getAllProducts().subscribe( { next:data=>{ this.allProducts = data.data this.pageSize= data.metadata.limit; this.currentPage=data.metadata.currentPage; this.total=data.results }, error:err=>{ } } ) this._WishlistService.getUserWishList().subscribe({ next:data=>{ const newData = data.data.map((item:any)=>item.id) this.wishListData = newData } }) } addProduct(id:any,elem:HTMLButtonElement){ this._CartService.addToCart(id).subscribe({ next:data=>{ this._ToastrService.success(data.message) this._CartService.cartNumber.next(data.numOfCartItems) }, error:err=>{ console.log(err); } }) } pageChanged(event:any){ this._EcommDataService.getAllProducts(event).subscribe({ next:data=>{ this.allProducts = data.data; this.pageSize = data.metadata.limit; this.currentPage = data.metadata.currentPage; this.total = data.results; }, error:err=>{ console.log(err); } }) } addToWish(id:string){ this._WishlistService.addToWishList(id).subscribe({ next:data=>{ this._ToastrService.success(data.message) this.wishListData= data.data; // console.log(this.wishListData); this._WishlistService.listNum.next(this.wishListData.length) }, error:err=>{ console.log(err); } }) } removeFromWish(id:string){ this._WishlistService.removeProduct(id).subscribe({ next:data=>{ this._ToastrService.success(data.message) this.wishListData= data.data; // console.log(this.wishListData); this._WishlistService.listNum.next(this.wishListData.length) }, error:err=>{ console.log(err); } }) } }
import LeaderboardResponse from '../dtos/LeaderboardReponse'; import LeaderboardAwayService from './LeaderboardAwayService'; import LeaderboardHomeService from './LeaderboardHomeService'; class LeaderboardService { private _homeService = new LeaderboardHomeService(); private _awayService = new LeaderboardAwayService(); private static switchFunc(a: LeaderboardResponse, b: LeaderboardResponse, levels: boolean[]) { switch (true) { case levels[3]: return b.goalsOwn - a.goalsOwn; case levels[2]: return b.goalsFavor - a.goalsFavor; case levels[1]: return b.goalsBalance - a.goalsBalance; case levels[0]: return b.totalVictories - a.totalVictories; default: return b.totalPoints - a.totalPoints; } } private static sortFunction(a: LeaderboardResponse, b: LeaderboardResponse) { const levelFour = ( a.totalPoints === b.totalPoints && a.totalVictories === b.totalVictories && a.goalsBalance === b.goalsBalance && a.goalsFavor === b.goalsFavor ); const levelThree = ( a.totalPoints === b.totalPoints && a.totalVictories === b.totalVictories && a.goalsBalance === b.goalsBalance ); const levelTwo = (a.totalPoints === b.totalPoints && a.totalVictories === b.totalVictories); const levelOne = a.totalPoints === b.totalPoints; const levels = [levelOne, levelTwo, levelThree, levelFour]; return LeaderboardService.switchFunc(a, b, levels); } private static sumLists(homeData: LeaderboardResponse[], awayData: LeaderboardResponse[]) { const results: LeaderboardResponse[] = []; homeData.map((club) => club.name).forEach((name) => { const result = new LeaderboardResponse(); const home = homeData.filter((club) => club.name === name)[0]; const away = awayData.filter((club) => club.name === name)[0]; result.name = home.name; result.totalPoints = home.totalPoints + away.totalPoints; result.totalGames = home.totalGames + away.totalGames; result.totalVictories = home.totalVictories + away.totalVictories; result.totalLosses = home.totalLosses + away.totalLosses; result.totalDraws = home.totalDraws + away.totalDraws; result.goalsFavor = home.goalsFavor + away.goalsFavor; result.goalsOwn = home.goalsOwn + away.goalsOwn; result.goalsBalance = result.goalsFavor - result.goalsOwn; result.efficiency = +(((result.totalPoints) / (result.totalGames * 3)) * 100).toFixed(2); results.push(result); }); return results; } public async List() { const homeData = await this._homeService.List(); const awayData = await this._awayService.List(); const results = LeaderboardService.sumLists(homeData, awayData); return results.sort((a, b) => LeaderboardService.sortFunction(a, b)); } } export default LeaderboardService;
import { Component, OnChanges, OnInit, SimpleChanges } from '@angular/core'; import { Router } from '@angular/router'; import { LoginService } from '../services/login.service'; import { CartService } from '../services/cart.service'; @Component({ selector: 'app-main-nav', templateUrl: './main-nav.component.html', styleUrls: ['./main-nav.component.scss'] }) export class MainNavComponent implements OnInit, OnChanges { loggedInUser: any; user: any cartItemCount: number; constructor(private router: Router, private loginService: LoginService, private cartService: CartService) { } ngOnInit(): void { const cartItems = localStorage.getItem('cartCount'); if (cartItems) { this.cartItemCount = JSON.parse(cartItems); } this.user = this.loginService.getLoggedInUser(); if (this.user) { this.loggedInUser = true; } this.loginService.userLoggedIn.subscribe(user => { this.loggedInUser = true; this.user = this.loginService.getLoggedInUser(); }); this.cartService.countChanged.subscribe({ next: (response: any) => { this.cartItemCount = response; } }) } ngOnChanges(): void { this.user = this.loginService.getLoggedInUser(); if (this.user) { this.loggedInUser = true; } this.loginService.userLoggedIn.subscribe(user => { this.loggedInUser = true; this.user = this.loginService.getLoggedInUser(); }); } navigateToLoginPage() { if (this.loggedInUser) { this.router.navigate(['/shop']); } else { this.router.navigate(['/login']); } } logout(): void { this.loginService.logout(); this.loggedInUser = null; this.router.navigate(['/login']); this.clearCart(); // Navigate to the login page } clearCart() { this.cartService.clearCart(); } }
use uo; use os; include "include/wodinc"; include "include/client"; include "include/objtype"; include "include/spawn"; include "include/eventid"; include "include/effects"; include "include/attributes"; include "../pkg/items/doors/doors"; program use_lever (character, lever) var did_something := 0; if (GetObjProperty (lever, "usemessage")) PrintTextAbove (lever, GetObjProperty (lever, "usemessage")); endif if (GetObjProperty (lever, "spawnNPCGuardians")) SpawnNPCsFromSwitch (character, lever); did_something := 1; endif if (GetObjProperty (lever, "doorserial")) OpenDoorFromSwitch (character, lever); did_something := 1; endif if (GetObjProperty (lever, "unlockeditemserial")) UnlockChestFromSwitch (character, lever); did_something := 1; endif if (GetObjProperty (lever, "teleportx")) SwitchTeleporter (character, lever); did_something := 1; endif if (GetObjProperty (lever, "explosion")) var ev := struct{}; ev.+type := EVID_ENGAGED; ev.+source := character; PlayStationaryEffect (character.x, character.y, character.z, 0x36b0, 7, 0x10, 0, character.realm); PlaySoundEffect (character, 0x208); foreach critter in ListMobilesNearLocationEx (character.x, character.y, character.z, 5, LISTEX_FLAG_NORMAL + LISTEX_FLAG_HIDDEN, character.realm ); if (!GetObjProperty (critter, "#specialhidden_nodamage")) SendEvent (critter, ev); PlayObjectCenteredEffect (critter, 0x36b0, 7, 0x10); var dmg := Randomint(11) + 5; DoDamageByType (0, critter, dmg, DAMAGETYPE_FIRE); endif endforeach DestroyItem (lever); endif if (!did_something) SendSysMessage (character, "Hmm, seems broken."); endif endprogram // Spawns a number of NPCs function SpawnNPCsFromSwitch (character, lever) if (character) endif if (GetObjProperty (lever, "#spawnswitch")) if (GetObjProperty (lever, "#spawnswitch") > ReadGameClock()) return; endif endif SetObjProperty (lever, "#spawnswitch", ReadGameClock() + 600); var guardian_array := GetObjProperty (lever, "spawnNPCGuardians"); if (!guardian_array or !len(guardian_array)) return; endif foreach guardian_elem in guardian_array var npctemplate := guardian_elem[1]; var thenpc := SpawnNPCInArea (npctemplate, lever.x, lever.y, 4, 20, lever.realm); if (thenpc) thenpc.graphic := guardian_elem[2]; thenpc.color := guardian_elem[3]; SetObjProperty (thenpc, "color", thenpc.color); thenpc.name := guardian_elem[4]; var npc_script := guardian_elem[5]; if (npc_script) thenpc.script := npc_script; RestartScript (thenpc); endif var npc_str := guardian_elem[6]; if (npc_str) SetAttributeBaseValue (thenpc, "Strength", npc_str); endif var npc_dex := guardian_elem[7]; if (npc_dex) SetAttributeBaseValue (thenpc, "Dexterity", npc_dex); endif var npc_int := guardian_elem[8]; if (npc_int) SetAttributeBaseValue (thenpc, "Intelligence", npc_int); endif var npc_skills := guardian_elem[9]; if (npc_skills) for i := 0 to 48 SetAttributeBaseValue (thenpc, GetAttributeIDBySkillID (i), npc_skills[i]*10); endfor endif RecalcVitals (thenpc); thenpc.gender := guardian_elem[10]; endif endforeach endfunction // When the lever is thrown, the door opens for a short amount of time function OpenDoorFromSwitch (character, lever) var door_serial := GetObjProperty (lever, "doorserial"); var relock_time := GetObjProperty (lever, "relocktime"); var door := SystemFindObjectBySerial (door_serial); if (!door) SendSysMessage (character, "That doesn't seem to do anything..."); return; endif var alldoors := array{door}; if (door.graphic == door.objtype) set_critical (1); ChangeLeverGraphic (lever, 1); foreach item in ListItemsNearLocation (door.x, door.y, door.z, 1, door.realm) if (item.isa (POLCLASS_DOOR)) OpenDoor (item); PlayDoorOpenSound (item); alldoors.append (item); endif endforeach set_critical (0); endif if (!relock_time) return; endif var open_time := ReadGameClock(); SetObjProperty (door, "#lastopen", open_time ); sleep (relock_time); if (GetObjProperty (door, "#lastopen") == open_time) set_critical (1); foreach item in alldoors CloseDoor (item); PlayDoorCloseSound (item); endforeach ChangeLeverGraphic (lever, 0); EraseObjProperty (door, "#lastopen"); set_critical (0); endif endfunction // When the lever is thrown, a chest or door unlocks for a short period of time function UnlockChestFromSwitch (character, lever) var itemserial := GetObjProperty (lever, "unlockeditemserial"); var relock_time := GetObjProperty (lever, "relocktime"); var item := SystemFindObjectBySerial (itemserial); if (!item) SendSysMessage (character, "That doesn't seem to do anything..."); return; endif ChangeLeverGraphic (lever, 1); item.locked := 0; var alldoors := array{}; if (item.isa (POLCLASS_DOOR)) foreach possibledoor in ListItemsNearLocation (item.x, item.y, item.z, 1, item.realm) if (possibledoor.isa (POLCLASS_DOOR)) possibledoor.locked := 0; alldoors.append (possibledoor); endif endforeach endif if (!relock_time) return; endif var open_time := ReadGameClock (); SetObjProperty (item, "#leverswitch", open_time ); sleep (relock_time); if (GetObjProperty (item, "#leverswitch") == open_time) item.locked := 1; if (item.isa (POLCLASS_DOOR)) foreach door in alldoors door.locked := 1; endforeach endif ChangeLeverGraphic (lever, 0); EraseObjProperty (item, "#leverswitch"); if (item.isa (POLCLASS_DOOR)) CloseDoor (item); PlayDoorCloseSound (item); endif endif endfunction // When the lever is thrown, teleports the user function SwitchTeleporter (character, lever) var destx := GetObjProperty (lever, "teleportx"); var desty := GetObjProperty (lever, "teleporty"); var destz := GetObjProperty (lever, "teleportz"); var destr := GetObjProperty (lever, "teleportr"); if (!destr) destr := _DEFAULT_REALM; endif ChangeLeverGraphic (lever, 1); sleep (1); if(MoveObjectToLocation( character, destx, desty, destz, destr, flags := MOVEOBJECT_NORMAL )) if (!character.concealed) PlaySoundEffect (character, SFX_SPELL_RECALL); PlaySoundEffect (lever, SFX_SPELL_RECALL); endif endif var open_time := ReadGameClock (); SetObjProperty (lever, "#lastopen", open_time ); sleep (4); if (GetObjProperty (lever, "#lastopen") == open_time) ChangeLeverGraphic (lever, 0); EraseObjProperty (lever, "#lastopen"); endif endfunction // When the lever is thrown, teleports the user function SpawnSwitchNPC (character, lever) if (lever.container) SendSysMessage (character, "This lever cannot be used inside of a container!"); return; endif if (GetObjProperty (lever, "#spawnswitch")) if (GetObjProperty (lever, "#spawnswitch") > ReadGameClock()) return; endif endif SetObjProperty (lever, "#spawnswitch", ReadGameClock() + 600); var npctemplate := GetObjProperty (lever, "npctemplate"); ChangeLeverGraphic (lever, 1); sleep (1); SpawnNPCInArea (npctemplate, lever.x, lever.y); var open_time := ReadGameClock (); SetObjProperty (lever, "#lastopen", open_time ); sleep (9); if (GetObjProperty (lever, "#lastopen") == open_time) ChangeLeverGraphic (lever, 0); EraseObjProperty (lever, "#lastopen"); endif endfunction // Changes the graphic of the lever function ChangeLeverGraphic (lever, open := 1) case (lever.graphic) 0x108d: if (open) lever.graphic := 0x108e; endif 0x108e: if (!open) lever.graphic := 0x108d; endif 0x108f: if (open) lever.graphic := 0x1090; endif 0x1090: if (!open) lever.graphic := 0x108f; endif 0x1091: if (open) lever.graphic := 0x1092; endif 0x1092: if (!open) lever.graphic := 0x1091; endif 0x1094: if (open) lever.graphic := 0x1095; endif 0x1095: if (!open) lever.graphic := 0x1094; endif endcase endfunction
--схема БД: https://docs.google.com/document/d/1NVORWgdwlKepKq_b8SPRaSpraltxoMg2SIusTEN6mEQ/edit?usp=sharing --HomeWork_Lesson 3-4 --task13 (lesson3) --Компьютерная фирма: Вывести список всех продуктов и производителя с указанием типа продукта (pc, printer, laptop). Вывести: model, maker, type with all_models as ( select model from pc union all select model from laptop union all select model from printer ) select model, maker, type from all_models join product using (model) --task14 (lesson3) --Компьютерная фирма: При выводе всех значений из таблицы printer дополнительно вывести для тех, у кого цена вышей средней PC - "1", у остальных - "0" select * from printer where price > (select avg(price) from printer ) select *, case when price > (select avg(price) from printer) then 1 else 0 end flag from printer --task15 (lesson3) --Корабли: Вывести список кораблей, у которых class отсутствует (IS NULL) select * from ships where class is null --task16 (lesson3) --Корабли: Укажите сражения, которые произошли в годы, не совпадающие ни с одним из годов спуска кораблей на воду. комментарий: нужно разобрать пример по этой задаче гуглинг не помог не получилось сопоставить разные типы данных: battles.date и ships.launched --task17 (lesson3) --Корабли: Найдите сражения, в которых участвовали корабли класса Kongo из таблицы Ships. вариант 1 select battle from outcomes join ships on outcomes.ship = ships.name where class = 'Kongo' вариант 2 select battle from outcomes where ship = any (select name from ships where class ='Kongo') --task1 (lesson4) -- Компьютерная фирма: Сделать view (название all_products_flag_300) для всех товаров (pc, printer, laptop) с флагом, если стоимость больше > 300. Во view три колонки: model, price, flag create view all_products_flag_300 as with all_product as ( select model, price, code from pc union select model, price, code from printer union select model, price, code from laptop ) select model, price, case when price > 300 then 1 else 0 end flag from all_product --task2 (lesson4) -- Компьютерная фирма: Сделать view (название all_products_flag_avg_price) для всех товаров (pc, printer, laptop) с флагом, если стоимость больше cредней . Во view три колонки: model, price, flag create view all_products_flag_avg_price as with all_product as ( select model, price, code from pc union select model, price, code from printer union select model, price, code from laptop ) select model, price, case when price > (select avg(price) from all_product) then 1 else 0 end flag from all_product --task3 (lesson4) -- Компьютерная фирма: Вывести все принтеры производителя = 'A' со стоимостью выше средней по принтерам производителя = 'D' и 'C'. Вывести model коммент к решению в таблице Product нет производителя Printer = С только A,D,E поэтому среднюю будем искать по производителю принтеров D и E select model from printer join product using (model) where maker ='A' and price > (select avg(price) from printer join product using (model) where maker > 'A') --task4 (lesson4) -- Компьютерная фирма: Вывести все товары производителя = 'A' со стоимостью выше средней по принтерам производителя = 'D' и 'C'. Вывести model эта задача дублирует task3 --task5 (lesson4) -- Компьютерная фирма: Какая средняя цена среди уникальных продуктов производителя = 'A' (printer & laptop & pc) select (( select sum(price) from laptop join product using(model) where maker = 'A' ) + ( select sum(price) from printer join product using(model) where maker = 'A' ) + ( select sum(price) from pc join product using(model) where maker = 'A' )) / ( ( select count(price) from laptop join product using(model) where maker = 'A' ) + ( select count(price) from printer join product using(model) where maker = 'A' ) + ( select count(price) from pc join product using(model) where maker = 'A' ) ) --task6 (lesson4) -- Компьютерная фирма: Сделать view с количеством товаров (название count_products_by_makers) по каждому производителю. Во view: maker, count create view count_products_by_makers as with products_by_makers as ( select model, maker from pc join product using (model) union all select model, maker from printer join product using (model) union all select model,maker from laptop join product using (model) ) select maker, count(*) as quantity from products_by_makers group by maker order by quantity --task7 (lesson4) -- По предыдущему view (count_products_by_makers) сделать график в colab (X: maker, y: count) ссылка на колаб https://colab.research.google.com/drive/1MFDge7pxCIZSiofsm8q0EczZ58QT13bJ#scrollTo=_1ZDOBt4LnSi&line=11&uniqifier=1 --task8 (lesson4) -- Компьютерная фирма: Сделать копию таблицы printer (название printer_updated) и удалить из нее все принтеры производителя 'D' CREATE TABLE printer_updated as with product_renametype as ( select maker, model, type as typemaker from product ) SELECT model, code, color, type, price FROM printer join product_renametype using (model) where maker <> 'D' --task9 (lesson4) -- Компьютерная фирма: Сделать на базе таблицы (printer_updated) view с дополнительной колонкой производителя (название printer_updated_with_makers) CREATE view printer_updated_with_makers as with product_renametype as ( select maker, model, type as typemaker from product ) select model, code, color, type, price, maker FROM printer_updated join product_renametype using (model) order by maker --task10 (lesson4) -- Корабли: Сделать view c количеством потопленных кораблей и классом корабля (название sunk_ships_by_classes). Во view: count, class (если значения класса нет/IS NULL, то заменить на 0) create view sunk_ships_by_classes as with table1 as ( select class, name from outcomes join ships on outcomes.ship = ships.name where result = 'sunk' ) select class as clas, count(*) as quantity from table1 group by class --task11 (lesson4) -- Корабли: По предыдущему view (sunk_ships_by_classes) сделать график в colab (X: class, Y: count) https://colab.research.google.com/drive/1MFDge7pxCIZSiofsm8q0EczZ58QT13bJ#scrollTo=B3o6rCPAvPMy&line=17&uniqifier=1 --task12 (lesson4) -- Корабли: Сделать копию таблицы classes (название classes_with_flag) и добавить в нее flag: если количество орудий больше или равно 9 - то 1, иначе 0 create table classes_with_flag as select *, case when numguns >= 9 then 1 else 0 end flag from classes --task13 (lesson4) -- Корабли: Сделать график в colab по таблице classes с количеством классов по странам (X: country, Y: count) график по ссылке https://colab.research.google.com/drive/1MFDge7pxCIZSiofsm8q0EczZ58QT13bJ#scrollTo=hO6tO43X2Plc&line=3&uniqifier=1 select country, count(*) as quantity_clasess from classes group by country --task14 (lesson4) -- Корабли: Вернуть количество кораблей, у которых название начинается с буквы "O" или "M". select count(name) from ships where name like 'M%' or name like 'O%' --task15 (lesson4) -- Корабли: Вернуть количество кораблей, у которых название состоит из двух слов. select * from ships WHERE name like '% %'; --task16 (lesson4) -- Корабли: Построить график с количеством запущенных на воду кораблей и годом запуска (X: year, Y: count) ссылка на график https://colab.research.google.com/drive/1MFDge7pxCIZSiofsm8q0EczZ58QT13bJ#scrollTo=tckNFKSUOvW1&line=3&uniqifier=1 select launched, count(*) as quontity_ships_launched from ships group by launched
const express = require('express'); const app = express(); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const cors = require('cors'); require('dotenv').config(); //const fileUpload = require('express-fileupload'); //middlewares app.use(cors()); app.use(express.json()); // const spell = require('spell-checker-js') const port = 5002; mongoose.set('strictQuery', true); app.get('/', (req, res) => { res.send('Hello, World!').status(200); }); app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', 'http://localhost:5001'); res.header( 'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept' ); next(); }); //authentication module const authRoutes = require('./routes/auth'); app.use('/auth',authRoutes); //admin module const adminRoutes = require('./routes/taxBracketAdmin'); app.use('/admin',adminRoutes); //tax calculation module const taxCalcRoutes = require('./routes/taxCalc'); app.use('/taxCalc',taxCalcRoutes); //user profile module const userProfileRoutes = require('./routes/userProfileRoutes'); app.use('/userProfile',userProfileRoutes); //friend request module const friendRequestRoutes = require('./routes/familyAdding'); app.use('/friendRequest',friendRequestRoutes); const connectionParams={ useNewUrlParser: true, useUnifiedTopology: true } mongoose.connect(process.env.DB_CONNECTION, connectionParams, ) .then(()=>console.log('DB connected')) .catch(e=>console.log(e)); //how do we start listening to the server app.listen(5002); // create a get route to welcome app.get('/',(req,res)=>{ res.send('we are on home'); res.status(200); }); console.log('listening on port ', port); module.exports=app;
import moment from 'moment'; import { useState, useCallback, useEffect } from 'react'; import { v4 as uuid } from 'uuid'; import PerfectScrollbar from 'react-perfect-scrollbar'; import { Link as RouterLink } from 'react-router-dom'; import { Box, Button, Card, CardHeader, Link, Divider, Table, TableBody, TableCell, TableHead, TableRow, } from '@material-ui/core'; import ArrowRightIcon from '@material-ui/icons/ArrowRight'; import useMounted from '../../hooks/useMounted'; import { propertiesApi } from '../../api/PropertiesApi'; const DueTasks = (props) => { const [tasks, setTasks]= useState([]); const mounted = useMounted(); const getDueTasks = useCallback(async () => { try { let data = await propertiesApi.getDueTasks(); data = data.sort().slice(-5); if (mounted.current) { setTasks(data); } } catch (err) { console.error(err); } }, [mounted]); useEffect(() => { getDueTasks(); }, [getDueTasks]); return ( <Card {...props}> <CardHeader title="Tasks" /> <Divider /> <Table> <TableHead> <TableRow> <TableCell> Task </TableCell> <TableCell sortDirection="desc"> Date </TableCell> </TableRow> </TableHead> <TableBody> {tasks.map((task) => ( <TableRow key={task.id}> {task.name && <> <TableCell> <Link component={RouterLink} to="/dashboard/kanban"> {task.name} </Link> </TableCell> <TableCell> {task.createdAt} </TableCell> </>} <> {task.status ==0 && <> <TableCell> <Link component={RouterLink} to="/dashboard/kanban"> {(() => { if (task.type === 'LANDLORD_EMERGENCY_COVER') return 'LANDLORD EMERGENCY COVER' + ' is about to expire'; else if (task.type === 'RENT_PROTECTION_INSURANCE') return 'RENT PROTECTION INSURANCE' + ' is about to expire'; else if (task.type === 'BUILDING_INSURANCE') return 'BUILDING INSURANCE' + ' is about to expire'; else if (task.type === 'CONTENT_INSURANCE') return 'CONTENT INSURANCE' + ' is about to expire'; else return task.type + ' is about to expire'; })()} </Link> </TableCell> <TableCell> {task.createdAt} </TableCell> </> } {task.status ==1 && <> <TableCell> <Link component={RouterLink} to="/dashboard/kanban"> {(() => { if (task.type === 'LANDLORD_EMERGENCY_COVER') return 'LANDLORD EMERGENCY COVER' + ' expired'; else if (task.type === 'RENT_PROTECTION_INSURANCE') return 'RENT PROTECTION INSURANCE' + ' expired'; else if (task.type === 'BUILDING_INSURANCE') return 'BUILDING INSURANCE' + ' expired'; else if (task.type === 'CONTENT_INSURANCE') return 'CONTENT INSURANCE' + ' expired'; else return task.type + ' expired'; })()} </Link> </TableCell> <TableCell> {task.createdAt} </TableCell> </> } </> </TableRow> ))} </TableBody> </Table> <Box sx={{ display: 'flex', justifyContent: 'flex-end', p: 2 }}> <Button component={RouterLink} color="primary" endIcon={<ArrowRightIcon />} to = "/dashboard/kanban" size="small" variant="text"> View all </Button> </Box> </Card> ) }; export default DueTasks;
import mido import os from os import environ environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "1" import pygame import tkinter as tk from tkinter import messagebox from tkinter import ttk # Dictionary mapping characters to MIDI notes char_to_note = { "A": 60, "B": 61, "C": 62, "D": 63, "E": 64, "F": 65, "G": 66, "H": 67, "I": 68, "J": 69, "K": 70, "L": 71, "M": 72, "N": 73, "O": 74, "P": 75, "Q": 76, "R": 77, "S": 78, "T": 79, "U": 80, "V": 81, "W": 82, "X": 83, "Y": 84, "Z": 85, " ": 86, "?": 87, ",": 88, ".": 89, "!": 90, "0": 91, "1": 92, "2": 93, "3": 94, "4": 95, "5": 96, "6": 97, "7": 98, "8": 99, "9": 100, } def text_to_midi(text): mid = mido.MidiFile() track = mido.MidiTrack() track.append(mido.Message("program_change", program=2)) for char in text.upper(): if char in char_to_note: note = char_to_note[char] track.append(mido.Message("note_on", note=note, velocity=100, time=0)) track.append(mido.Message("note_off", note=note, velocity=0, time=80)) mid.tracks.append(track) return mid def save_midi(output_file_path, midi_data): output_directory = "../midis/" path_name = "output%s.mid" # Increment midi output name if path already exists def next_path(path_pattern): i = 1 while os.path.exists(path_pattern % i): i += 1 return path_pattern % i output_file_path = next_path(os.path.join(output_directory, path_name)) midi_data.save(output_file_path) return output_file_path def play_midi(output_file_path): play_midi = messagebox.askyesno( "Play MIDI", "Do you wish to hear the encoded message?" ) if play_midi: pygame.mixer.init() pygame.mixer.music.load(output_file_path) pygame.mixer.music.play() def convert_text_to_midi(): text = entry_text.get() if text: midi_data = text_to_midi(text) output_file_path = save_midi("../midis/", midi_data) messagebox.showinfo( "MIDI Saved", f"MIDI file saved to: {os.path.abspath(output_file_path)}" ) play_midi(output_file_path) else: messagebox.showwarning("No Text Entered", "Please enter some text to convert.") # Create main window root = tk.Tk() root.title("Text to MIDI Converter") # Configure style style = ttk.Style(root) style.theme_use("clam") # Use a different theme for a modern look style.configure("TLabel", font=("Arial", 12)) style.configure("TButton", font=("Arial", 12)) # Set window size root.geometry("600x300") # Set width to 600 and height to 300 # Function to center the window def center_window(width, height): # Get screen width and height screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() # Calculate x and y coordinates for the window to be centered x = (screen_width / 2) - (width / 2) y = (screen_height / 2) - (height / 2) root.geometry("%dx%d+%d+%d" % (width, height, x, y)) # Center the window center_window(600, 300) # Create explanation label label_explanation = ttk.Label( root, text="Enter the text you want to convert to MIDI below:" ) label_explanation.pack(pady=10) # Create input field entry_text = ttk.Entry(root, width=60, font=("Arial", 12)) entry_text.pack(pady=10) # Create convert button button_convert = ttk.Button( root, text="Convert Text to MIDI", command=convert_text_to_midi ) button_convert.pack(pady=10) root.mainloop()
<?php namespace App\Http\Controllers\User; use App\Models\User\Role; use App\Models\User\Employee; use Illuminate\Support\Facades\DB; use App\Transformers\Role\RoleTransformer; use App\Http\Requests\UserRole\StoreRequest; use App\Http\Requests\UserRole\DestroyRequest; use App\Events\Employee\StoreEmployeeRoleEvent; use App\Events\Employee\DestroyEmployeeRoleEvent; use App\Transformers\Auth\EmployeeRoleTransformer; use App\Http\Controllers\GlobalController as Controller; class UserRoleController extends Controller { public function __construct() { parent::__construct(); $this->middleware('transform.request:' . EmployeeRoleTransformer::class)->only('store', 'update'); $this->middleware('scope:account,account_read')->only('index'); $this->middleware('scope:account,account_register')->only('store'); $this->middleware('scope:account,account_update')->only('update'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Employee $user) { $roles = $user->roles()->get(); return $this->showAll($roles, EmployeeRoleTransformer::class); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(StoreRequest $request, Employee $user) { DB::transaction(function () use ($request, $user) { $user->roles()->syncWithoutDetaching($request->role_id); }); StoreEmployeeRoleEvent::dispatch($this->authenticated_user()); return $this->showOne(Role::find($request->role_id), RoleTransformer::class, 201); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy(DestroyRequest $request, Employee $user, Role $role) { DB::transaction(function () use ($role, $user) { $user->roles()->detach($role->id); }); DestroyEmployeeRoleEvent::dispatch($this->authenticated_user()); return $this->showOne($role, $role->transformer); } }
// here we remove unnecessary retrieval of user (see getMe func) const jwt = require('jsonwebtoken') const bcrypt = require('bcryptjs') const asyncHandler = require('express-async-handler') const User = require('../models/userModel.js') const registerUser = asyncHandler(async(req, res) => { const {name, email, password} = req.body if (!name || !email || !password) { res.status(400) throw new Error('Please add all fields') } const userExists = await User.findOne({email}) if (userExists) { res.status(400) throw new Error('User already exists') } const salt = await bcrypt.genSalt(10) const hashedPassword = await bcrypt.hash(password, salt) const user = await User.create({ name, email, password: hashedPassword }) if (user) { res.status(201).json({ _id: user.id, name: user.name, email: user.email, token: generateToken(user._id) }) } else { res.status(400) throw new Error('Invalid user data') } }) const loginUser = asyncHandler(async(req, res) => { const {email, password} = req.body const user = await User.findOne({email}) if (user && (await bcrypt.compare(password, user.password))) { res.json({ _id: user.id, name: user.name, email: user.email, token: generateToken(user._id) }) } else { res.status(400) throw new Error('Invalid credentials') } }) const getMe = asyncHandler(async(req, res) => { res.status(200).json(req.user) // send back all the user's info. No need to find him again. }) const generateToken = (id) => { return jwt.sign({ id }, process.env.JWT_SECRET, { expiresIn:'30d', }) } module.exports = { registerUser, loginUser, getMe, }
/* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * * This code was contributed from the Molecular Biology Toolkit * (MBT) project at the University of California San Diego. * * Please reference J.L. Moreland, A.Gramada, O.V. Buzko, Qing * Zhang and P.E. Bourne 2005 The Molecular Biology Toolkit (MBT): * A Modular Platform for Developing Molecular Visualization * Applications. BMC Bioinformatics, 6:21. * * The MBT project was funded as part of the National Institutes * of Health PPG grant number 1-P01-GM63208 and its National * Institute of General Medical Sciences (NIGMS) division. Ongoing * development for the MBT project is managed by the RCSB * Protein Data Bank(http://www.pdb.org) and supported by funds * from the National Science Foundation (NSF), the National * Institute of General Medical Sciences (NIGMS), the Office of * Science, Department of Energy (DOE), the National Library of * Medicine (NLM), the National Cancer Institute (NCI), the * National Center for Research Resources (NCRR), the National * Institute of Biomedical Imaging and Bioengineering (NIBIB), * the National Institute of Neurological Disorders and Stroke * (NINDS), and the National Institute of Diabetes and Digestive * and Kidney Diseases (NIDDK). * * Created on 2008/12/22 * */ package org.rcsb.ks.ui; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import javax.swing.BoxLayout; import javax.swing.JPanel; import javax.swing.JTextArea; import org.rcsb.vf.controllers.scene.SceneState; /** * Represents the right lower panel in the Kiosk Viewer. * This area displays the ligand being animated in the Kiosk Viewer. * * @author Peter Rose * */ public class StateAnnotationPanel extends JPanel { private static final long serialVersionUID = 8133311298423034878L; private JTextArea ligandName = new JTextArea (); /** * Sets up the StateAnnoationPanel */ public StateAnnotationPanel(Dimension size) { setLayout ( new BoxLayout ( this, BoxLayout.Y_AXIS )); setBackground(Color.black); // scale font size by height of the panel ligandName.setFont( new Font ("Helvetica", Font.BOLD, size.height/6)); ligandName.setBackground (Color.black); ligandName.setForeground(Color.green); ligandName.setWrapStyleWord(true); ligandName.setLineWrap(true); add(ligandName); } /** * Updated the ligand name and repaints the panel * * @param state */ public void updateState(SceneState state) { String name = state.toString(); // pad short names with blanks int diff = 25 - name.length(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < diff; i++) { sb.append(" "); } sb.append(name); ligandName.setText(sb.toString()); repaint (); } }
library(limma) library(edgeR) ## LikeDESeq2, import count data, use cpm to filter data exprSet<- read.table(file = "/home/xu/RNAseq/edegR/D01357/D01357_counts", sep = "\t", header = TRUE, row.names = 1, stringsAsFactors = FALSE) # exprSet <- exprSet[,1:21] group_list <- factor(c(rep("D0",3),rep("D1",3),rep("D3",3),rep("D5",3),rep("D7",3))) group_list time_course <- relevel(group_list, ref = "D0") # reorder levels of factors exprSet <- DGEList(counts = exprSet, group = time_course) # genes=genes exprSet dim(exprSet) ## only keeping a gene if it has a cpm of 1 or greater (100) for at least 3 samples exprSet <- exprSet[rowSums(cpm(exprSet) > 1) >= 3,] # or just simply, use filterByExpr() dim(exprSet) ## reset the library sizes exprSet$samples$lib.size <- colSums(exprSet$counts) exprSet$samples ## TMM normalization, without this, the normailization factor (RNA composition) will be 1 as default value exprSet <- calcNormFactors(exprSet, method="TMM") exprSet design <- model.matrix(~ time_course) design exprSet <- estimateDisp(exprSet, design) # NB dispersion sqrt(exprSet$common.dispersion) plotBCV(exprSet) fit <- glmQLFit(exprSet, design, robust = TRUE) plotQLDisp(fit) fit <- glmQLFTest(fit, coef=2:5) # coef, To find genes different between any two of the groups: tab <- as.data.frame(topTags(fit, n=nrow(exprSet))) tab write.table(tab, file = "D01357_qlf_timecourse", sep = "\t") summary(decideTests(fit, lfc=1, p.value = 0.01)) # absolute logFC should be at least 1, p value (is FDR actually) less than 0.05 as cutoff of significance sig<-decideTests(fit, lfc=1, p.value = 0.01) # 1 is true, 0 is false write.table(sig, file = "D01357_qlf_timecourse_sig", sep = "\t") ## DEG fit <- glmQLFit(exprSet, design, robust = TRUE) qlf.D1vsD0 <- glmQLFTest(fit, contrast = c(0,1,0,0,0)) # compare group2 vs 1, or any other group number vs group1, gruop 1 is always the reference tTag <- topTags(qlf.D1vsD0, n=nrow(exprSet)) #diff_gene_edgeR <- subset(tTag$table, FDR < 0.05 & (logFC > 1 | logFC < -1)) #diff_gene_edgeR <- row.names(diff_gene_edgeR) write.table(tTag$table, file = "D1vsD0_qlf_DGE", sep = "\t") fit <- glmQLFit(exprSet, design, robust = TRUE) qlf.D3vsD1 <- glmQLFTest(fit, contrast = c(0,-1,1,0,0)) # compare group3 vs 2 tTag <- topTags(qlf.D3vsD1, n=nrow(exprSet)) write.table(tTag$table, file = "D3vsD1_qlf_DGE", sep = "\t") fit <- glmQLFit(exprSet, design, robust = TRUE) qlf.D7vsD5 <- glmQLFTest(fit, contrast = c(0,0,0,-1,1)) # compare group4 vs 3 tTag <- topTags(qlf.D7vsD5, n=nrow(exprSet)) write.table(tTag$table, file = "D7vsD5_qlf_DGE", sep = "\t") ## RPKM or CPM ## extract gene length infor write.table(exprSet$counts, file = "exprSet_counts", sep = "\t", row.names = TRUE, col.names = TRUE) # extract expressed genes to get their gene length length<- read.table(file = "/home/xu/RNAseq/edegR/D01357/exprSet_length", sep = "\t", header = TRUE, row.names = 1, stringsAsFactors = FALSE) rpkm_nomalized <- rpkm(exprSet, gene.length=length$Length, normalized.lib.sizes=TRUE, log=FALSE) # prior.count=2, write.table(rpkm_nomalized, file = "D01357_qlf_rpkm", sep = "\t", row.names = TRUE, col.names = TRUE) log_rpkm_nomalized <- rpkm(exprSet, gene.length=length$Length, prior.count=2, normalized.lib.sizes=TRUE, log=TRUE) write.table(log_rpkm_nomalized, file = "D01357_qlf_logrpkm", sep = "\t", row.names = TRUE, col.names = TRUE) ## heatmap map clusteing logrpkm <- rpkm(exprSet, gene.length=length$Length, prior.count=2, normalized.lib.sizes=TRUE, log=TRUE) rownames(logrpkm) <- exprSet$genes$Symbol colnames(logrpkm) <- paste(exprSet$samples, sep="\t") # dimnames not inputed,it should be 1:21. Without dimnames, heatmap can show original sample name logrpkm <- t(scale(t(logrpkm))) #scale each gene to have mean zero and standard deviation library(gplots) col.pan <- colorpanel(100, "red", "white", "blue") heatmap.2(logrpkm, col=col.pan, Rowv=TRUE, scale="none", labRow = NULL, trace="none", dendrogram="both", cexRow=1, cexCol=1.4, density.info="none", key = TRUE, keysize = TRUE, margin=c(10,9), lhei=c(2,10), lwid=c(2,6))
using Application.Contracts.Persistence; using Domain; using MediatR; namespace Application.UseCases.AssetOwners.GetAssetOwnerList; /// <summary> /// Handles the query to get a list of asset owners. /// </summary> internal class GetAssetOwnersQueryHandler : IRequestHandler<GetAssetOwnersQuery, List<AssetOwner>> { private readonly IAssetOwnerRepository _assetOwnerRepository; /// <summary> /// Initializes a new instance of the <see cref="GetAssetOwnersQueryHandler"/> class. /// </summary> /// <param name="assetOwnerRepository">The asset owner repository.</param> public GetAssetOwnersQueryHandler(IAssetOwnerRepository assetOwnerRepository) { _assetOwnerRepository = assetOwnerRepository; } /// <summary> /// Handles the get asset owners query. /// </summary> /// <param name="request">The get asset owners query.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The list of asset owners.</returns> public async Task<List<AssetOwner>> Handle(GetAssetOwnersQuery request, CancellationToken cancellationToken) { return await _assetOwnerRepository.ListAll(); } }
<?php namespace App\EloquentBuilders; use Illuminate\Database\Eloquent\Builder; class FilterBuilder extends Builder { public const WHERE = 'where'; public const WHERE_OR = 'orWhere'; public const OPERATOR_EQUAL = '='; public const OPERATOR_NOT_EQUAL = '!='; public const OPERATOR_LESS_THAN = '<'; public const OPERATOR_LESS_THAN_OR_EQUAL = '<='; public const OPERATOR_GREATER_THAN = '>'; public const OPERATOR_GREATER_THAN_OR_EQUAL = '>='; public const OPERATOR_LIKE = 'like'; public const OPERATOR_START_WITH = 'startWith'; public const OPERATOR_END_WITH = 'endWith'; public const OPERATOR_CONTAINS = 'contain'; public const OPERATOR_IN = 'in'; public const OPERATOR_NOT_IN = 'notIn'; public const RELATION_FIELD_SEPARATOR = '.'; public function buildFilter(array $queries): self { foreach ($queries as $query) { [$whereType, $field, $operator, $value] = $query; $this->when(! empty($value), function ($q) use ($whereType, $field, $operator, $value) { if ($this->isRelationField($field)) { $this->buildWhereHasClause($q, $whereType, $field, $operator, $value); } elseif (in_array($operator, [self::OPERATOR_IN, self::OPERATOR_NOT_IN])) { $q->whereIn( $field, $this->parseQueryValue($operator, $value), $whereType === self::WHERE_OR ? 'or' : 'and', $operator === self::OPERATOR_NOT_IN ); } else { $q->$whereType($field, $this->parseQueryOperator($operator), $this->parseQueryValue($operator, $value)); } }); } return $this; } private function buildWhereHasClause(Builder $query, string $whereType, string $field, string $operator, string|array $value): void { $parseFields = explode(self::RELATION_FIELD_SEPARATOR, $field); if (count($parseFields) == 1) { return; } $relationField = array_shift($parseFields); $whereHasType = $whereType === self::WHERE_OR ? 'orWhereHas' : 'whereHas'; $query->$whereHasType($relationField, function ($q) use ( $parseFields, $operator, $value ) { if (count($parseFields) > 1) { $this->buildWhereHasClause($q, self::WHERE, implode(self::RELATION_FIELD_SEPARATOR, $parseFields), $operator, $value); } else { if (in_array($operator, [self::OPERATOR_IN, self::OPERATOR_NOT_IN])) { $q->whereIn( $parseFields[0], $this->parseQueryValue($operator, $value), 'and', $operator === self::OPERATOR_NOT_IN ); } else { $q->where($parseFields[0], $this->parseQueryOperator($operator), $this->parseQueryValue($operator, $value)); } } }); } private function isRelationField(string $field): bool { return str_contains($field, self::RELATION_FIELD_SEPARATOR); } private function parseQueryOperator(string $operator): string { if (in_array($operator, [self::OPERATOR_START_WITH, self::OPERATOR_END_WITH, self::OPERATOR_CONTAINS])) { return self::OPERATOR_LIKE; } return $operator; } private function parseQueryValue(string $operator, string|array $value): string|array { return match ($operator) { self::OPERATOR_START_WITH => '%'.$value, self::OPERATOR_END_WITH => $value.'%', self::OPERATOR_CONTAINS => '%'.$value.'%', default => $value, }; } }
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:google_mobile_ads/google_mobile_ads.dart'; import 'package:quize_project/Model/Quez.dart'; import 'package:quize_project/View/singnIn.dart'; import '../Servise/FarebaseBackend.dart'; import '../Servise/auth.dart'; import 'CreatQuize.dart'; import 'QuationPage.dart'; class HomePage extends StatefulWidget { const HomePage({Key? key}) : super(key: key); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { var _QuizeFuture = FirestoreBackend().getQuize(); List<Quize>? _Quize; BannerAd? bannerAd; bool isLodded = false; @override void didChangeDependencies() { super.didChangeDependencies(); bannerAd = BannerAd( size: AdSize.banner, adUnitId: "ca-app-pub-3940256099942544/6300978111", listener: BannerAdListener(onAdLoaded: (a) { setState(() { isLodded = true; }); }, onAdFailedToLoad: (a, error) { a.dispose(); }), request: const AdRequest(), ); bannerAd!.load(); } @override Widget build(BuildContext context) { return FutureBuilder<List<Quize>>( future: _QuizeFuture, builder: (context, snapshot) { _Quize = snapshot.hasData ? snapshot.data! : []; return Scaffold( drawer: Drawer( child: SafeArea( child: Column( children: [ ListTile( title: Text('Sign out'), onTap: () { AuthServise.signOut(); Navigator.of(context).pushAndRemoveUntil( MaterialPageRoute(builder: (_) => singin()), (_) => false); }, ), ], ), ), ), appBar: AppBar(title: Text('Home Page')), body: Container( child: ListView.separated( itemBuilder: (_, index) { return _toWidget(_Quize![index]); }, separatorBuilder: (_, __) => Divider(), itemCount: _Quize!.length, ), ), floatingActionButton: FloatingActionButton( child: Icon(Icons.add), onPressed: () { Navigator.push(context, MaterialPageRoute(builder: (context) => const CreateQuize())); }, ), persistentFooterButtons: [ Column(children: [ const Spacer(), isLodded ? SizedBox( height: 50, child: AdWidget( ad: bannerAd!, ), ) : const SizedBox(), ]) ], ); }, ); } Widget _toWidget(Quize Q) { return Stack( children: [ GestureDetector( onTap: () { String? id = Q.id; Navigator.push( context, MaterialPageRoute( builder: (context) => QuationPage( quizeId: id, ))); print(Q.id); }, child: Container( color: Colors.grey, alignment: Alignment.center, child: Column(children: [ Text(Q.QuizeTitle.toString(), style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500, color: Colors.white)), Text(Q.QuizeDescription.toString(), style:TextStyle(color: Colors.white)) ]), ), ) ], ); } }
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #include <sys/resource.h> void print_fibonacci(long n) { long first = 0, second = 1, next, i; if (n == 1) { printf("%lu", first); } else if (n >= 2) { printf("%lu %lu ", first, second); for (i = 3; i <= n; i++) { next = first + second; printf("%lu ", next); first = second; second = next; } } printf("\n"); } void print_powers_of_two(int n) { int i, p = 1; for (i = 0; i < n; i++) { printf("%d ", p); p *= 2; } printf("\n"); } int is_prime(int n) { int i; if (n < 2) return 0; for (i = 2; i * i <= n; i++) { if (n % i == 0) return 0; } return 1; } void print_primes(int n) { int i, count = 0, num = 2; while (count < n) { if (is_prime(num)) { printf("%d ", num); count++; } num++; } printf("\n"); } double get_time() { struct rusage usage; getrusage(RUSAGE_SELF, &usage); return usage.ru_utime.tv_sec + (usage.ru_utime.tv_usec / 1000000.0); } int main() { pid_t pid1, pid2; int status; pid1 = fork(); if (pid1 == -1) { perror("fork"); exit(EXIT_FAILURE); } else if (pid1 == 0) { // child process 1 printf("Fibonacci series:\n"); print_fibonacci(100); exit(EXIT_SUCCESS); } else { // parent process pid2 = fork(); if (pid2 == -1) { perror("fork"); exit(EXIT_FAILURE); } else if (pid2 == 0) { // child process 2 printf("Powers of two:\n"); print_powers_of_two(10); exit(EXIT_SUCCESS); } else { // parent process printf("Primes:\n"); print_primes(50); waitpid(pid1, &status, 0); waitpid(pid2, &status, 0); } } return 0; }
# Q4 - Are there differences in activity patterns between weekdays and weekends? ## Create a new factor variable in the dataset with two levels - "weekday" and "weekend" indicating whether a given date is a weekday or weekend day. activity.imputed$day <- ifelse(weekdays(as.Date(activity.imputed$date)) == "Saturday" | weekdays(as.Date(activity.imputed$date)) == "Sunday", "weekend", "weekday") ## Make a panel plot containing a time series plot of the 5-minute interval and the average number of steps taken, averaged across all weekday days or weekend days stepsPerInterval.weekend <- tapply(activity.imputed[activity.imputed$day == "weekend" ,]$steps, activity.imputed[activity.imputed$day == "weekend" ,]$interval, mean, na.rm = TRUE) stepsPerInterval.weekday <- tapply(activity.imputed[activity.imputed$day == "weekday" ,]$steps, activity.imputed[activity.imputed$day == "weekday" ,]$interval, mean, na.rm = TRUE) ### Set a 2 panel plot par(mfrow=c(1,2)) ### Plot weekday activity plot(as.numeric(names(stepsPerInterval.weekday)), stepsPerInterval.weekday, xlab="Interval", ylab="Steps", main="Activity Pattern (Weekdays)", type="l") ### Plot weekend activity plot(as.numeric(names(stepsPerInterval.weekend)), stepsPerInterval.weekend, xlab="Interval", ylab="Steps", main="Activity Pattern (Weekends)", type="l")
#' Method 1 for finding the date inside the label #' #' @param tree A tree of sequences, phylo #' @param order Location of the date, character or numeric #' #' @return date, character #' @export #' #' @examples #' #' data("MCC_FluA_H3_tree") #' dateType1(MCC_FluA_H3_tree, "last") #' dateType1 <- function(tree, order) { date <- numeric(length(tree$tip.label))##count tip if (order == "last") { for (i in 1:length(tree$tip.label)) { result <- regexpr("\\d+(\\-?|\\d+)+(\\-?|\\d+)$", tree$tip.label[i]) pos <- result[1] length <- attr(result, "match.length") - 1 ##substr(x,start,stop),get the time time <- substr(tree$tip.label[i], pos, pos + length) ## save in date date[i] <- time }} else{ for (i in 1:length(tree$tip.label)) { order <- as.numeric(order) result <- gregexpr("\\d+(\\-?|\\d+)+(\\-?|\\d+)", tree$tip.label[i]) pos <- result[[1]][order] length <- attr(result[[1]], "match.length")[order] - 1 time <- substr(tree$tip.label[i], pos, pos + length) date[i] <- time }} return(date) }
import { Element } from "../Element.js"; import { Permission } from "../models/Permission.js"; import { Session } from "../models/Session.js"; export class Template { session = new Session('Template') menuIsOpen = false constructor(app, body, props) { this.app = app this.header = new Element('div', {class: 'header'}).add(body) this.nav = new Element('div', {class: 'nav'}).add(body) this.body = body this.renderHeader() this.enableMenu() } renderHeader() { const menu = new Element('div', {class: 'menu'}).add(this.header) new Element('img', {src: 'assets/images/zaf-logo.png', alt: 'ZAF Logo', class: 'logo'}).add(this.header) new Element('div', 'BETA', {class: 'beta'}).add(this.header) this.setAccount() // menu btn this.menuBtn = new Element('button', '<i class="fa-solid fa-bars"></i>', {class: 'menu-btn', tabindex: 1000}).add(menu) new Element('a', '<i class="fa-solid fa-phone fa-lg"></i> &nbsp; <span class="phone-action">801-255-2102</span>', {href: 'tel:801-255-2102'}).add(menu) } async logout() { window.location = '/account/logout/' } enableMenu() { document.addEventListener('click', (event) => { if (!this.nav.getRoot().contains(event.target) && !this.menuBtn.getRoot().contains(event.target)) { this.closeMenu() } else { this.openMenu() } }); } openMenu() { this.open = true this.nav.addClass('open') } closeMenu() { this.open = false this.nav.removeClass('open') } navigate(path, e) { e.preventDefault() this.app.route(path) setTimeout(() => { if(this.closeMenu) this.closeMenu() }, 100); } setAccount(forceSet) { if(this.account) this.account.remove() console.log('session', this.session.get('user')) if(this.session.get('user') || forceSet){ this.account = new Element('div', 'Logout &nbsp; <i class="fa-solid fa-circle-user fa-xl"></i>', {class: 'account', click: this.logout.bind(this)}).add(this.header) } else { this.account = new Element('div', 'Login &nbsp; <i class="fa-solid fa-circle-user fa-xl"></i>', {class: 'account', click: this.navigate.bind(this, '/login')}).add(this.header) } } clear() { } }
package hello.proxy.jdkdynamic; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @Slf4j public class ReflectionTest { @Test void reflection0() { Hello target = new Hello(); //공통 로직1 시작 log.info("start"); String result1 = target.callA(); log.info("result={}", result1); //공통 로직1 종료 //공통 로직2 시작 log.info("start"); String result2 = target.callB(); log.info("result={}", result2); //공통 로직2 종료 //여기서 공통 로직1과 공통 로직2를 하나의 메서드로 뽑아서 합칠 수 있을까??? //메서드로 뽑아서 공통화 하는 건 생각보다 어렵다. - 중간에 호출하는 메서드 자체가 다르기 때문 } //cf. 람다를 사용해서 공통화하는 것도 가능하지만 목적이 리플렉션 학습이므로 생략 @Test void reflection1() throws Exception { //클래스 메타정보 획득 Class classHello = Class.forName("hello.proxy.jdkdynamic.ReflectionTest$Hello"); //Hello 인스턴스(target이 될 것) 만듦 Hello target = new Hello(); //callA 메서드 메타정보 획득 - 메서드 이름 문자열을 통해서 -> 동적으로 바뀔 수 있는 부분 Method methodCallA = classHello.getMethod("callA"); Object result1 = methodCallA.invoke(target); log.info("result1={}", result1); //callB 메서드 메타정보 획득 - 메서드 이름 문자열을 통해서 -> 동적으로 바뀔 수 있는 부분 Method methodCallB = classHello.getMethod("callB"); Object result2 = methodCallB.invoke(target); log.info("result2={}", result2); } //===> 기존 callA(), callB() 메서드를 직접 호출하는 부분이 Method로 대체(추상화) //cf. Method는 java.lang.reflect 패키지의 클래스 @Test void reflection2() throws Exception { //클래스 메타정보 획득 Class classHello = Class.forName("hello.proxy.jdkdynamic.ReflectionTest$Hello"); //Hello 인스턴스(target이 될 것) 만듦 Hello target = new Hello(); //callA 메서드 메타정보 획득 -> dynamicCall(~)로 넘김 Method methodCallA = classHello.getMethod("callA"); dynamicCall(methodCallA, target); //callB 메서드 메타정보 획득 -> dynamicCall(~)로 넘김 Method methodCallB = classHello.getMethod("callB"); dynamicCall(methodCallB, target); } private void dynamicCall(Method method, Object target) throws Exception { /* // reflection0()에서 target.callA() 부분 공통화가 안 되던 것을 해결 log.info("start"); String result1 = target.callA(); log.info("result={}", result1); */ log.info("start"); Object result = method.invoke(target); log.info("result={}", result); } @Slf4j static class Hello { public String callA() { log.info("callA"); return "A"; } public String callB() { log.info("callB"); return "B"; } } }
(() => { const login = (data: { email: string; password: string }) => { const { email, password } = data; console.log(email, password); }; login({ email: '[email protected]', password: '12345678**' }); type Sizes = 'S' | 'M' | 'L' | 'XL'; //Product is now a type type Product = { title: string; createdAt: Date; stock: number; size?: Sizes; }; //Can do the same with an interface interface Prod { title: string; createdAt: Date; stock: number; size?: Sizes; } const products: Product[] = []; const addProduct = (data: Product) => { products.push(data); }; addProduct({ title: 'p1', createdAt: new Date(2022, 1, 1), stock: 55, }); addProduct({ title: 'p2', createdAt: new Date(2020, 8, 1), stock: 15, }); addProduct({ title: 'p3', createdAt: new Date(20218, 10, 15), stock: 78, }); console.log(products); })();
import React, { useCallback, useMemo, useRef } from 'react' import makeSvgPath from '../../utils/makeSvgPath' import { ICoordinateType, ILinkType } from '../../types' import { isEqual } from 'lodash-es' import { computedLinkSvgInfo } from '../../utils' interface LinkProps { input: ICoordinateType output: ICoordinateType link: ILinkType onDelete: (link: ILinkType) => void } export const Link: React.FC<LinkProps> = React.memo( (props) => { const { input, output, link, onDelete } = props const svgRef = useRef<SVGSVGElement>(null) /* * 画出 link 的 svg 矩形容器,和位置,并且重新计算在 矩形容器内的起点和终点 * */ const { width, height, left, top, start, end } = useMemo(() => computedLinkSvgInfo(input, output), [input, output]) /* * 根据两点坐标生成 svg path 路径 * */ const path = useMemo(() => makeSvgPath(start as ICoordinateType, end as ICoordinateType), [start, end]) const handleDelete = useCallback(() => { onDelete(link) }, [onDelete, link]) const handleMouseOver = useCallback(() => { svgRef.current?.classList.add('hover') }, []) const handleMouseOut = useCallback(() => { svgRef.current?.classList.remove('hover') }, []) return ( <svg ref={svgRef} className={'diagram-link'} style={{ left, top }} width={width} height={height} pointerEvents="none" > <path d={path} className="bi-link-path" /> <path d={path} className="bi-link-ghost" onDoubleClick={handleDelete} onMouseOver={handleMouseOver} onMouseOut={handleMouseOut} /> </svg> ) }, (prev, next) => { /* * memo 默认是浅比较 只比较 props 第一层 * 由于 props 上面 的 input output 等属性在外层每次会重新创建 导致浅层 比较地址 永远等于 false ,使得组件每次都会render 导致memo无效 * 所以使用 isEqual 进行值的比较 进行优化 */ return isEqual(prev, next) } ) Link.displayName = 'Link'
import React from "react"; import { useRef } from "react"; const UserDetails = (props) => { const { pic, setPic, profilePic, uploadPic, password, setPassword, confirmPassword, setConfirmPassword, userData, setUserData, handleChange, submitHandler, } = props; const ref = useRef(); // This function will remove the selected image from the input const imageRemove = (e) => { e.preventDefault(); ref.current.value = ""; setUserData({ ...userData, profilePic: "" }); setPic(""); }; console.log(profilePic); return ( <div className="h-[90.8vh] overflow-y-hidden md:h-[89.15vh] grid place-content-center"> <div className="bg-paleturquoise w-[85vw] md:w-[25vw] rounded-lg py-4"> <form onSubmit={submitHandler}> <div className="my-4 flex justify-center space-x-2"> <input required className="font-poppins bg-darkslategray placeholder:font-poppins text-azure focus:ring-azure h-10 w-[39%] rounded-lg px-2 py-1 focus:border-transparent focus:outline-none focus:ring-2" type="text" placeholder="First Name" name="firstname" value={userData.firstname ? userData.firstname : ""} onChange={(e) => handleChange(e)} /> <input required type="text" className="font-poppins bg-darkslategray placeholder:font-poppins text-azure focus:ring-azure h-10 w-[39%] rounded-lg px-2 py-1 focus:border-transparent focus:outline-none focus:ring-2" placeholder="Last Name" name="lastname" value={userData.lastname ? userData.lastname : ""} onChange={(e) => handleChange(e)} /> </div> <div className="mb-4 flex justify-center"> <input required type="text" className="font-poppins bg-darkslategray placeholder:font-poppins text-azure focus:ring-azure h-10 w-4/5 rounded-lg px-2 py-1 focus:border-transparent focus:outline-none focus:ring-2" placeholder="City" name="city" value={userData.city ? userData.city : ""} onChange={(e) => handleChange(e)} /> </div> <div className="mb-4 flex justify-center"> <input required type="text" className="font-poppins bg-darkslategray placeholder:font-poppins text-azure focus:ring-azure h-10 w-4/5 rounded-lg px-2 py-1 focus:border-transparent focus:outline-none focus:ring-2" placeholder="Phone Number" name="phone" value={userData.phone ? userData.phone : ""} onChange={(e) => handleChange(e)} /> </div> <div className="mb-4 flex justify-center"> <input required type="email" className="font-poppins bg-darkslategray placeholder:font-poppins text-azure focus:ring-azure h-10 w-4/5 rounded-lg px-2 py-1 focus:border-transparent focus:outline-none focus:ring-2" placeholder="Email" name="email" value={userData.email ? userData.email : ""} onChange={(e) => handleChange(e)} /> </div> <div className="mb-4 flex justify-center"> <input type="password" className="font-poppins bg-darkslategray placeholder:font-poppins text-azure focus:ring-azure h-10 w-4/5 rounded-lg px-2 py-1 focus:border-transparent focus:outline-none focus:ring-2" placeholder="Password" name="password" value={password} onChange={(e) => setPassword(e.target.value)} /> </div> <div className="mb-4 flex justify-center"> <input type="password" className="font-poppins bg-darkslategray placeholder:font-poppins text-azure focus:ring-azure h-10 w-4/5 rounded-lg px-2 py-1 focus:border-transparent focus:outline-none focus:ring-2" placeholder="Confirm Password" name="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} /> </div> <div> <div className="grid items-center"> <input ref={ref} type="file" accept="image/*" className={`mx-auto w-4/5 ${ pic ? "mb-0" : "mb-10" } font-poppins tracking-tighter`} onChange={(e) => uploadPic(e.target.files[0])} /> </div> {pic && ( <div className="mb-4 flex h-24 items-center justify-end"> <div className={`relative mr-3 h-20 w-1/4 rounded-lg`}> <img src={pic ? pic : ""} className="h-full w-[80%] rounded-md" alt="" /> <button className="text-darkslategray hover:bg-azure hover:text-darkslategray absolute top-1 right-8 rounded-xl bg-white px-0.5 text-xs" onClick={(e) => imageRemove(e)} > X </button> </div> </div> )} </div> <div className="mb-4 grid w-full place-items-center"> <button className={`font-poppins bg-darkslategray text-md text-azure focus:ring-azure rounded-lg px-6 py-2 focus:border-transparent focus:outline-none focus:ring-2`} type="submit" > Save </button> </div> </form> </div> </div> ); }; export default UserDetails;
import { z } from 'zod'; import { UserEntity } from '../entities'; const registerUserDTOValidator = z.object({ email: z.string().email(), password: z.string().min(8), phone: z.string().min(10), }); export default class RegisterUserDTO { private constructor( public email: string, public password: string, public phone: string, ) {} static create(data: { [key in keyof UserEntity]: unknown }): [ Error?, RegisterUserDTO?, ] { const result = registerUserDTOValidator.safeParse(data); if (!result.success) return [result.error, undefined]; return [ undefined, new RegisterUserDTO( data.email as string, data.password as string, data.phone as string, ), ]; } }
<!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Form Bindings</title> </head> <body> <div id="app"> <!-- <input :value="text" @input="onInput" placeholder="값을 입력하세요"> --> <input v-model="text" placeholder="값을 입력하세요"> <span>{{text}}</span> <input type="checkbox" id="checkbox" v-model="checked" /> <label for="checkbox">{{ checked }}</label> </div> <script type="module"> import { createApp, ref } from '../js/vue.esm-browser.js' createApp({ setup() { const checked = ref(false) const text = ref('sample') return { text, checked } } }).mount('#app') </script> </body> </html>
<template> <fragment> <b-sidebar :fullheight="fullheight" :overlay="overlay" :open.sync="open"> <div class="p-1"> <img src="https://raw.githubusercontent.com/buefy/buefy/dev/static/img/buefy-logo.png" alt="Lightweight UI components for Vue.js based on Bulma" /> <b-menu> <b-menu-list> <b-menu-item label="Home" icon="home" @click="goTo('/')" :active="isActiveMenu('/')" ></b-menu-item> <b-menu-item label="About" icon="link" @click="goTo('/about')" :active="isActiveMenu('/about')" ></b-menu-item> </b-menu-list> </b-menu> </div> </b-sidebar> <b-button @click="open = true" icon-right="menu" /> </fragment> </template> <script lang="ts"> import { Component, Vue } from 'vue-property-decorator'; @Component export default class SideBar extends Vue { public open = false; public overlay = true; public fullheight = true; isActiveMenu(url: string) { const sameAsCurrent = this.$router.currentRoute.path === url; return sameAsCurrent; } goTo(url: string): void { const sameAsCurrent = this.$router.currentRoute.path === url; if (!sameAsCurrent) this.$router.push(url); this.toggleSidebar(); } toggleSidebar(): void { this.open = !open; } } </script> <style lang="scss" scoped> .p-1 { padding: 1em; } button { border: 0; background: none; position: fixed; margin: 16px; color: #fff; } </style>
part of bakecode.engine; class Ecosystem { Map map; final File source; Ecosystem({required this.source, required this.map}); static const jsonEncoder = JsonEncoder.withIndent(' '); static Map _convertAddressToMap(Iterable<String> levels, String uuid) { final map = {}; if (levels.length > 1) { map[levels.first] = _convertAddressToMap(levels.skip(1), uuid); } else if (levels.length == 1) { map[levels.single] = uuid; } return map; } Future<void> addService(Address address, String uuid) async { map = mergeMap([map, _convertAddressToMap(address.levels, uuid)]); await saveToFile(); } static Future<Ecosystem> loadFromFile( [String source = 'config/ecosystem.json']) async { final file = File(source); if (!await file.exists()) { stdout.write(""" Ecosystem configuration does not exist at `$source`. Do you wish to write an example ecosystem? [Y/n] """); var input = stdin.readLineSync()?.substring(0, 1).toLowerCase() ?? ''; if (input == 'y') { await file .writeAsString(jsonEncoder.convert(Ecosystem.exampleEcosystem())); } else { exit(0); } } final json = jsonDecode(await file.readAsString()); if (json is! Map) { throw FormatException('Invalid format.', json); } return Ecosystem(map: json, source: File(source)); } Future<File> saveToFile([File? file]) => (file ?? source).writeAsString(jsonEncoder.convert(this)); Map toJson() => map; factory Ecosystem.exampleEcosystem() { return Ecosystem( source: File('config/ecosystem.json'), map: { "bakecode": { "kitchen": { "storage": { "icy-resurrection": {}, } }, "dine-in": { "family-dine-in": {}, "open-dine-in": {}, }, "dine-out": {}, } }, ); } @override String toString() => jsonEncode(this); }
/* * LearnVulkan Examples * * This is the header file of engine class. * * Copyright (C) by engineer1109 - https://github.com/engineer1109/LearnVulkan * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #ifndef BASEPROJECT_H #define BASEPROJECT_H #include "vulkan_basicengine.h" /** * @brief BaseProject is the main engine class which inherits from the parent class VulkanBasicEngine.\n */ class BaseProject : public VulkanBasicEngine { // VulkanBasicEngine is the parent class. public: /** * @brief Construtor. * @param[in] debug Display debug layer info */ BaseProject(bool debug = false); ~BaseProject(); /** * @brief Virtual function for your prepare render. */ virtual void prepare(); /** * @brief Renderloop function. Every time you render a frame, this function executes once. */ virtual void render(); /** * @brief Draw rendering image to display devices. It should be executed in the 'render()'. */ virtual void draw(); /** * @brief Design IMGUI. */ virtual void OnUpdateUIOverlay(vks::UIOverlay *overlay); /** * @brief Set Vulkan other features. */ virtual void getEnabledFeatures(); private: /** * @brief Your objects can be contructed and prepared here. */ void createObjects(); /** * @brief setupDescriptorPool for vulkan */ void setupDescriptorPool(); /** * @brief setupDescriptorSetLayout for vulkan */ void setupDescriptorSetLayout(); /** * @brief setupDescriptorSet for vulkan */ void setupDescriptorSet(); /** * @brief main class pipeline */ void preparePipelines(); /** * @brief main class command buffers. */ void buildCommandBuffers(); private: // You can define your object class here. Like cube, sphere, and so on. }; #endif
import http from 'http'; import Koa from 'koa'; import WebSocket from 'ws'; import Router from 'koa-router'; import bodyParser from "koa-bodyparser"; import jwt from 'koa-jwt'; import cors from '@koa/cors'; import { jwtConfig, timingLogger, exceptionHandler } from './utils.js'; import { initWss } from './wss.js'; import { offerRouter } from './offer.js'; import { authRouter } from './auth.js'; const app = new Koa(); const server = http.createServer(app.callback()); const wss = new WebSocket.Server({ server }); initWss(wss); app.use(cors()); app.use(timingLogger); app.use(exceptionHandler); app.use(bodyParser()); const prefix = '/api'; // public const publicApiRouter = new Router({ prefix }); publicApiRouter .use('/auth', authRouter.routes()); app .use(publicApiRouter.routes()) .use(publicApiRouter.allowedMethods()); app.use(jwt(jwtConfig)); // protected const protectedApiRouter = new Router({ prefix }); protectedApiRouter .use('/offers', offerRouter.routes()); app .use(protectedApiRouter.routes()) .use(protectedApiRouter.allowedMethods()); server.listen(3000); console.log('started on port 3000'); // // // // // app.use(async (ctx, next) => { // const start = new Date(); // await next(); // const ms = new Date() - start; // console.log(`${ctx.method} ${ctx.url} ${ctx.response.status} - ${ms}ms`); // }); // // app.use(async (ctx, next) => { // await new Promise(resolve => setTimeout(resolve, 2000)); // await next(); // }); // // app.use(async (ctx, next) => { // try { // await next(); // } catch (err) { // ctx.response.body = { issue: [{ error: err.message || 'Unexpected error' }] }; // ctx.response.status = 500; // } // }); // // class CarOffer { // constructor({ id, make, model, year, description, date, isAvailable }) { // this.id = id; // this.make = make; // this.model = model; // this.year = year; // this.description = description; // this.date = date; // this.isAvailable = isAvailable; // } // } // // const offers = []; // for (let i = 0; i < 3; i++) { // offers.push(new CarOffer({ // id: `${i}`, // model: `model ${i}`, // make: `make ${i}`, // year: 2023, // description: `description: #${i}`, // date: new Date(Date.now() + i), // isAvailable: true, // })); // } // let lastId = offers[offers.length - 1].id; // const pageSize = 10; // // const broadcast = data => // wss.clients.forEach(client => { // if (client.readyState === WebSocket.OPEN) { // client.send(JSON.stringify(data)); // } // }); // // const router = new Router(); // // router.get('/offers', ctx => { // ctx.response.body = offers; // ctx.response.status = 200; // }); // // router.get('/offers/:id', async (ctx) => { // const offerId = ctx.request.params.id; // const offer = offers.find(offer => offerId === offer.id); // if (offer) { // ctx.response.body = offer; // ctx.response.status = 200; // ok // } else { // ctx.response.body = { message: `Offer with id ${offerId} not found` }; // ctx.response.status = 404; // NOT FOUND (if you know the resource was deleted, then return 410 GONE) // } // }); // // const createOffer = async (ctx) => { // const offer = ctx.request.body; // console.log(offer) // if (!offer.make || !offer.model || !offer.year || !offer.description) { // validation // ctx.response.body = { message: 'Text is missing' }; // ctx.response.status = 400; // BAD REQUEST // return; // } // lastId = `${parseInt(lastId) + 1}`; // offer.id = `${lastId}`; // offer.date = new Date(Date.now()); // console.log(offer); // offers.push(offer); // ctx.response.body = offer; // ctx.response.status = 201; // CREATED // broadcast({ event: 'created', payload: { offer: offer } }); // }; // // router.post('/offers', async (ctx) => { // await createOffer(ctx); // }); // // router.put('/offers/:id', async (ctx) => { // const id = ctx.params.id; // const offer = ctx.request.body; // const itemId = offer.id; // if (itemId && id !== offer.id) { // ctx.response.body = { message: `Param id and body id should be the same` }; // ctx.response.status = 400; // BAD REQUEST // return; // } // if (!offer.make || !offer.model || !offer.year || !offer.description) { // validation // ctx.response.body = { message: 'Text is missing' }; // ctx.response.status = 400; // BAD REQUEST // return; // } // if (!itemId) { // await createOffer(ctx); // return; // } // const index = offers.findIndex(item => item.id === id); // if (index === -1) { // ctx.response.body = { issue: [{ error: `item with id ${id} not found` }] }; // ctx.response.status = 400; // BAD REQUEST // return; // } // offers[index] = offer; // ctx.response.body = offer; // ctx.response.status = 200; // OK // console.log(offer) // broadcast({ event: 'updated', payload: { offer: offer } }); // }); // // router.del('/offers/:id', ctx => { // const id = ctx.params.id; // const index = offers.findIndex(item => id === item.id); // if (index !== -1) { // const item = offers[index]; // offers.splice(index, 1); // lastUpdated = new Date(); // broadcast({ event: 'deleted', payload: { offer:item } }); // } // ctx.response.status = 204; // no content // }); // // // setInterval(() => { // // lastUpdated = new Date(); // // lastId = `${parseInt(lastId) + 1}`; // // const item = new CarOffer({ id: lastId, text: `item ${lastId}`, date: lastUpdated, version: 1 }); // // offers.push(item); // // console.log(`New item: ${item.text}`); // // broadcast({ event: 'created', payload: { item } }); // // }, 5000); // // app.use(router.routes()); // app.use(router.allowedMethods()); // // server.listen(3000);
# Import Libraries import pandas as pd import numpy as np import nltk import cleantext # Preprocessing from sklearn.feature_extraction.text import TfidfVectorizer from nltk.tokenize import word_tokenize # Similarities & Distances from sklearn.metrics import pairwise from nltk.tokenize import word_tokenize from nltk.probability import FreqDist # Import raw data with postings file = "./postings-clean.csv.zip" raw_data = pd.read_csv(file, index_col='id',) try: raw_data.drop(columns=['Unnamed: 0'], inplace=True) except: pass # Create a list of job descriptions corpus = raw_data['pos_docs'].tolist() # Create TfidfVectorizer object tfidf = TfidfVectorizer() # Compute a sparse matrix of word vectors for all job descriptions tfidf_matrix = tfidf.fit_transform(corpus) # Compute cosine scores def ranking(tfidf_matrix, new_query_vector): cosine_sim = pairwise.cosine_similarity(tfidf_matrix, new_query_vector) cosine_sim_df = pd.DataFrame(cosine_sim, columns = ['cosine_similarity_score'], index = raw_data.index) cosine_sim_df = cosine_sim_df.sort_values(by = ['cosine_similarity_score'], ascending=False) output = raw_data.loc[cosine_sim_df.index,:] return output # Create Display Cards def create_cards(recommendations:pd.DataFrame): rec_columns = ['job_title', 'city', 'state'] output = {} for index in range(len(recommendations)): insights = [] # Return information about recommended job for column in rec_columns: # if there is no information go to the next columns if pd.isnull(recommendations[column].iloc[index]) == True: continue # else add information to the list else: insights.append(recommendations[column].iloc[index]) # Generate Link to LinkedIn base_url = "https://www.linkedin.com/jobs/search/?" keywords = f"keywords={recommendations['job_title'][index].replace(' ','%20')}" # If there is a city and state given if pd.isnull(recommendations['city'][index]) == False and pd.isnull(recommendations['state'][index]) == False: location = f"location={recommendations['city'][index].replace(' ', '%20')}" insights.append(base_url + keywords + '&' + location) else: insights.append(base_url + keywords) output[index] = insights return output # Format Display Cards def display_cards(job_cards): displays = [] for card in job_cards.values(): try: insights = [] for insight in card: display_insight = '' for word in insight.split(' '): display_insight += word[0].upper() + word[1:] + ' ' insights.append(display_insight) displays.append(insights) except: continue return displays
package com.liulishuo.filedownloader.download; import android.database.sqlite.SQLiteFullException; import android.os.Build; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.os.SystemClock; import android.support.v4.media.session.PlaybackStateCompat; import com.liulishuo.filedownloader.database.FileDownloadDatabase; import com.liulishuo.filedownloader.exception.FileDownloadGiveUpRetryException; import com.liulishuo.filedownloader.exception.FileDownloadOutOfSpaceException; import com.liulishuo.filedownloader.message.MessageSnapshotFlow; import com.liulishuo.filedownloader.message.MessageSnapshotTaker; import com.liulishuo.filedownloader.model.FileDownloadModel; import com.liulishuo.filedownloader.services.FileDownloadBroadcastHandler; import com.liulishuo.filedownloader.util.FileDownloadLog; import com.liulishuo.filedownloader.util.FileDownloadProperties; import com.liulishuo.filedownloader.util.FileDownloadUtils; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.LockSupport; /* loaded from: classes.dex */ public class DownloadStatusCallback implements Handler.Callback { private static final String ALREADY_DEAD_MESSAGE = "require callback %d but the host thread of the flow has already dead, what is occurred because of there are several reason can final this flow on different thread."; private static final int CALLBACK_SAFE_MIN_INTERVAL_BYTES = 1; private static final int CALLBACK_SAFE_MIN_INTERVAL_MILLIS = 5; private static final int NO_ANY_PROGRESS_CALLBACK = -1; private long callbackMinIntervalBytes; private final int callbackProgressMaxCount; private final int callbackProgressMinInterval; private Handler handler; private HandlerThread handlerThread; private final int maxRetryTimes; private final FileDownloadModel model; private volatile Thread parkThread; private final ProcessParams processParams; private volatile boolean handlingMessage = false; private volatile long lastCallbackTimestamp = 0; private final AtomicLong callbackIncreaseBuffer = new AtomicLong(); private final AtomicBoolean needCallbackProgressToUser = new AtomicBoolean(false); private final AtomicBoolean needSetProcess = new AtomicBoolean(false); private final AtomicBoolean isFirstCallback = new AtomicBoolean(true); private final FileDownloadDatabase database = CustomComponentHolder.getImpl().getDatabaseInstance(); /* JADX INFO: Access modifiers changed from: package-private */ public DownloadStatusCallback(FileDownloadModel fileDownloadModel, int i, int i2, int i3) { this.model = fileDownloadModel; this.callbackProgressMinInterval = i2 >= 5 ? i2 : 5; this.callbackProgressMaxCount = i3; this.processParams = new ProcessParams(); this.maxRetryTimes = i; } public boolean isAlive() { return this.handlerThread != null && this.handlerThread.isAlive(); } /* JADX INFO: Access modifiers changed from: package-private */ public void discardAllMessage() { if (this.handler != null) { this.handler.removeCallbacksAndMessages(null); this.handlerThread.quit(); this.parkThread = Thread.currentThread(); while (this.handlingMessage) { LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100L)); } this.parkThread = null; } } public void onPending() { this.model.setStatus((byte) 1); this.database.updatePending(this.model.getId()); onStatusChanged((byte) 1); } /* JADX INFO: Access modifiers changed from: package-private */ public void onStartThread() { this.model.setStatus((byte) 6); onStatusChanged((byte) 6); this.database.onTaskStart(this.model.getId()); } /* JADX INFO: Access modifiers changed from: package-private */ public void onConnected(boolean z, long j, String str, String str2) throws IllegalArgumentException { String eTag = this.model.getETag(); if (eTag != null && !eTag.equals(str)) { throw new IllegalArgumentException(FileDownloadUtils.formatString("callback onConnected must with precondition succeed, but the etag is changes(%s != %s)", str, eTag)); } this.processParams.setResuming(z); this.model.setStatus((byte) 2); this.model.setTotal(j); this.model.setETag(str); this.model.setFilename(str2); this.database.updateConnected(this.model.getId(), j, str, str2); onStatusChanged((byte) 2); this.callbackMinIntervalBytes = calculateCallbackMinIntervalBytes(j, this.callbackProgressMaxCount); this.needSetProcess.compareAndSet(false, true); } /* JADX INFO: Access modifiers changed from: package-private */ public void onMultiConnection() { this.handlerThread = new HandlerThread("source-status-callback"); this.handlerThread.start(); this.handler = new Handler(this.handlerThread.getLooper(), this); } /* JADX INFO: Access modifiers changed from: package-private */ public void onProgress(long j) { this.callbackIncreaseBuffer.addAndGet(j); this.model.increaseSoFar(j); inspectNeedCallbackToUser(SystemClock.elapsedRealtime()); if (this.handler == null) { handleProgress(); } else if (this.needCallbackProgressToUser.get()) { sendMessage(this.handler.obtainMessage(3)); } } /* JADX INFO: Access modifiers changed from: package-private */ public void onRetry(Exception exc, int i) { this.callbackIncreaseBuffer.set(0L); if (this.handler == null) { handleRetry(exc, i); } else { sendMessage(this.handler.obtainMessage(5, i, 0, exc)); } } /* JADX INFO: Access modifiers changed from: package-private */ public void onPausedDirectly() { handlePaused(); } /* JADX INFO: Access modifiers changed from: package-private */ public void onErrorDirectly(Exception exc) { handleError(exc); } /* JADX INFO: Access modifiers changed from: package-private */ public void onCompletedDirectly() throws IOException { if (interceptBeforeCompleted()) { return; } handleCompleted(); } private synchronized void sendMessage(Message message) { if (!this.handlerThread.isAlive()) { if (FileDownloadLog.NEED_LOG) { FileDownloadLog.d(this, ALREADY_DEAD_MESSAGE, Integer.valueOf(message.what)); } return; } try { this.handler.sendMessage(message); } catch (IllegalStateException e) { if (!this.handlerThread.isAlive()) { if (FileDownloadLog.NEED_LOG) { FileDownloadLog.d(this, ALREADY_DEAD_MESSAGE, Integer.valueOf(message.what)); } } else { throw e; } } } private static long calculateCallbackMinIntervalBytes(long j, long j2) { if (j2 <= 0) { return -1L; } if (j == -1) { return 1L; } long j3 = j / j2; if (j3 <= 0) { return 1L; } return j3; } private Exception exFiltrate(Exception exc) { long length; String tempFilePath = this.model.getTempFilePath(); if ((this.model.isChunked() || FileDownloadProperties.getImpl().fileNonPreAllocation) && (exc instanceof IOException) && new File(tempFilePath).exists()) { long freeSpaceBytes = FileDownloadUtils.getFreeSpaceBytes(tempFilePath); if (freeSpaceBytes <= PlaybackStateCompat.ACTION_SKIP_TO_QUEUE_ITEM) { File file = new File(tempFilePath); if (!file.exists()) { FileDownloadLog.e(this, exc, "Exception with: free space isn't enough, and the target file not exist.", new Object[0]); length = 0; } else { length = file.length(); } if (Build.VERSION.SDK_INT >= 9) { return new FileDownloadOutOfSpaceException(freeSpaceBytes, PlaybackStateCompat.ACTION_SKIP_TO_QUEUE_ITEM, length, exc); } return new FileDownloadOutOfSpaceException(freeSpaceBytes, PlaybackStateCompat.ACTION_SKIP_TO_QUEUE_ITEM, length); } return exc; } return exc; } private void handleSQLiteFullException(SQLiteFullException sQLiteFullException) { int id = this.model.getId(); if (FileDownloadLog.NEED_LOG) { FileDownloadLog.d(this, "the data of the task[%d] is dirty, because the SQLite full exception[%s], so remove it from the database directly.", Integer.valueOf(id), sQLiteFullException.toString()); } this.model.setErrMsg(sQLiteFullException.toString()); this.model.setStatus((byte) -1); this.database.remove(id); this.database.removeConnections(id); } private void renameTempFile() throws IOException { boolean z; String tempFilePath = this.model.getTempFilePath(); String targetFilePath = this.model.getTargetFilePath(); File file = new File(tempFilePath); try { File file2 = new File(targetFilePath); if (file2.exists()) { long length = file2.length(); if (!file2.delete()) { throw new IOException(FileDownloadUtils.formatString("Can't delete the old file([%s], [%d]), so can't replace it with the new downloaded one.", targetFilePath, Long.valueOf(length))); } FileDownloadLog.w(this, "The target file([%s], [%d]) will be replaced with the new downloaded file[%d]", targetFilePath, Long.valueOf(length), Long.valueOf(file.length())); } z = !file.renameTo(file2); if (z) { try { throw new IOException(FileDownloadUtils.formatString("Can't rename the temp downloaded file(%s) to the target file(%s)", tempFilePath, targetFilePath)); } catch (Throwable th) { th = th; if (z && file.exists() && !file.delete()) { FileDownloadLog.w(this, "delete the temp file(%s) failed, on completed downloading.", tempFilePath); } throw th; } } else if (z && file.exists() && !file.delete()) { FileDownloadLog.w(this, "delete the temp file(%s) failed, on completed downloading.", tempFilePath); } } catch (Throwable th2) { th = th2; z = true; } } /* JADX WARN: Removed duplicated region for block: B:11:0x0020 A[DONT_GENERATE] */ @Override // android.os.Handler.Callback /* Code decompiled incorrectly, please refer to instructions dump. To view partially-correct add '--show-bad-code' argument */ public boolean handleMessage(android.os.Message r5) { /* r4 = this; r0 = 1 r4.handlingMessage = r0 int r1 = r5.what r2 = 3 r3 = 0 if (r1 == r2) goto L17 r2 = 5 if (r1 == r2) goto Ld goto L1a Ld: java.lang.Object r1 = r5.obj // Catch: java.lang.Throwable -> L26 java.lang.Exception r1 = (java.lang.Exception) r1 // Catch: java.lang.Throwable -> L26 int r5 = r5.arg1 // Catch: java.lang.Throwable -> L26 r4.handleRetry(r1, r5) // Catch: java.lang.Throwable -> L26 goto L1a L17: r4.handleProgress() // Catch: java.lang.Throwable -> L26 L1a: r4.handlingMessage = r3 java.lang.Thread r5 = r4.parkThread if (r5 == 0) goto L25 java.lang.Thread r5 = r4.parkThread java.util.concurrent.locks.LockSupport.unpark(r5) L25: return r0 L26: r5 = move-exception r4.handlingMessage = r3 java.lang.Thread r0 = r4.parkThread if (r0 == 0) goto L32 java.lang.Thread r0 = r4.parkThread java.util.concurrent.locks.LockSupport.unpark(r0) L32: throw r5 */ throw new UnsupportedOperationException("Method not decompiled: com.liulishuo.filedownloader.download.DownloadStatusCallback.handleMessage(android.os.Message):boolean"); } private void handleProgress() { if (this.model.getSoFar() == this.model.getTotal()) { this.database.updateProgress(this.model.getId(), this.model.getSoFar()); return; } if (this.needSetProcess.compareAndSet(true, false)) { if (FileDownloadLog.NEED_LOG) { FileDownloadLog.i(this, "handleProgress update model's status with progress", new Object[0]); } this.model.setStatus((byte) 3); } if (this.needCallbackProgressToUser.compareAndSet(true, false)) { if (FileDownloadLog.NEED_LOG) { FileDownloadLog.i(this, "handleProgress notify user progress status", new Object[0]); } onStatusChanged((byte) 3); } } private void handleCompleted() throws IOException { renameTempFile(); this.model.setStatus((byte) -3); this.database.updateCompleted(this.model.getId(), this.model.getTotal()); this.database.removeConnections(this.model.getId()); onStatusChanged((byte) -3); if (FileDownloadProperties.getImpl().broadcastCompleted) { FileDownloadBroadcastHandler.sendCompletedBroadcast(this.model); } } private boolean interceptBeforeCompleted() { if (this.model.isChunked()) { this.model.setTotal(this.model.getSoFar()); } else if (this.model.getSoFar() != this.model.getTotal()) { onErrorDirectly(new FileDownloadGiveUpRetryException(FileDownloadUtils.formatString("sofar[%d] not equal total[%d]", Long.valueOf(this.model.getSoFar()), Long.valueOf(this.model.getTotal())))); return true; } return false; } private void handleRetry(Exception exc, int i) { Exception exFiltrate = exFiltrate(exc); this.processParams.setException(exFiltrate); this.processParams.setRetryingTimes(this.maxRetryTimes - i); this.model.setStatus((byte) 5); this.model.setErrMsg(exFiltrate.toString()); this.database.updateRetry(this.model.getId(), exFiltrate); onStatusChanged((byte) 5); } private void handlePaused() { this.model.setStatus((byte) -2); this.database.updatePause(this.model.getId(), this.model.getSoFar()); onStatusChanged((byte) -2); } private void handleError(Exception exc) { Exception exFiltrate = exFiltrate(exc); if (exFiltrate instanceof SQLiteFullException) { handleSQLiteFullException((SQLiteFullException) exFiltrate); } else { try { this.model.setStatus((byte) -1); this.model.setErrMsg(exc.toString()); this.database.updateError(this.model.getId(), exFiltrate, this.model.getSoFar()); } catch (SQLiteFullException e) { exFiltrate = e; handleSQLiteFullException((SQLiteFullException) exFiltrate); } } this.processParams.setException(exFiltrate); onStatusChanged((byte) -1); } private void inspectNeedCallbackToUser(long j) { boolean z; if (!this.isFirstCallback.compareAndSet(true, false)) { long j2 = j - this.lastCallbackTimestamp; if (this.callbackMinIntervalBytes == -1 || this.callbackIncreaseBuffer.get() < this.callbackMinIntervalBytes || j2 < this.callbackProgressMinInterval) { z = false; if (z || !this.needCallbackProgressToUser.compareAndSet(false, true)) { } if (FileDownloadLog.NEED_LOG) { FileDownloadLog.i(this, "inspectNeedCallbackToUser need callback to user", new Object[0]); } this.lastCallbackTimestamp = j; this.callbackIncreaseBuffer.set(0L); return; } } z = true; if (z) { } } private void onStatusChanged(byte b) { if (b == -2) { if (FileDownloadLog.NEED_LOG) { FileDownloadLog.d(this, "High concurrent cause, Already paused and we don't need to call-back to Task in here, %d", Integer.valueOf(this.model.getId())); return; } return; } MessageSnapshotFlow.getImpl().inflow(MessageSnapshotTaker.take(b, this.model, this.processParams)); } /* loaded from: classes.dex */ public static class ProcessParams { private Exception exception; private boolean isResuming; private int retryingTimes; void setResuming(boolean z) { this.isResuming = z; } public boolean isResuming() { return this.isResuming; } void setException(Exception exc) { this.exception = exc; } void setRetryingTimes(int i) { this.retryingTimes = i; } public Exception getException() { return this.exception; } public int getRetryingTimes() { return this.retryingTimes; } } }
package com.codepath.apps.restclienttemplate; import android.content.Context; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.codepath.apps.restclienttemplate.models.Tweet; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.List; import java.util.Locale; public class TweetsAdapter extends RecyclerView.Adapter<TweetsAdapter.ViewHolder> { Context context; List<Tweet> tweets; // Pass in the context and list of tweets public TweetsAdapter(Context context, List<Tweet> tweets) { this.context = context; this.tweets = tweets; } // For each row, inflate a layout @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item_tweet, parent, false); return new ViewHolder(view); } // Bind values based on the position of the element @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { // Get the data at position Tweet tweet = tweets.get(position); // Bind the tweet with view holder holder.bind(tweet); } @Override public int getItemCount() { return tweets.size(); } // Define a viewholder public class ViewHolder extends RecyclerView.ViewHolder { ImageView ivProfileImage; TextView tvBody; TextView tvScreenName; // for tweets images ImageView ivImage; TextView timestamp; public ViewHolder(@NonNull View itemView) { super(itemView); ivProfileImage = itemView.findViewById(R.id.ivProfileImage); tvBody = itemView.findViewById(R.id.tvBody); tvScreenName = itemView.findViewById(R.id.tvScreenName); // for tweets image ivImage = itemView.findViewById(R.id.ivImage); // for timestamp timestamp = itemView.findViewById(R.id.timestamp); } public void bind(Tweet tweet) { tvBody.setText(tweet.body); tvScreenName.setText(tweet.user.screenName); Glide.with(context).load(tweet.user.profileImageUrl).into(ivProfileImage); if(tweet.img != "none") { Glide.with(context).load(tweet.img).into(ivImage); } else { ivImage.setVisibility(View.GONE); } timestamp.setText(getRelativeTimeAgo(tweet.createdAt)); } } private static final int SECOND_MILLIS = 1000; private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS; private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS; private static final int DAY_MILLIS = 24 * HOUR_MILLIS; public String getRelativeTimeAgo(String rawJsonDate) { String twitterFormat = "EEE MMM dd HH:mm:ss ZZZZZ yyyy"; SimpleDateFormat sf = new SimpleDateFormat(twitterFormat, Locale.ENGLISH); sf.setLenient(true); try { long time = sf.parse(rawJsonDate).getTime(); long now = System.currentTimeMillis(); final long diff = now - time; if (diff < MINUTE_MILLIS) { return "just now"; } else if (diff < 2 * MINUTE_MILLIS) { return "a minute ago"; } else if (diff < 50 * MINUTE_MILLIS) { return diff / MINUTE_MILLIS + " m"; } else if (diff < 90 * MINUTE_MILLIS) { return "an hour ago"; } else if (diff < 24 * HOUR_MILLIS) { return diff / HOUR_MILLIS + " h"; } else if (diff < 48 * HOUR_MILLIS) { return "yesterday"; } else { return diff / DAY_MILLIS + " d"; } } catch (ParseException e) { e.printStackTrace(); } return ""; } // Clean all elements of the recycler public void clear() { tweets.clear(); notifyDataSetChanged(); } // Add a list of items -- change to type used public void addAll(List<Tweet> list) { tweets.addAll(list); notifyDataSetChanged(); } }
/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */ /* Document /** * 1. Correct the line height in all browsers. * 2. Prevent adjustments of font size after orientation changes in iOS. */ html { line-height: 1.15; /* 1 */ -webkit-text-size-adjust: 100%; /* 2 */ } /* Sections /** * Remove the margin in all browsers. */ body { margin: 0; } /** * Render the `main` element consistently in IE. */ main { display: block; } /** * Correct the font size and margin on `h1` elements within `section` and * `article` contexts in Chrome, Firefox, and Safari. */ h1 { font-size: 2em; margin: 0.67em 0; } /* Grouping content /** * 1. Add the correct box sizing in Firefox. * 2. Show the overflow in Edge and IE. */ hr { box-sizing: content-box; /* 1 */ height: 0; /* 1 */ overflow: visible; /* 2 */ } /** * 1. Correct the inheritance and scaling of font size in all browsers. * 2. Correct the odd `em` font sizing in all browsers. */ pre { font-family: monospace, monospace; /* 1 */ font-size: 1em; /* 2 */ } /* Text-level semantics /** * Remove the gray background on active links in IE 10. */ a { background-color: transparent; } /** * 1. Remove the bottom border in Chrome 57- * 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari. */ abbr[title] { border-bottom: none; /* 1 */ text-decoration: underline; /* 2 */ text-decoration: underline dotted; /* 2 */ } /** * Add the correct font weight in Chrome, Edge, and Safari. */ b, strong { font-weight: bolder; } /** * 1. Correct the inheritance and scaling of font size in all browsers. * 2. Correct the odd `em` font sizing in all browsers. */ code, kbd, samp { font-family: monospace, monospace; /* 1 */ font-size: 1em; /* 2 */ } /** * Add the correct font size in all browsers. */ small { font-size: 80%; } /** * Prevent `sub` and `sup` elements from affecting the line height in * all browsers. */ sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } /* Embedded content /** * Remove the border on images inside links in IE 10. */ img { border-style: none; } /* Forms /** * 1. Change the font styles in all browsers. * 2. Remove the margin in Firefox and Safari. */ button, input, optgroup, select, textarea { font-family: inherit; /* 1 */ font-size: 100%; /* 1 */ line-height: 1.15; /* 1 */ margin: 0; /* 2 */ } /** * Show the overflow in IE. * 1. Show the overflow in Edge. */ button, input { /* 1 */ overflow: visible; } /** * Remove the inheritance of text transform in Edge, Firefox, and IE. * 1. Remove the inheritance of text transform in Firefox. */ button, select { /* 1 */ text-transform: none; } /** * Correct the inability to style clickable types in iOS and Safari. */ button, [type=button], [type=reset], [type=submit] { -webkit-appearance: button; } /** * Remove the inner border and padding in Firefox. */ button::-moz-focus-inner, [type=button]::-moz-focus-inner, [type=reset]::-moz-focus-inner, [type=submit]::-moz-focus-inner { border-style: none; padding: 0; } /** * Restore the focus styles unset by the previous rule. */ button:-moz-focusring, [type=button]:-moz-focusring, [type=reset]:-moz-focusring, [type=submit]:-moz-focusring { outline: 1px dotted ButtonText; } /** * Correct the padding in Firefox. */ fieldset { padding: 0.35em 0.75em 0.625em; } /** * 1. Correct the text wrapping in Edge and IE. * 2. Correct the color inheritance from `fieldset` elements in IE. * 3. Remove the padding so developers are not caught out when they zero out * `fieldset` elements in all browsers. */ legend { box-sizing: border-box; /* 1 */ color: inherit; /* 2 */ display: table; /* 1 */ max-width: 100%; /* 1 */ padding: 0; /* 3 */ white-space: normal; /* 1 */ } /** * Add the correct vertical alignment in Chrome, Firefox, and Opera. */ progress { vertical-align: baseline; } /** * Remove the default vertical scrollbar in IE 10+. */ textarea { overflow: auto; } /** * 1. Add the correct box sizing in IE 10. * 2. Remove the padding in IE 10. */ [type=checkbox], [type=radio] { box-sizing: border-box; /* 1 */ padding: 0; /* 2 */ } /** * Correct the cursor style of increment and decrement buttons in Chrome. */ [type=number]::-webkit-inner-spin-button, [type=number]::-webkit-outer-spin-button { height: auto; } /** * 1. Correct the odd appearance in Chrome and Safari. * 2. Correct the outline style in Safari. */ [type=search] { -webkit-appearance: textfield; /* 1 */ outline-offset: -2px; /* 2 */ } /** * Remove the inner padding in Chrome and Safari on macOS. */ [type=search]::-webkit-search-decoration { -webkit-appearance: none; } /** * 1. Correct the inability to style clickable types in iOS and Safari. * 2. Change font properties to `inherit` in Safari. */ ::-webkit-file-upload-button { -webkit-appearance: button; /* 1 */ font: inherit; /* 2 */ } /* Interactive /* * Add the correct display in Edge, IE 10+, and Firefox. */ details { display: block; } /* * Add the correct display in all browsers. */ summary { display: list-item; } /* Misc /** * Add the correct display in IE 10+. */ template { display: none; } /** * Add the correct display in IE 10. */ [hidden] { display: none; } html, body { margin: 0; padding: 0; border: 0; box-sizing: border-box; } .main__button { border: 2px solid #0c0910; background-color: #ffffff; padding: 1rem 2rem; font-family: "Raleway", sans-serif; color: #0c0910; font-weight: 700; margin-top: 1rem; cursor: pointer; } .form { width: 100%; } .form__label { color: #ffffff; font-size: 14px; font-family: "Old Standard TT", serif; } .form__input { width: 90%; padding: 0.8rem; margin: 0.5rem 0 1rem -0.5rem; font-family: "Raleway", sans-serif; font-size: 12px; } .nav { width: 100%; position: fixed; top: 0; background-color: #ffffff; } .nav__logo { width: 15%; background-color: #0c0910; text-align: center; display: inline-block; padding: 0.7rem; } .nav__text { color: #ffffff; font-size: 18px; font-family: "Old Standard TT", serif; } .nav__list { display: none; text-align: center; list-style: none; margin-left: -40px; } .nav__item { padding-bottom: 1rem; } .nav__item a { text-decoration: none; color: #0c0910; font-family: "Raleway", sans-serif; font-weight: 700; } .nav__line { width: 70%; border: 2px solid #0c0910; margin: 0.2rem 0; border-radius: 5px; width: 10%; } .hamburger-icon { position: relative; float: right; font-size: 30px; padding-top: 7%; padding-right: 1rem; cursor: pointer; } #menu-toggle { display: none; } #menu-toggle:checked + .nav__list { display: block; } @media (min-width: 768px) { .nav__list { display: inline-block; float: right; padding-top: 0.8rem; } .nav__item { display: inline-block; padding-right: 3rem; font-family: "Raleway", sans-serif; font-weight: 700; } .nav__item a { text-decoration: none; color: #0c0910; } .nav__burger { display: none; } .hamburger-icon { display: none; } } @media (min-width: 1280px) { .nav__logo { width: 5%; } .nav__list { padding-top: 0.5rem; } } .container { height: 100vh; } .main { width: 100%; margin-top: 4rem; } .main__img { width: 100%; height: auto; } .main__container-text { padding: 1rem 1.5rem; } .main__title { font-size: 50px; font-weight: 700; margin: 0; color: #0c0910; } .main__text { font-size: 16px; font-family: "Raleway", sans-serif; font-weight: 400; line-height: 1.7rem; color: #646266; } @media (min-width: 768px) { .main { margin-top: 0; padding-bottom: 3rem; } .main__img { height: 40vh; object-fit: cover; margin-top: 4.5rem; } .main__container-text { padding: 1rem 4rem; } .main__title { width: 70%; } .main__text { width: 70%; } } @media (min-width: 1280px) { .main { height: 100vh; padding-bottom: 0; position: absolute; bottom: 0; } .main__img { width: 55%; height: 100vh; position: relative; float: right; z-index: -1; } .main__container-text { padding: 5rem 4rem; } .main__title { width: 30%; padding-top: 4rem; } .main__text { width: 30%; } } @media (min-width: 1400px) { .main { height: 100vh; padding-bottom: 0; position: absolute; bottom: 0; } .main__title { padding-top: 4rem; } } .footer { width: 100%; } .footer__newsletter { background-color: #0c0910; padding: 1rem 1.5rem; display: inline-block; width: 70%; } .footer__title { color: #ffffff; font-family: "Old Standard TT", serif; font-size: 20px; margin-bottom: 0.3rem; } .footer__button { width: 10%; display: inline-block; vertical-align: middle; margin-top: -1.8rem; } .footer__button button { font-family: "Old Standard TT", serif; font-weight: 700; writing-mode: vertical-lr; background-color: #ffffff; border: none; padding: 0.5rem; cursor: pointer; } @media (min-width: 768px) { .footer { position: absolute; bottom: 0; } .footer__newsletter { width: 80%; padding-left: 4rem; } .footer__button { width: 5%; } .footer__button button { padding: 0.8rem; } } @media (min-width: 1280px) { .footer { width: 40%; position: absolute; bottom: -9%; } .footer__newsletter { width: 77%; } .footer__button button { padding: 1.5rem; } } @media (min-width: 1400px) { .footer { position: absolute; bottom: -9%; } } /*# sourceMappingURL=main.css.map */
第一步:建立git仓库 cd到你的本地项目根目录下,执行git命令 git init 第二步:将项目的所有文件添加到仓库中 git add . 如果想添加某个特定的文件,只需把.换成特定的文件名即可 第三步:将add的文件commit到仓库 git commit -m "注释语句" 第四步:去github上创建自己的Repository,创建页面如下图所示: 拿到仓库地址https 出现 第五步:将本地的仓库关联到Github上 git remote add origin https://仓库地址 第六步 上传github之前 要先pull一下 执行如下命令 git pull origin master 第七步,上传代码到github远程仓库 git push -u origin master 注意:若提示:更新被拒绝,因为您当前分支的最新提交落后于其对应的远程分支。 进行如下操作即可: 首先进行: git remote add origin https://github.com/xuyonghui6512/mypro.git $git fetch origin //获取远程更新 $git merge origin/master //把更新的内容合并到本地分支 若上述方法还不行,可进行如下的方法 先备份一个分支 git checkout -b master_bak 删除git branch -D master 重新拉取git fetch origin master:master git checkout master git merge master_bak git push origin master
<?php declare(strict_types=1); namespace Boolfly\ProductQuestion\Model; use Boolfly\ProductQuestion\Api\Data\QuestionInterface; use Magento\Framework\DataObject\IdentityInterface; use Magento\Framework\Model\AbstractModel; class Question extends AbstractModel implements IdentityInterface, QuestionInterface { /**#@+ * Question's statuses */ const STATUS_ENABLED = 1; const STATUS_DISABLED = 0; const TYPE_QUESTION = 0; const TYPE_REPLY = 1; const CACHE_TAG = 'bf_question'; protected $_cacheTag = 'bf_question'; protected $_eventObject = 'question'; protected $_eventPrefix = 'bf_question'; protected function _construct() { $this->_init('Boolfly\ProductQuestion\Model\ResourceModel\Question'); } /** * Return unique ID(s) for each object in system * * @return string[] */ public function getIdentities() { return [self::CACHE_TAG . '_' . $this->getId()]; } /** * Get ID * * @return int|null */ public function getId() { return $this->getData(self::QUESTION_ID); } /** * Get Title * * @return string|null */ public function getTitle() { return $this->getData(self::TITLE); } /** * @return string */ public function getContent() { return $this->getData(self::CONTENT); } /** * Get Author Email * * @return string|null */ public function getAuthorEmail() { return $this->getData(self::AUTHOR_EMAIL); } /** * Get Author Name * * @return string|null */ public function getAuthorName() { return $this->getData(self::AUTHOR_NAME); } /** * Get Creation Time * * @return string|null */ public function getCreationTime() { return $this->getData(self::CREATION_TIME); } /** * Get Update Time * * @return string|null */ public function getUpdateTime() { return $this->getData(self::UPDATE_TIME); } /** * Check Is Active * * @return int|null */ public function getIsActive() { return $this->getData(self::IS_ACTIVE); } /** * Set Title * * @param string $title * @return $this */ public function setTitle($title) { return $this->setData(self::TITLE, $title); } /** * @inheritDoc */ public function setContent($content) { return $this->setData(self::CONTENT, $content); } /** * Set Author Email * * @param string $email * @return $this */ public function setAuthorEmail($email) { return $this->setData(self::AUTHOR_EMAIL, $email); } /** * Set Author Name * * @param string $name * @return $this */ public function setAuthorName($name) { return $this->setData(self::AUTHOR_NAME, $name); } /** * Set Creation Time * * @param string $creationTime * @return $this */ public function setCreationTime($creationTime) { return $this->setData(self::CREATION_TIME, $creationTime); } /** * Set Update Time * * @param string $updateTime * @return $this */ public function setUpdateTime($updateTime) { return $this->setData(self::UPDATE_TIME, $updateTime); } /** * Set Is Active * * @param int $isActive * @return $this */ public function setIsActive($isActive) { return $this->setData(self::IS_ACTIVE, $isActive); } /** * Set ID * * @param int $id * @return $this */ public function setId($id) { return $this->setData(self::QUESTION_ID, $id); } /** * Check Type * * @return int|null */ public function getType() { return $this->getData(self::TYPE); } /** * Check If have parent_id * * @return int|null */ public function getParentId() { return $this->getData(self::PARENT_ID); } /** * Set Type * * @param int $type * @return $this */ public function setType($type) { return $this->setData(self::TYPE, $type); } /** * Set Parent ID * * @param int $parentId * @return $this */ public function setParentId($parentId) { return $this->setData(self::PARENT_ID, $parentId); } /** * @param $data * @return $this */ public function prepareRepliesData($data) { $listReplies = []; if (isset($data['list_replies']) && is_array($data['list_replies'])) { foreach ($data['list_replies'] as $value) { if ($value['content']) { unset($value['record_id']); unset($value['initialize']); array_push($listReplies, $value); } } } $this->setData('replies', $listReplies); return $this; } /** * Get Product ID * * @return int|null */ public function getProductId() { return $this->getData(self::PRODUCT_ID); } /** * Set Product ID * * @param int $productId * @return $this */ public function setProductId($productId) { return $this->setData(self::PRODUCT_ID, $productId); } /** * Get short content * * @return string */ public function getShortContent() { $content = $this->getContent(); return (strlen($content) > 30) ? substr($content, 0, strpos($content, ' ', 30)).'...' : $content; } }
import { APP_ROUTES } from "@/lib/constants"; import { useCommitMedia, useCoreDetails, useUser } from "@/lib/hooks/graphql"; import { gqlClient } from "@/lib/services/api"; import { Verb, getLot, getVerb } from "@/lib/utilities"; import { ActionIcon, Anchor, Avatar, Box, Button, Collapse, Flex, Image, Loader, ScrollArea, Text, Tooltip, } from "@mantine/core"; import { useDisclosure } from "@mantine/hooks"; import { notifications } from "@mantine/notifications"; import { AddMediaToCollectionDocument, type AddMediaToCollectionMutationVariables, type MediaSearchQuery, MetadataLot, MetadataSource, type ReviewItem, } from "@ryot/generated/graphql/backend/graphql"; import { changeCase, getInitials } from "@ryot/utilities"; import { IconEdit, IconStarFilled } from "@tabler/icons-react"; import { useMutation } from "@tanstack/react-query"; import { DateTime } from "luxon"; import Link from "next/link"; import { useRouter } from "next/router"; import { withQuery } from "ufo"; export const MediaScrollArea = (props: { children: JSX.Element }) => { const coreDetails = useCoreDetails(); return coreDetails.data ? ( <ScrollArea.Autosize mah={coreDetails.data.itemDetailsHeight}> {props.children} </ScrollArea.Autosize> ) : null; }; export const ReviewItemDisplay = ({ review, metadataId, creatorId, }: { review: ReviewItem; metadataId?: number; creatorId?: number; }) => { const [opened, { toggle }] = useDisclosure(false); const user = useUser(); return ( <Box key={review.id} data-review-id={review.id}> <Flex align={"center"} gap={"sm"}> <Avatar color="cyan" radius="xl"> {getInitials(review.postedBy.name)}{" "} </Avatar> <Box> <Text>{review.postedBy.name}</Text> <Text>{DateTime.fromJSDate(review.postedOn).toLocaleString()}</Text> </Box> {user && user.id === review.postedBy.id ? ( <Link href={withQuery(APP_ROUTES.media.postReview, { metadataId, creatorId, reviewId: review.id, })} passHref legacyBehavior > <Anchor> <ActionIcon> <IconEdit size="1rem" /> </ActionIcon> </Anchor> </Link> ) : null} </Flex> <Box ml={"sm"} mt={"xs"}> {typeof review.showSeason === "number" ? ( <Text color="dimmed"> S{review.showSeason}-E {review.showEpisode} </Text> ) : null} {typeof review.podcastEpisode === "number" ? ( <Text color="dimmed">EP-{review.podcastEpisode}</Text> ) : null} {review.rating > 0 ? ( <Flex align={"center"} gap={4}> <IconStarFilled size={"1rem"} style={{ color: "#EBE600FF" }} /> <Text sx={(theme) => ({ color: theme.colorScheme === "dark" ? "white" : undefined, })} fw="bold" > {review.rating} % </Text> </Flex> ) : null} {review.text ? ( !review.spoiler ? ( <Text dangerouslySetInnerHTML={{ __html: review.text }} /> ) : ( <> {!opened ? ( <Button onClick={toggle} variant={"subtle"} compact> Show spoiler </Button> ) : null} <Collapse in={opened}> <Text dangerouslySetInnerHTML={{ __html: review.text }} /> </Collapse> </> ) ) : null} </Box> </Box> ); }; export const BaseDisplayItem = (props: { name: string; imageLink?: string | null; imagePlaceholder: string; topRight?: JSX.Element; topLeft?: JSX.Element; bottomLeft?: string | number | null; bottomRight?: string | number | null; href: string; highlightRightText?: string; children?: JSX.Element; }) => { return ( <Flex key={`${props.bottomLeft}-${props.bottomRight}-${props.name}`} align="center" justify={"center"} direction={"column"} pos={"relative"} > {props.topLeft} <Link passHref legacyBehavior href={props.href}> <Anchor style={{ flex: "none" }} pos="relative"> <Image imageProps={{ loading: "lazy" }} src={props.imageLink} radius={"md"} height={250} width={167} withPlaceholder placeholder={<Text size={60}>{props.imagePlaceholder}</Text>} style={{ cursor: "pointer" }} alt={`Image for ${props.name}`} sx={(_t) => ({ ":hover": { boxShadow: "0 0 15px black" }, transitionProperty: "transform", transitionTimingFunction: "cubic-bezier(0.4, 0, 0.2, 1)", transitionDuration: "150ms", })} /> {props.topRight} </Anchor> </Link> <Flex w={"100%"} direction={"column"}> <Flex justify={"space-between"} direction={"row"} w="100%"> <Text c="dimmed">{props.bottomLeft}</Text> <Tooltip label={props.highlightRightText} disabled={props.highlightRightText ? false : true} position="right" > <Text c={props.highlightRightText ? "yellow" : "dimmed"}> {props.bottomRight} </Text> </Tooltip> </Flex> <Tooltip label={props.name} position="right"> <Text w="100%" truncate fw={"bold"} mb="xs"> {props.name} </Text> </Tooltip> {props.children} </Flex> </Flex> ); }; type Item = MediaSearchQuery["mediaSearch"]["items"][number]["item"]; export const MediaItemWithoutUpdateModal = (props: { item: Item; lot: MetadataLot; children?: JSX.Element; imageOverlayForLoadingIndicator?: boolean; href: string; existsInDatabase?: boolean; averageRating?: number; }) => { return ( <BaseDisplayItem href={props.href} imageLink={props.item.image} imagePlaceholder={getInitials(props.item?.title || "")} topLeft={ props.imageOverlayForLoadingIndicator ? ( <Loader pos={"absolute"} style={{ zIndex: 999 }} top={10} left={10} color="red" variant="bars" size="sm" /> ) : undefined } topRight={ props.averageRating ? ( <Box p={2} pos={"absolute"} top={5} right={5} style={{ backgroundColor: "rgba(0, 0, 0, 0.75)", borderRadius: 3, }} > <Flex align={"center"} gap={4}> <IconStarFilled size={"0.8rem"} style={{ color: "#EBE600FF" }} /> <Text color="white" size="xs" fw="bold"> {props.averageRating} % </Text> </Flex> </Box> ) : undefined } bottomLeft={props.item.publishYear} bottomRight={changeCase(props.lot || "")} highlightRightText={ props.existsInDatabase ? "This media exists in the database" : undefined } name={props.item.title} children={props.children} /> ); }; export default function (props: { item: Item; idx: number; query: string; offset: number; lot: MetadataLot; source: MetadataSource; searchQueryRefetch: () => void; maybeItemId?: number; }) { const router = useRouter(); const lot = getLot(router.query.lot); const commitMedia = useCommitMedia(lot); const addMediaToCollection = useMutation({ mutationFn: async (variables: AddMediaToCollectionMutationVariables) => { const { addMediaToCollection } = await gqlClient.request( AddMediaToCollectionDocument, variables, ); return addMediaToCollection; }, onSuccess: () => { props.searchQueryRefetch(); notifications.show({ title: "Success", message: "Media added to watchlist successfully", }); }, }); const commitFunction = async () => { const { id } = await commitMedia.mutateAsync({ identifier: props.item.identifier, lot: props.lot, source: props.source, }); props.searchQueryRefetch(); return id; }; return ( <MediaItemWithoutUpdateModal item={props.item} lot={props.lot} imageOverlayForLoadingIndicator={commitMedia.isLoading} href={ props.maybeItemId ? withQuery(APP_ROUTES.media.individualMediaItem.details, { id: props.maybeItemId, }) : withQuery(APP_ROUTES.media.individualMediaItem.commit, { identifier: props.item.identifier, lot: props.lot, source: props.source, }) } existsInDatabase={!!props.maybeItemId} > <> {props.lot !== MetadataLot.Show ? ( <Button variant="outline" w="100%" compact onClick={async () => { const id = await commitFunction(); const nextPath = withQuery(router.pathname, router.query); router.push( withQuery(APP_ROUTES.media.individualMediaItem.updateProgress, { id, next: nextPath, }), ); }} > Mark as {getVerb(Verb.Read, props.lot)} </Button> ) : ( <> <Button variant="outline" w="100%" compact onClick={async () => { const id = await commitFunction(); router.push( withQuery(APP_ROUTES.media.individualMediaItem.details, { id, }), ); }} > Show details </Button> </> )} <Button mt="xs" variant="outline" w="100%" compact onClick={async () => { const id = await commitFunction(); addMediaToCollection.mutate({ input: { collectionName: "Watchlist", mediaId: id }, }); }} disabled={addMediaToCollection.isLoading} > Add to Watchlist </Button> </> </MediaItemWithoutUpdateModal> ); }
+++ title = 'Backend Web Development Curriculum' date = 2024-06-11T13:48:32+07:00 draft = false description = 'A curriculum to learn Backend Web Development from ChatGPT' tags = ['web', 'backend', 'AI generated'] +++ Creating a detailed and comprehensive curriculum for Backend Web Development from scratch involves laying a solid foundation in web concepts, programming, databases, and server-side technologies. Here’s a structured outline for a semester-long course, designed to cover the essentials and progressively build up to more advanced backend development skills. The course is structured to meet once or twice a week for about 12-15 weeks. ### Week 1-2: Introduction to Web Development and Internet Fundamentals - **Lecture Topics:** - Introduction to web development: front-end vs. back-end. - How the internet works: understanding HTTP, DNS, and basic networking. - Overview of web servers and clients. - Introduction to the request-response cycle. - **Practical Sessions:** - Exploring basic web technologies: HTML, CSS, and JavaScript. - Using web browsers and developer tools. - Setting up a local development environment (IDE setup, Git installation). - **Assignments:** - Research and summarize how HTTP works. - Create a basic HTML page and style it with CSS. ### Week 3-4: Introduction to Programming with Python - **Lecture Topics:** - Basics of programming: variables, data types, and operators. - Control flow: if statements, loops. - Functions and modules: defining and using functions, importing modules. - Introduction to object-oriented programming (OOP) concepts. - **Practical Sessions:** - Writing and running simple Python scripts. - Implementing control flow and functions in Python programs. - Using Python libraries and modules for basic tasks. - **Assignments:** - Write a Python script that calculates and prints the Fibonacci sequence up to a given number. - Create a small program that demonstrates the use of functions and loops. ### Week 5-6: Introduction to Databases and SQL - **Lecture Topics:** - Basics of databases: what they are, why they are used. - Introduction to relational databases and SQL. - Basic SQL commands: `CREATE`, `INSERT`, `SELECT`, `UPDATE`, `DELETE`. - Understanding primary keys, foreign keys, and relationships. - **Practical Sessions:** - Setting up a relational database (e.g., SQLite or PostgreSQL). - Writing SQL queries to create tables and manipulate data. - Using SQL to retrieve and filter data from tables. - **Assignments:** - Create a database for a simple application (e.g., a library system) and populate it with sample data. - Write SQL queries to perform various operations on the database. ### Week 7-8: Introduction to Server-Side Development with Flask - **Lecture Topics:** - Introduction to web frameworks and Flask. - Setting up a Flask project and understanding the project structure. - Creating routes and handling requests in Flask. - Rendering templates and using Flask's template engine. - **Practical Sessions:** - Setting up a Flask application. - Creating basic routes and views to handle different URLs. - Using Flask’s templating system to generate dynamic HTML pages. - **Assignments:** - Develop a simple Flask application with multiple routes and templates. - Create a form in Flask and process its data on submission. ### Week 9-10: Connecting to Databases and ORM - **Lecture Topics:** - Integrating Flask with a database. - Introduction to Object-Relational Mapping (ORM) with SQLAlchemy. - Defining and managing models with SQLAlchemy. - Performing CRUD operations using ORM. - **Practical Sessions:** - Connecting a Flask application to a PostgreSQL or SQLite database. - Defining models and relationships using SQLAlchemy. - Implementing CRUD operations in Flask using SQLAlchemy. - **Assignments:** - Extend the Flask application to include database models and perform CRUD operations. - Write Flask routes to interact with the database through SQLAlchemy. ### Week 11-12: Advanced Flask Features and REST APIs - **Lecture Topics:** - Introduction to RESTful APIs and their principles. - Building RESTful endpoints with Flask. - Handling JSON data and using Flask for API development. - Authentication and authorization in web applications. - **Practical Sessions:** - Creating RESTful API endpoints in Flask. - Handling and responding with JSON data. - Implementing token-based authentication for a Flask API. - **Assignments:** - Develop a RESTful API with Flask that supports CRUD operations for a resource. - Add authentication to the API using token-based methods (e.g., JWT). ### Week 13-14: Advanced Topics in Backend Development - **Lecture Topics:** - Introduction to asynchronous programming and real-time data with WebSockets. - Understanding and implementing caching strategies. - Basics of containerization and using Docker for development. - Deployment best practices and using cloud services (e.g., AWS, Heroku). - **Practical Sessions:** - Implementing WebSocket communication in Flask for real-time updates. - Setting up caching for a Flask application to improve performance. - Containerizing a Flask application with Docker. - Deploying a Flask application to a cloud service (e.g., Heroku). - **Assignments:** - Add real-time features to the Flask application using WebSockets. - Containerize and deploy the Flask application using Docker and a cloud platform. ### Week 15: Final Project and Course Review - **Lecture Topics:** - Review of key concepts and best practices in backend development. - Introduction to continuous integration and continuous deployment (CI/CD). - Overview of monitoring and maintaining web applications. - **Practical Sessions:** - Final project development: integrate all learned concepts into a comprehensive application. - Setting up a CI/CD pipeline for automatic deployment. - Monitoring application performance and managing logs. - **Assignments:** - Develop and present a final project that incorporates database integration, API development, authentication, and deployment. - Document the project and prepare a deployment pipeline using CI/CD tools. ### Recommended Resources: - **Books:** - "Flask Web Development" by Miguel Grinberg - "Python Crash Course" by Eric Matthes - "SQL for Beginners" by Brandon Simonson - "Docker: Up & Running" by Karl Matthias and Sean Kane - **Online Tutorials and Documentation:** - [Flask Documentation](https://flask.palletsprojects.com/) - [SQLAlchemy Documentation](https://docs.sqlalchemy.org/) - [Real Python Flask Tutorials](https://realpython.com/tutorials/flask/) - [Docker Documentation](https://docs.docker.com/) - **Tools:** - Integrated Development Environments (IDEs) like PyCharm or VSCode - Version control systems (Git and GitHub) - Database management tools (pgAdmin, DBeaver) - API development and testing tools (Postman) - Containerization and deployment tools (Docker, Heroku) This curriculum provides a structured path from basic web and programming concepts to advanced backend development techniques. It ensures that students gain both theoretical knowledge and practical skills to design, implement, and deploy robust backend applications.
/* * IntelliJ Jenkins Integration Plugin * Copyright (C) 2014 Andreas Vogler * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package geneon.intellij.plugin.jenkins.ui; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.ui.*; import com.intellij.ui.table.JBTable; import geneon.intellij.plugin.jenkins.AppConfiguration; import geneon.intellij.plugin.jenkins.model.JenkinsServer; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellEditor; import java.awt.*; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class AppConfigurable implements Configurable { // UI private JPanel configPanel; private JBTable serversTable; private JenkinsServerTableModel serversTableModel; public AppConfigurable() { } @Nls public String getDisplayName() { return "Jenkins Integration"; } @Nullable public String getHelpTopic() { return null; } @Nullable public JComponent createComponent() { configPanel = new JPanel(new GridBagLayout()); configPanel.setBorder(IdeBorderFactory.createTitledBorder("Jenkins servers", false)); serversTableModel = new JenkinsServerTableModel(); serversTable = new JBTable(serversTableModel); JPanel serversPanel = ToolbarDecorator.createDecorator(serversTable) .setAddAction(new AnActionButtonRunnable() { public void run(AnActionButton anActionButton) { stopEditing(); JenkinsServer server = new JenkinsServer(); if (editServer(server)) { serversTableModel.addServer(server); } } }) .setEditAction(new AnActionButtonRunnable() { public void run(AnActionButton button) { editSelectedServer(); } }) .setRemoveAction(new AnActionButtonRunnable() { public void run(AnActionButton button) { stopEditing(); serversTableModel.removeServer(getSelectedServer()); } }) .createPanel(); new DoubleClickListener() { @Override protected boolean onDoubleClick(MouseEvent e) { editSelectedServer(); return true; } }.installOn(serversTable); configPanel.add(serversPanel, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); return configPanel; } private void editSelectedServer() { if (editServer(getSelectedServer())) { serversTableModel.fireServerUpdated(getSelectedServer()); } } private boolean editServer(JenkinsServer server) { EditServerDialog dialog = new EditServerDialog(configPanel, server); dialog.show(); return dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE; } private JenkinsServer getSelectedServer() { int row = serversTable.getSelectedRow(); if (row != -1) { return serversTableModel.getServer(row); } else { return null; } } private void stopEditing() { if (serversTable.isEditing()) { TableCellEditor editor = serversTable.getCellEditor(); if (editor != null) { editor.stopCellEditing(); } } } public boolean isModified() { stopEditing(); List<JenkinsServer> initialServers = getConfiguredServers(); List<JenkinsServer> myServers = serversTableModel.getServers(); if (myServers.size() != initialServers.size()) { return true; } for (JenkinsServer initialServer : initialServers) { if (!myServers.contains(initialServer)) { return true; } } return false; } public void apply() throws ConfigurationException { stopEditing(); if (isModified()) { setConfiguredServers(serversTableModel.getServers()); } } public void reset() { serversTableModel.setServers(getConfiguredServers()); } private List<JenkinsServer> getConfiguredServers() { return ServiceManager.getService(AppConfiguration.class).getServers(); } private void setConfiguredServers(List<JenkinsServer> servers) { ServiceManager.getService(AppConfiguration.class).setServers(servers); } public void disposeUIResources() { configPanel = null; serversTableModel = null; serversTable = null; } private static class JenkinsServerTableModel extends AbstractTableModel { private String[] colNames = {"Server", "URL"}; private List<JenkinsServer> servers = Collections.emptyList(); public int getRowCount() { return getServers().size(); } public int getColumnCount() { return 2; } public Object getValueAt(int rowIndex, int columnIndex) { JenkinsServer server = getServers().get(rowIndex); switch (columnIndex) { case 0: return server.getName(); case 1: return server.getUrl(); default: throw new IllegalArgumentException("invalid column index"); } } public void addServer(JenkinsServer server) { servers.add(server); int row = servers.size() - 1; fireTableRowsInserted(row, row); } public void removeServer(JenkinsServer server) { int row = servers.indexOf(server); if (row != -1) { servers.remove(row); fireTableRowsDeleted(row, row); } } @Override public String getColumnName(int column) { return colNames[column]; } public void setServers(List<JenkinsServer> servers) { this.servers = new ArrayList<JenkinsServer>(servers); fireTableDataChanged(); } public List<JenkinsServer> getServers() { return Collections.unmodifiableList(servers); } public JenkinsServer getServer(int row) { return servers.get(row); } public void fireServerUpdated(JenkinsServer server) { int row = servers.indexOf(server); fireTableRowsUpdated(row, row); } } }
import React from "react"; import { BrowserRouter as Router, Route, Routes, Navigate, } from "react-router-dom"; import "react-toastify/dist/ReactToastify.css"; import Dashboard from "./pages/dashboard/Dashboard"; import Category from "./pages/category/Category"; import { ToastContainer } from "react-toastify"; import Transaction from "./pages/transaction/Transaction"; import User from "./pages/users/User"; import Photo from "./pages/photo/Photo"; import Video from "./pages/video/Video"; import Login from "./pages/Signin"; export default function App() { const isAdmin = () => { return localStorage.getItem("role") === "admin"; } return ( <div> <ToastContainer /> <Router> <Routes> <Route path="/" element={ isAdmin() ? ( <Navigate to="/admin/category" /> ) : ( <Navigate to="/login" /> ) } /> <Route path="/admin/category" element={!isAdmin() ? <Navigate to="/login" /> : <Category />} /> <Route path="/admin/transaction" element={!isAdmin() ? <Navigate to="/login" /> : <Transaction />} /> <Route path="/admin/user" element={!isAdmin() ? <Navigate to="/login" /> : <User />} /> <Route path="/admin/photo" element={!isAdmin() ? <Navigate to="/login" /> : <Photo />} /> <Route path="/admin/video" element={!isAdmin() ? <Navigate to="/login" /> : <Video />} /> <Route path="/login" element={isAdmin() ? <Navigate to="/admin/category" /> : <Login />} /> </Routes> </Router> </div> ); }
<h1>Skill Challenge: Programación básica en Java</h1> <p> El reto consiste en implementar una aplicación de gestión de películas. Deberás crear las clases necesarias para representar una película y un gestor de películas que permita realizar operaciones básicas, como agregar una película, eliminar una película y obtener una lista de películas. </p> Requisitos: <ol> <li> Crea una clase Película que tenga los siguientes atributos: <ul> - id : int - nombre : String - disponible : booolean </ul> </li> <li> Crea una clase GestorPelicula que contenga una colección de películas (puedes utilizar una lista, por ejemplo) y que tenga los siguientes métodos: <ul> + agregarPelicula(pelicula : Pelicula) : void + eliminarPelicula(id : int) : void + obtenerPeliculas() : List<Pelicula> + obtenerPeliculasDisponibles() : List<Pelicula> + obtenerPeliculasNoDisponibles() : List<Pelicula> + disponibilizarPelicula(id : int) </ul> </li> <li> Crea una clase Main que sirva como punto de entrada de la aplicación. En el método main, crea instancias de películas, agrégalas al gestor de películas y realiza algunas operaciones como: <ul> Eliminar una película Marcar una película como activa Mostrar la lista de películas no disponibles </ul> </li> <li> Estructura del proyecto: <ul> Crea un paquete com.methaporce.modelo para las clases relacionadas las tareas Crea un paquete com.methaporce.vista para la clase Main </ul> </li> </ol>
import BaseSchema from '@ioc:Adonis/Lucid/Schema' export default class extends BaseSchema { protected tableName = 'Coments' public async up() { this.schema.createTable(this.tableName, (table) => { table.increments('id') table.string('username') table.string('text') table.integer('moment_id').unsigned().references('moments.id').onDelete('CASCADE') /** * Uses timestamptz for PostgreSQL and DATETIME2 for MSSQL */ table.timestamp('created_at', { useTz: true }) table.timestamp('updated_at', { useTz: true }) }) } public async down() { this.schema.dropTable(this.tableName) } }
import {Component, OnInit, Input, forwardRef} from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; import * as moment from 'moment'; @Component({ selector: 'app-date-form-input', templateUrl: './date-form-input.component.html', styleUrls: ['./date-form-input.component.less'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => DateFormInputComponent), multi: true } ] }) export class DateFormInputComponent implements OnInit, ControlValueAccessor { @Input() public formControl = {}; value = ''; constructor() { } ngOnInit() { } writeValue(value: string) { const dateObj = moment(value); this.value = dateObj.isValid() ? moment(value).format('DD-MM-YYYY') : ''; } onChange = (value: string) => { } onTouched = () => { } registerOnChange(fn: (value: string) => void) { this.onChange = fn; } registerOnTouched(fn: () => VideoFacingModeEnum) { this.onTouched = fn; } updateValue(value: string) { this.value = value; const dateObj = moment(value, 'DD-MM-YYYY'); this.onChange(dateObj.isValid() ? dateObj.format() : value); this.onTouched(); } }
use crate::api_service::Data; use actix_web::{delete, get, post, web, HttpResponse, Responder}; #[get("/get-all")] async fn get_all_json(app_data: web::Data<crate::AppState>) -> impl Responder { let action: Result<Vec<bson::ordered::OrderedDocument>, mongodb::error::Error> = app_data.service_manager.api.get_json(); let result: Result<Vec<bson::ordered::OrderedDocument>, actix_web::error::BlockingError<mongodb::error::Error>> = web::block(move || action).await; match result { Ok(result) => HttpResponse::Ok().json(result), Err(e) => { println!("Error while getting, {:?}", e); HttpResponse::InternalServerError().finish() } } } #[get("/get-by/{param}")] async fn get_user_email(app_data: web::Data<crate::AppState>, param: web::Path<String>) -> impl Responder { let action: Result<Vec<bson::ordered::OrderedDocument>, mongodb::error::Error> = app_data.service_manager.api.get_by(&param); let result: Result<Vec<bson::ordered::OrderedDocument>, actix_web::error::BlockingError<mongodb::error::Error>> = web::block(move || action).await; match result { Ok(result) => HttpResponse::Ok().json(result), Err(e) => { println!("Error while getting, {:?}", e); HttpResponse::InternalServerError().finish() } } } #[post("/add")] async fn add_user(app_data: web::Data<crate::AppState>, data: web::Json<Data>) -> impl Responder { let action: Result<mongodb::results::InsertOneResult, mongodb::error::Error> = app_data.service_manager.api.create(&data); let result: Result<mongodb::results::InsertOneResult, actix_web::error::BlockingError<mongodb::error::Error>> = web::block(move || action).await; match result { Ok(result) => HttpResponse::Ok().json(result.inserted_id), Err(e) => { println!("Error while getting, {:?}", e); HttpResponse::InternalServerError().finish() } } } #[post("/update/{param}")] async fn update_user(app_data: web::Data<crate::AppState>, data: web::Json<Data>, param: web::Path<String>) -> impl Responder { let action: Result<mongodb::results::UpdateResult, mongodb::error::Error> = app_data.service_manager.api.update(&data, &param); let result: Result<mongodb::results::UpdateResult, actix_web::error::BlockingError<mongodb::error::Error>> = web::block(move || action).await; match result { Ok(result) => HttpResponse::Ok().json(result.modified_count), Err(e) => { println!("Error while getting, {:?}", e); HttpResponse::InternalServerError().finish() } } } #[delete("/delete")] async fn delete_user(app_data: web::Data<crate::AppState>, data: web::Json<Data>) -> impl Responder { let action: Result<mongodb::results::DeleteResult, mongodb::error::Error> = app_data.service_manager.api.delete(&data.title); let result: Result<mongodb::results::DeleteResult, actix_web::error::BlockingError<mongodb::error::Error>> = web::block(move || action).await; match result { Ok(result) => HttpResponse::Ok().json(result.deleted_count), Err(e) => { println!("Error while getting, {:?}", e); HttpResponse::InternalServerError().finish() } } } // function that will be called on new Application to configure routes for this module pub fn init(cfg: &mut web::ServiceConfig) { cfg.service(get_user_email); cfg.service(add_user); cfg.service(update_user); cfg.service(delete_user); cfg.service(get_all_json); }
<!DOCTYPE html> <html lang="pt-br"> <head> <!-- Meta tags Obrigatórias --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Formulário com máscara e validação</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <!-- icones --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css"> <!-- Sweet Alert - Alerta de CPF invalido --> <script src="https://cdn.jsdelivr.net/npm/sweetalert2@8"></script> <style> .swal2-title{ font-size: 22px; } .swal2-popup { width: 18em; } @media (max-width: 575px){ .font-mb-3{ font-size: 28px; } .swal2-title{ font-size: 24px; } } </style> </head> <body> <div class="container py-3 p-md-2"> <h1 class="text-center font-mb-3">Formulário com máscara e validação</h1> <div class="shadow p-3 p-md-5"> <form name="form1" method="POST"> <div class="row"> <div class="col-12 col-md"> <div class="form-row"> <div class="form-group col-12 col-md"> <label class="mb-0">CPF</label> <input type="text" class="form-control" id="" name="" mask-cpf valida-cpf maxlength="14" required> <div id="alertCPF" class="alertError"></div> </div> <div class="form-group col-12 col-md"> <label class="mb-0">CNPJ</label> <input type="text" class="form-control" id="" name="" mask-cnpj valida-cnpj maxlength="18" required> <div id="alertCNPJ" class="alertError"></div> </div> </div> <div class="form-row"> <div class="form-group col-12 col-md"> <label class="mb-0">RG</label> <input type="text" class="form-control" id="" name="" mask-rg valida-rg maxlength="12" required> <div id="alertRG" class="alertError d-none"></div> </div> <div class="form-group col-12 col-md"> <label class="mb-0">CPF ou CNPJ</label><span class="small font-italic text-truncate"> - Somente números</span> <input type="text" class="form-control" id="" name="" mask-cnpj-cpf valida-cnpj-cpf maxlength="14" required> <div id="alertCPF-CNPJ" class="alertError"></div> </div> </div> <div class="form-row"> <div class="form-group col"> <label class="mb-0">Nome completo</label> <input type="text" class="form-control" id="" name="" valida-nome required> <div id="alertNOME" class="alertError"></div> </div> </div> <div class="form-row"> <div class="form-group col-12 col-md"> <label class="mb-0">E-mail</label> <input type="email" class="form-control" id="" name="" valida-email required> <div id="alertEmail" class="alertError"></div> </div> <div class="form-group col-12 col-md"> <label class="mb-0">Confirmar e-mail</label> <input type="email" class="form-control" id="" name="" valida-confEmail required> <div id="alertConfEmail" class="alertError"></div> </div> </div> <div class="form-row"> <div class="form-group col"> <label class="mb-0">Enviar arquivo</label> <div class="border rounded px-1 py-1"> <input type="file" class="form-control-file" id="" name="" valida-arquivo required> <div id="alertArquivo" class="alertError"></div> </div> </div> </div> <div class="form-row"> <div class="form-group col-12 col-md"> <label class="mb-0">Data de nascimento</label> <input type="text" class="form-control" id="" name="" mask-nascimento valida-nascimento maxlength="10" required> <div id="alertNascimento" class="alertError"></div> </div> <div class="form-group col-12 col-md"> <label class="mb-0 small">Data por período<span class="small text-truncate"> - <b>(01/01/2020 a 31/12/2020)</b></span></label> <input type="date" class="form-control" id="entrada" name="" mask-periodo valida-periodo maxlength="10" required> <div id="alertPeriodo" class="alertError d-none"></div> </div> </div> <div class="form-row"> <div class="form-group col-12 col-md"> <label class="mb-0">Telefone</label> <input type="text" class="form-control" id="" name="" mask-telefone valida-telefone maxlength="13" required> <div id="alertTelefone" class="alertError"></div> </div> <div class="form-group col-12 col-md"> <label class="mb-0">Celular</label> <input type="text" class="form-control" id="" name="" mask-celular valida-celular maxlength="14" required> <div id="alertCelular" class="alertError"></div> </div> </div> <div class="form-row"> <div class="form-group col-12 col-md"> <label class="mb-0">Seleção</label> <select name="" id="" class="form-control" valida-selecao required> <option value="">Escolha uma opção</option> <option value="opção 1">opção 1</option> <option value="opção 2">opção 2</option> <option value="opção 3">opção 3</option> <option value="opção 4">opção 4</option> <option value="opção 5">opção 5</option> </select> <div id="alertSelecao" class="alertError"></div> </div> <div class="form-group col-12 col-md"> <label class="mb-0">Opção</label> <div class="border rounded pt-2 pb-1 px-2"> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="optRadio" id="" value="opcao-01" valida-radio required> <label class="form-check-label">Opção 01</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="optRadio" id="" value="opcao-02" valida-radio required> <label class="form-check-label">Opção 02</label> </div> </div> <div id="alertRadio" class="alertError"></div> </div> </div> </div> <div class="col-12 col-md"> <div class="form-row"> <div class="form-group col col-md-6"> <label class="mb-0">CEP</label> <input type="text" class="form-control" id="" name="" mask-cep valida-cep maxlength="9" required> <div id="alertCEP" class="alertError"></div> </div> </div> <div class="form-row"> <div class="form-group col"> <label class="mb-0">Endereço</label> <input type="text" id="" name="" class="form-control" valida-endereco required> <div id="alertEnd" class="alertError"></div> </div> </div> <div class="form-row"> <div class="form-group col-12 col-md"> <label class="mb-0">Número</label> <input type="text" id="" name="" maxlength="6" class="form-control" valida-numero required> <div id="alertNum" class="alertError"></div> </div> <div class="form-group col-12 col-md"> <label class="mb-0">Complemento <span class="small font-italic text-truncate">- Opcional</span></label> <input id="" name="" type="text" class="form-control"> </div> </div> <div class="form-row"> <div class="form-group col-12 col-md"> <label class="mb-0">Bairro</label> <input type="text" id="" name="" class="form-control" valida-bairro required> <div id="alertBairro" class="alertError"></div> </div> </div> <div class="form-row"> <div class="form-group col-12 col-md"> <label class="mb-0">Cidade</label> <input type="text" id="" name="" class="form-control" valida-cidade required> <div id="alertCidade" class="alertError"></div> </div> <div class="form-group col-12 col-md"> <label class="mb-0">UF</label> <select id="" name="" class="form-control custom-select" valida-uf required> <option value="">Selecione seu estado</option> <option value="AC">AC</option> <option value="AL">AL</option> <option value="AM">AM</option> <option value="AP">AP</option> <option value="BA">BA</option> <option value="CE">CE</option> <option value="DF">DF</option> <option value="ES">ES</option> <option value="GO">GO</option> <option value="MA">MA</option> <option value="MG">MG</option> <option value="MS">MS</option> <option value="MT">MT</option> <option value="PA">PA</option> <option value="PB">PB</option> <option value="PE">PE</option> <option value="PI">PI</option> <option value="PR">PR</option> <option value="RJ">RJ</option> <option value="RN">RN</option> <option value="RO">RO</option> <option value="RR">RR</option> <option value="RS">RS</option> <option value="SC">SC</option> <option value="SE">SE</option> <option value="SP">SP</option> <option value="TO">TO</option> </select> <div id="alertUF" class="alertError"></div> </div> </div> <!-- <hr class="my-4 pb-1"> --> <div class="form-row"> <div class="form-group col"> <label class="mb-0">Observação</label> <div class="input-group"> <textarea id="" name="" valida-mensagem class="form-control" rows="1" required></textarea> </div> <div id="alertMensagem" class="alertError"></div> </div> </div> <div class="form-row"> <div class="form-group col-12 col-md"> <label class="mb-0">Senha</label> <div class="input-group"> <input id="" name="" type="password" class="form-control" valida-senha required> </div> <div id="alertSenha" class="alertError"></div> </div> <div class="form-group col-12 col-md"> <label class="mb-0">Confirmar senha</label> <div class="input-group"> <input id="" name="" type="password" class="form-control" valida-confsenha required> </div> <div id="alerConfSenha" class="alertError"></div> </div> </div> <div class="form-row"> <div class="form-group col-12 col-md"> <label class="mb-0">Senha <span class="text-info">(Opção com "força de senha")</span></label> <div class="input-group"> <input id="" name="" type="password" class="form-control" valida-forca-senha required> <span class="input-group-append"> <span class="input-group-text bg-transparent" id="pass-icon"><i class="fas fa-times-circle"></i></span> </span> </div> <div id="alertForcaSenha" class="alertError mt-1"></div> </div> </div> <div class="form-check text-dark mb-3"> <input type="checkbox" name="checkbox" id="" class="form-check-input" valida-checkbox required> <label class="form-check-label">Concordo com o <a href="#" title="Regulamento"><u>regulamento</u></a>.</label> <div id="alertRegulamento" class="alertError"></div> </div> </div> </div> <hr> <div class="text-right"> <button type="submit" id="btnEnviar" class="btn btn-primary">Validar</button> </div> </form> </div> </div> <!-- scripts --> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> <!-- Máscara e validação --> <script src="mascaraValidacao.js"></script> </body> </html>
!!Introduction !!!Rational @ch:ngRational The idea behind FamixNG is to allow the creation of meta-models by composing basic entities rather than using single inheritance. Take for example a simple model with Classes and Methods. A Class has a ''name'' and ''contains'' methods. A Method has a ''name''. The Figure *@simpleHierarchy* shows a simple hierarchy of these classes. +A simple meta-model entities hierarchy.>figures/intro1.eps|width=35|label=fig:simpleHierarchy+ However, if we introduce AnonymousClass we have a problem, it is a Class (thus a ContainerEntity, but it is not Named). With composition, we could say that there are named entities (that have a name) and there are container entities (that contain other entities). A Class is composed of NamedEntity and ContainerEntity, an AnonymousClass is a composition of ContainerEntity, and a Method is a composition of NamedEntity. FamixNG offers a collection of fundamental concepts (NamedEntities, ScopingEntities...) and a better mechanism to handle bi-directional associations to simplify the creation of new meta-models. !!!General Organisation @ch:ngPhilosophy The composition is implemented using Pharo (stateful) traits, and the concepts of the meta-model are implemented using Pharo classes. A new metamodel is generated using a *@Builder>ch:Builder* by telling it how the new concepts are composed and what are their relationships. The FamixNG provides all fundamental concepts as a library of traits. When you create a custom meta-model, you compose the entities of your meta-models (represented by classes) from these traits. You may want to create own traits if you require reusability of a concept they provide. In the most basic usages, one should be able to create a new meta-model by composing the existing fundamental concepts without the need to create new ones. !!!Catalog of Concepts @ch:ngCatalog !!!!Access +Access>figures/Access.eps|width=50|label=fig:Access+ TODO: This trait group requires description, see *@fig:Access* !!!!AnnotationInstance +AnnotationInstance>figures/AnnotationInstance.eps|width=36|label=fig:AnnotationInstance+ TODO: This trait group requires description, see *@fig:AnnotationInstance* !!!!AnnotationInstanceAttribute +AnnotationInstanceAttribute>figures/AnnotationInstanceAttribute.eps|width=43|label=fig:AnnotationInstanceAttribute+ TODO: This trait group requires description, see *@fig:AnnotationInstanceAttribute* !!!!AnnotationType +AnnotationType>figures/AnnotationType.eps|width=59|label=fig:AnnotationType+ TODO: This trait group requires description, see *@fig:AnnotationType* !!!!AnnotationTypeAttribute +AnnotationTypeAttribute>figures/AnnotationTypeAttribute.eps|width=48|label=fig:AnnotationTypeAttribute+ TODO: This trait group requires description, see *@fig:AnnotationTypeAttribute* !!!!Association +Association>figures/Association.eps|width=25|label=fig:Association+ TODO: This trait group requires description, see *@fig:Association* !!!!Attribute +Attribute>figures/Attribute.eps|width=24|label=fig:Attribute+ TODO: This trait group requires description, see *@fig:Attribute* !!!!CaughtException +CaughtException>figures/CaughtException.eps|width=30|label=fig:CaughtException+ TODO: This trait group requires description, see *@fig:CaughtException* !!!!Class +Class>figures/Class.eps|width=11|label=fig:Class+ TODO: This trait group requires description, see *@fig:Class* !!!!ClassHierarchyNavigation +ClassHierarchyNavigation>figures/ClassHierarchyNavigation.eps|width=28|label=fig:ClassHierarchyNavigation+ TODO: This trait group requires description, see *@fig:ClassHierarchyNavigation* !!!!ClassMetrics +ClassMetrics>figures/ClassMetrics.eps|width=39|label=fig:ClassMetrics+ TODO: This trait group requires description, see *@fig:ClassMetrics* !!!!Comment +Comment>figures/Comment.eps|width=25|label=fig:Comment+ TODO: This trait group requires description, see *@fig:Comment* !!!!CompilationUnit +CompilationUnit>figures/CompilationUnit.eps|width=34|label=fig:CompilationUnit+ TODO: This trait group requires description, see *@fig:CompilationUnit* !!!!DeclaredException +DeclaredException>figures/DeclaredException.eps|width=35|label=fig:DeclaredException+ TODO: This trait group requires description, see *@fig:DeclaredException* !!!!DereferencedInvocation +DereferencedInvocation>figures/DereferencedInvocation.eps|width=42|label=fig:DereferencedInvocation+ TODO: This trait group requires description, see *@fig:DereferencedInvocation* !!!!EnumValue +EnumValue>figures/EnumValue.eps|width=24|label=fig:EnumValue+ TODO: This trait group requires description, see *@fig:EnumValue* !!!!Exception +Exception>figures/Exception.eps|width=26|label=fig:Exception+ TODO: This trait group requires description, see *@fig:Exception* !!!!File +File>figures/File.eps|width=23|label=fig:File+ TODO: This trait group requires description, see *@fig:File* !!!!FileAnchor +FileAnchor>figures/FileAnchor.eps|width=19|label=fig:FileAnchor+ TODO: This trait group requires description, see *@fig:FileAnchor* !!!!FileInclude +FileInclude>figures/FileInclude.eps|width=56|label=fig:FileInclude+ TODO: This trait group requires description, see *@fig:FileInclude* !!!!Folder +Folder>figures/Folder.eps|width=37|label=fig:Folder+ TODO: This trait group requires description, see *@fig:Folder* !!!!Function +Function>figures/Function.eps|width=22|label=fig:Function+ TODO: This trait group requires description, see *@fig:Function* !!!!GlobalVariable +GlobalVariable>figures/GlobalVariable.eps|width=27|label=fig:GlobalVariable+ TODO: This trait group requires description, see *@fig:GlobalVariable* !!!!Header +Header>figures/Header.eps|width=20|label=fig:Header+ TODO: This trait group requires description, see *@fig:Header* !!!!ImplicitVariable +ImplicitVariable>figures/ImplicitVariable.eps|width=34|label=fig:ImplicitVariable+ TODO: This trait group requires description, see *@fig:ImplicitVariable* !!!!Invocable +Invocable>figures/Invocable.eps|width=63|label=fig:Invocable+ TODO: This trait group requires description, see *@fig:Invocable* !!!!LCOMMetrics +LCOMMetrics>figures/LCOMMetrics.eps|width=17|label=fig:LCOMMetrics+ TODO: This trait group requires description, see *@fig:LCOMMetrics* !!!!LocalVariable +LocalVariable>figures/LocalVariable.eps|width=33|label=fig:LocalVariable+ TODO: This trait group requires description, see *@fig:LocalVariable* !!!!Method +Method>figures/Method.eps|width=23|label=fig:Method+ TODO: This trait group requires description, see *@fig:Method* !!!!Module +Module>figures/Module.eps|width=26|label=fig:Module+ TODO: This trait group requires description, see *@fig:Module* !!!!Named +Named>figures/Named.eps|width=16|label=fig:Named+ TODO: This trait group requires description, see *@fig:Named* !!!!Namespace +Namespace>figures/Namespace.eps|width=49|label=fig:Namespace+ TODO: This trait group requires description, see *@fig:Namespace* !!!!Package +Package>figures/Package.eps|width=25|label=fig:Package+ TODO: This trait group requires description, see *@fig:Package* !!!!Parameter +Parameter>figures/Parameter.eps|width=36|label=fig:Parameter+ TODO: This trait group requires description, see *@fig:Parameter* !!!!ParameterizedType +ParameterizedType>figures/ParameterizedType.eps|width=36|label=fig:ParameterizedType+ TODO: This trait group requires description, see *@fig:ParameterizedType* !!!!ParameterizedTypeUser +ParameterizedTypeUser>figures/ParameterizedTypeUser.eps|width=47|label=fig:ParameterizedTypeUser+ TODO: This trait group requires description, see *@fig:ParameterizedTypeUser* !!!!PossibleStub +PossibleStub>figures/PossibleStub.eps|width=17|label=fig:PossibleStub+ TODO: This trait group requires description, see *@fig:PossibleStub* !!!!PreprocessorDefine +PreprocessorDefine>figures/PreprocessorDefine.eps|width=23|label=fig:PreprocessorDefine+ TODO: This trait group requires description, see *@fig:PreprocessorDefine* !!!!PreprocessorIfdef +PreprocessorIfdef>figures/PreprocessorIfdef.eps|width=21|label=fig:PreprocessorIfdef+ TODO: This trait group requires description, see *@fig:PreprocessorIfdef* !!!!Reference +Reference>figures/Reference.eps|width=50|label=fig:Reference+ TODO: This trait group requires description, see *@fig:Reference* !!!!ScopingEntity +ScopingEntity>figures/ScopingEntity.eps|width=31|label=fig:ScopingEntity+ TODO: This trait group requires description, see *@fig:ScopingEntity* !!!!SourceAnchor +SourceAnchor>figures/SourceAnchor.eps|width=46|label=fig:SourceAnchor+ TODO: This trait group requires description, see *@fig:SourceAnchor* !!!!SourceLanguage +SourceLanguage>figures/SourceLanguage.eps|width=35|label=fig:SourceLanguage+ TODO: This trait group requires description, see *@fig:SourceLanguage* !!!!Sub +Sub>figures/Sub.eps|width=14|label=fig:Sub+ TODO: This trait group requires description, see *@fig:Sub* !!!!SubInheritance +SubInheritance>figures/SubInheritance.eps|width=30|label=fig:SubInheritance+ TODO: This trait group requires description, see *@fig:SubInheritance* !!!!SuperInheritance +SuperInheritance>figures/SuperInheritance.eps|width=29|label=fig:SuperInheritance+ TODO: This trait group requires description, see *@fig:SuperInheritance* !!!!Template +Template>figures/Template.eps|width=45|label=fig:Template+ TODO: This trait group requires description, see *@fig:Template* !!!!ThrownException +ThrownException>figures/ThrownException.eps|width=32|label=fig:ThrownException+ TODO: This trait group requires description, see *@fig:ThrownException* !!!!Type +Type>figures/Type.eps|width=63|label=fig:Type+ TODO: This trait group requires description, see *@fig:Type* !!!!TypeAlias +TypeAlias>figures/TypeAlias.eps|width=24|label=fig:TypeAlias+ TODO: This trait group requires description, see *@fig:TypeAlias* !!!!TypedStructure +TypedStructure>figures/TypedStructure.eps|width=39|label=fig:TypedStructure+ TODO: This trait group requires description, see *@fig:TypedStructure* !!!!WithClassScope +WithClassScope>figures/WithClassScope.eps|width=20|label=fig:WithClassScope+ TODO: This trait group requires description, see *@fig:WithClassScope* !!!!WithModifiers +WithModifiers>figures/WithModifiers.eps|width=17|label=fig:WithModifiers+ TODO: This trait group requires description, see *@fig:WithModifiers* !!!!WithSignature +WithSignature>figures/WithSignature.eps|width=18|label=fig:WithSignature+ TODO: This trait group requires description, see *@fig:WithSignature*
/* JAVASCRIPT USADO EM TODO O SITE */ /* Neste documento estão os JavaScript que atendem à todas ou a mais de uma seção. Aqui também estão funções que podem ser utilizadas em mais de uma seção do site. */ /* FUNÇÕES GLOBAIS USADAS EM QUALQUER PÁGINA QUANDO NECESSÁRIO */ /* A função '$' é um atalho para 'document.getElement*()' */ function $(objSelector, objListIndex = false){ if(objListIndex) // Se selecionou um índice de uma lista de objetos (o índice é um inteiro >= 0) return document.querySelectorAll(objSelector)[objListIndex]; else if(objSelector.substr(0, 1) != '#') // Vários objetos podem usar a mesma classe, mesmo nome, etc. return document.querySelectorAll(objSelector); else // Objetos referenciados pelo ID são únicos return document.querySelector(objSelector); } // Função padrão para 'sanitizar' os valores dos campos de formulário function sanitiza(texto) { // Limpa espaços antes e depois da string texto = texto.trim(); // Limpa espaços duplicados dentro da string while(texto.indexOf(' ') != -1) // 'TRUE' enquanto ocorrerem espaços duplos texto = texto.replace(' ', ' '); // Troca espaços duplos por simples // Altera caracteres indesejados (usando expressão regular) pelo 'HTML entitie' equivalente texto = texto.replace(/&/g, '&amp;'); /* Caractere '&' */ texto = texto.replace(/</g, '&lt;'); /* Caractere '<' */ texto = texto.replace(/>/g, '&gt;'); /* Caractere '>' */ texto = texto.replace(/"/g, '&quot;'); /* Caractere '"' */ // Retorna string 'limpa' return texto; } // Função para validar somente letras em campos de formulários (usando expressão regular e match()) function soLetras(texto) { if(texto.match(/[^a-zà -ú ]/gi)) return false; return true; } // Função para validar um endereço de e-mail(usando expressão regular e match()) function isMail(texto) { if(texto.match(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]{2,}$/)) return true; return false; }
{% extends theme("base/base.html") %} {% block content %} <style> .coords { background-color: black; color: white; padding: 5px; } </style> <link rel="stylesheet" href="/_themes/default/libraries/leaflet/leaflet.css"/> <script type="text/javascript" src="/_themes/default/libraries/leaflet/leaflet.js"></script> <div class="container"> <h1>{% trans %}Location{% endtrans %}</h1> <div class="row"> <div class="col-md-4"> <div class="panel panel-default"> <div class="panel-body"> <p class="text-center"> <a id="start" class="btn btn-success" href="/locations/edit/0">{% trans %}Add a new location{% endtrans%}</a> </p> </div> </div> </div> </div> {% if locations|length == 0 %} <div class="alert alert-info" role="alert">{% trans %}No location have been defined yet!{% endtrans %}</div> {% else %} {% set index = 0 %} {% for data in locations %} {% if index % 3 == 0 %} <div class="row"> {% endif %} <div class="col-md-4"> <div class="panel panel-default"> <div class="panel-body"> <div class="person-info"> <div class="pull-left photo"> <i class="fa fa-user fa-4x" aria-hidden="true"></i> </div> <div class="pull-right"> {% if data.isHome %} <i class="fa fa-home fa-1x" aria-hidden="true"></i> {% endif %} </div> <ul class="list-unstyled"> <li><strong>{{ data.name }}</strong></li> </ul> <div> <a href="/locations/edit/{{ data.id }}" class="btn btn-default"><span class='glyphicon glyphicon-pencil' aria-hidden='true'></span> {% trans %}Edit{% endtrans %}</a> <a data-toggle="confirmation" class="btn btn-default" data-placement="bottom" data-href="/locations/del/{{ data.id }}"><span class='glyphicon glyphicon-trash' aria-hidden='true'></span> {% trans %}Delete{% endtrans %}</a> </div> </div> </div> </div> </div> {% if index % 3 == 2 %} </div> {% endif %} {% set index = index + 1 %} {% endfor %} {% set index = index - 1 %} {% endif %} <div id="map" style="width:100%; height:400px"></div> <div id="coordinates" class="coords">lat: 0.0000, lng: 0.0000</div> <script type="text/javascript"> $( document ).ready( function () { // polylines colors : see https://www.w3schools.com/colors/colors_names.asp colors = ['#5F9EA0', '#8A2BE2', '#DC143C', '#4BD700']; // Init the map var map = L.map(document.getElementById('map'), {editable: true}).setView([0, 0], 10); // Init tiles source layer L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); // Show the lat and lng under the mouse cursor. var coordsDiv = document.getElementById('coordinates'); map.on('mousemove', function(event) { coordsDiv.textContent = 'lat: ' + event.latlng.lat.toFixed(6)+ ', ' + 'lng: ' + event.latlng.lng.toFixed(6); }); var totalBound; //********* Place the locations {% for data in locations %} {% if data.lat != None and data.lng != None %} //****** Add circles for radius var locCircle = L.circle([ {{ data.lat }}, {{ data.lng }} ], { strokeColor: '#0000FF', strokeOpacity: 0.5, strokeWeight: 1, fillColor: '#0000FF', fillOpacity: 0.15, map: map, center: {lat: {{ data.lat }}, lng: {{ data.lng }}}, radius: {% if data.radius == None %}1000{% else %}{{ data.radius | int }}{% endif %} }).addTo(map); {% if data.isHome == True %} map.panTo(L.latLng({{ data.lat }}, {{ data.lng }})); {% endif %} let subBounds = L.latLngBounds(locCircle.getBounds()); totalBound = totalBound ? totalBound.extend(subBounds) : subBounds; //****** Add markers var contentString{{ data.id }} = '<div id="content">'+ '<div id="siteNotice">'+ '</div>'+ '<h1 id="firstHeading" class="firstHeading">{{ data.name }}</h1>'+ '<div id="bodyContent">'+ '<ul>'+ '<li>{% trans %}Latitude{% endtrans %} : {{ data.lat }} </li>'+ '<li>{% trans %}Longitude{% endtrans %} : {{ data.lng }} </li>'+ '<li>{% trans %}Radius{% endtrans %} : {{ data.radius }} m </li>'+ '</ul>'+ '</div>'+ '</div>'; var marker{{ data.id }} = L.marker([ {{ data.lat }}, {{ data.lng }} ], { {% if data.isHome == True %} icon: L.icon({iconUrl: '/static/images/map_house.png', iconSize: [48, 48], // size of the icon iconAnchor: [24, 46], // point of the icon which will correspond to marker's location popupAnchor: [0, -40] // point from which the popup should open relative to the iconAnchor }), {% endif %} title: '{{ data.name }}' }).addTo(map); marker{{ data.id }}.bindPopup(contentString{{ data.id }}); {% endif %} {% endfor %} //********* Place the persons {% for data in persons %} // DEBUG : data = {{ data }} {% if data.lat != None and data.lng != None %} //****** Add markers // var last_seen = new Date({{ data.last_seen }} * 1000).toLocaleString(); var last_seen = '16/11/2018'; var contentStringP{{ data.id }} = '<div id="content">'+ '<div id="siteNotice">'+ '</div>'+ '<h1 id="firstHeading" class="firstHeading">{{ data.first_name }} {{ data.last_name }}</h1>'+ '<div id="bodyContent">'+ '<ul>'+ '<li>{% trans %}Last seen{% endtrans %} : ' + last_seen + ' </li>'+ '<li>{% trans %}Latitude{% endtrans %} : {{ data.lat }} </li>'+ '<li>{% trans %}Longitude{% endtrans %} : {{ data.lng }} </li>'+ '</ul>'+ '</div>'+ '</div>'; let idColor = {{ data.id }}%colors.length; var markerP{{ data.id }} = L.marker([{{ data.lat }}, {{ data.lng }}], { icon: L.icon({iconUrl: '/static/images/map_person-'+idColor+'.png', iconSize: [42, 42], // size of the icon iconAnchor: [21, 40], // point of the icon which will correspond to marker's location popupAnchor: [0, -36] // point from which the popup should open relative to the iconAnchor }), label: '{{ data.first_name[0] }}', title: '{{ data.first_name }} {{ data.last_name }}' }).addTo(map); markerP{{ data.id }}.bindPopup(contentStringP{{ data.id }}); {% endif %} //********* Grab the history to display a polyline let historyLen = 30; var polyline{{ data.id }} = []; var jqxhr = $.getJSON( "/rest/sensorhistory/id/{{ data.location_sensor }}/last/" + historyLen, function() { console.log( "success" ); }) .done(function(data) { // Data test only for test /** let data = [{'value_str':'43.6132,5.5479'},{'value_str':'43.6532,5.5279'},{'value_str':'43.8132,5.2479'}, {'value_str':'43.82362903478315,5.044328015375653'},{'value_str':'43.2132,5.479'},{'value_str':'43.5132,5.3479'}, {'value_str':'43.51322903478315,5.3479328015375653'},{'value_str':'43.3132,5.3679'},{'value_str':'43.2532,5.41479'}]; **/ for(idx=0;idx<data.length;idx++) { polyline{{ data.id }}.push({lat: parseFloat(data[idx].value_str.split(",")[0]), lng: parseFloat(data[idx].value_str.split(",")[1]) }); } historyLen = polyline{{ data.id }}.length * 1.5; var colorGradient = generateColor('#ffffff', colors[idColor] , historyLen); console.log(colorGradient); for (var i = 0; i < polyline{{ data.id }}.length-1; i++) { var pathStyle = L.polyline([polyline{{ data.id }}[i], polyline{{ data.id }}[i+1]], { color: "#"+colorGradient[i], opacity: 1.0, weight: 8*(1-(i/historyLen)) }).addTo(map); } subBounds = L.latLngBounds(pathStyle.getBounds()); totalBound = totalBound ? totalBound.extend(subBounds) : subBounds; }) .fail(function() { console.log( "error" ); }) .always(function() { console.log( "complete" ); }); {% endfor %} if (totalBound) map.fitBounds(totalBound); }); function hex (c) { var s = "0123456789abcdef"; var i = parseInt (c); if (i == 0 || isNaN (c)) return "00"; i = Math.round (Math.min (Math.max (0, i), 255)); return s.charAt ((i - i % 16) / 16) + s.charAt (i % 16); } /* Convert an RGB triplet to a hex string */ function convertToHex (rgb) { return hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]); } /* Remove '#' in color hex string */ function trim (s) { return (s.charAt(0) == '#') ? s.substring(1, 7) : s } /* Convert a hex string to an RGB triplet */ function convertToRGB (hex) { var color = []; color[0] = parseInt ((trim(hex)).substring (0, 2), 16); color[1] = parseInt ((trim(hex)).substring (2, 4), 16); color[2] = parseInt ((trim(hex)).substring (4, 6), 16); return color; } function generateColor(colorStart,colorEnd,colorCount){ // The beginning of your gradient var start = convertToRGB (colorStart); // The end of your gradient var end = convertToRGB (colorEnd); // The number of colors to compute var len = colorCount; //Alpha blending amount var alpha = 0.0; var saida = []; for (i = 0; i < len; i++) { var c = []; alpha += (1.0/len); c[0] = start[0] * alpha + (1 - alpha) * end[0]; c[1] = start[1] * alpha + (1 - alpha) * end[1]; c[2] = start[2] * alpha + (1 - alpha) * end[2]; saida.push(convertToHex (c)); } return saida; } /** * Converts an RGB color value to HSL. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSL_color_space. * Assumes r, g, and b are contained in the set [0, 255] and * returns h, s, and l in the set [0, 1]. * * @param Number r The red color value * @param Number g The green color value * @param Number b The blue color value * @return Array The HSL representation */ function rgbToHsl(r, g, b){ r /= 255, g /= 255, b /= 255; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2; if(max == min){ h = s = 0; // achromatic }else{ var d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch(max){ case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return [h, s, l]; } /** * Converts an HSL color value to RGB. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSL_color_space. * Assumes h, s, and l are contained in the set [0, 1] and * returns r, g, and b in the set [0, 255]. * * @param Number h The hue * @param Number s The saturation * @param Number l The lightness * @return Array The RGB representation */ function hslToRgb(h, s, l){ var r, g, b; if(s == 0){ r = g = b = l; // achromatic }else{ function hue2rgb(p, q, t){ if(t < 0) t += 1; if(t > 1) t -= 1; if(t < 1/6) return p + (q - p) * 6 * t; if(t < 1/2) return q; if(t < 2/3) return p + (q - p) * (2/3 - t) * 6; return p; } var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hue2rgb(p, q, h + 1/3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1/3); } return [r * 255, g * 255, b * 255]; } </script> </div> {% endblock %}
--- title: Quickstart Tutorial meta_title: Args &mdash; Quickstart Tutorial --- Imagine we're building a utility for joining MP3 files. We want the user to supply the file names as a list of command line arguments. We also want to support an `--out/-o` option so the user can specify an output filename and a `--quiet/-q` flag for turning down the program's verbosity. First we need to create an `ArgParser` instance: ::: code c #include "args.h" ArgParser* parser = ap_new_parser(); ap_set_helptext(parser, "Usage: mp3cat..."); ap_set_version(parser, "1.0"); Supplying a helptext string for the parser activates an automatic `--help/-h` flag; similarly, supplying a version string activates an automatic `--version/-v` flag. Now we can register our options and flags: ::: code c ap_add_str_opt(parser, "out o", "default.mp3"); ap_add_flag(parser, "quiet q"); That's it, we're done specifying our interface. Now we can parse the program's command line arguments, passing in `argc` and `argv` as supplied to `main()`: ::: code c ap_parse(parser, argc, argv); This will exit with a suitable error message for the user if anything goes wrong. Now we can check if the `--quiet` flag was found: ::: code c if (ap_found(parser, "quiet")) { do_stuff(); } And determine our output filepath: ::: code c char* path = ap_get_str_value(parser, "out"); The input filenames will be collected by the parser into a list of positional arguments which we can access in various ways, e.g ::: code c for (int i = 0; i < ap_count_args(parser); i++) { char* filename = ap_get_arg_at_index(parser, i); do_stuff(); } When we're finished using it, we can free up the parser's memory: ::: code c ap_free(parser);
package com.example.parkme.navigation import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.fragment.app.Fragment import androidx.navigation.findNavController import androidx.navigation.fragment.navArgs import com.bumptech.glide.Glide import com.example.parkme.R import com.example.parkme.databinding.FragmentCocheraDetailBinding import com.example.parkme.entities.Cochera import com.example.parkme.entities.User import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore class CocheraDetailUserFr : Fragment() { private val args: CocheraDetailUserFrArgs by navArgs() private lateinit var binding: FragmentCocheraDetailBinding private val db = FirebaseFirestore.getInstance() private val cochera: Cochera by lazy { args.cochera } private val uid: String? by lazy { FirebaseAuth.getInstance().currentUser?.uid } private lateinit var user: User override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { getUserState() binding = FragmentCocheraDetailBinding.inflate(inflater, container, false) return binding.root } private fun setBinding(){ var reservarButton: Button = binding.CocheraDetailReservarButton var programarButton: Button = binding.CocheraDetailProgramarButton if (user.reservaInCheckIn != "") { reservarButton.isEnabled = false programarButton.text = getString(R.string.realizar_checkout_cochera_anterior) } else { reservarButton.isEnabled = true programarButton.text = getString(R.string.estacionar_ahora) reservarButton.setOnClickListener { val action = CocheraDetailUserFrDirections.actionCocheraDetailUserFrToReservaCocheraFr(cochera) binding.root.findNavController()?.navigate(action) } } if (user.reservaInReservada != "") { programarButton.isEnabled = false programarButton.text = getString(R.string.alcanzaste_el_limite_de_una_reserva) } else { programarButton.isEnabled = true programarButton.text = getString(R.string.programa_reserva) programarButton.setOnClickListener { val action = CocheraDetailUserFrDirections.actionCocheraDetailUserFrToReservaCocheraFr(cochera) binding.root.findNavController()?.navigate(action) } } binding.ownerIdText.text = cochera.direccion binding.cocheraDetailText.text = cochera.direccion binding.precioPorHoraDetail.text = cochera.price.toString() binding.cocheraOwnerName.text = "Dueño: ${cochera.ownerName}" Glide.with(requireContext()) .load(cochera.urlImage) .centerCrop() .into(binding.imageView2) programarButton.setOnClickListener { val action = CocheraDetailUserFrDirections.actionCocheraDetailUserFrToProgramarReservaFr(cochera) binding.root.findNavController()?.navigate(action) } } private fun getUserState() { if (uid != null) { db.collection("users").document(uid!!) .get() .addOnSuccessListener { document -> if (document != null) { user = document.toObject(User::class.java)!! setBinding() } else { Log.d("ReservaCocheraFr", "No such document") } } .addOnFailureListener { exception -> Log.d("ReservaCocheraFr", "get failed with ", exception) } } } }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <meta charset="UTF-8"> <title>Modify user</title> </head> <body> <form th:method="PATCH" th:action="@{/admin/update/{id}(id=${user.id})}" th:object="${user}"> <input type="hidden" name="_method" value="PATCH" /> <div class="main block"> <h2>Modify or correct data</h2> <div class="field"> <label for="username">username</label> <input type="text" th:field="*{username}" id="username"/> <div style="color:crimson" th:errors="*{username}" th:if="${#fields.hasErrors('username')}">Error</div> </div> <div class="field"> <label for="password">password</label> <input type="text" th:field="*{password}" id="password"/> <div style="color:crimson" th:errors="*{password}" th:if="${#fields.hasErrors('password')}">Error</div> </div> <div class="field"> <li th:each="role : ${userRoles}"> <select hidden th:field="*{roles[__${roleStat.index}__].id}"> <option th:value="${role.id}"></option> </select> <select hidden th:field="*{roles[__${roleStat.index}__].role}"> <option th:value="${role.role}"></option> </select> <input type="checkbox" th:field="*{roles[__${roleStat.index}__]}" th:value="${role}"> <label th:text="${role.role}"></label> </li> </div> <br/> <hr/> <input type="submit" value="Modify or correct"/> </div> </form> </body> </html>
package be.example.wordcombiner; import be.example.WordCombination; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; public class SimpleSixLetterWordsCombiner implements WordCombiner { private final int wordCombinationCharSize; public SimpleSixLetterWordsCombiner() { this.wordCombinationCharSize = 6; } public Set<WordCombination> findCombinationsIn(final List<String> words) { final Set<String> candidates = words.stream() .filter(word -> word.length() == wordCombinationCharSize) .collect(Collectors.toSet()); if (candidates.isEmpty()) { return Set.of(); } final List<String> combinationWords = words.stream() .filter(word -> word.length() < wordCombinationCharSize) .collect(Collectors.toList()); return findWordCombinationsFor(combinationWords, candidates); } private Set<WordCombination> findWordCombinationsFor(final List<String> combinationWords, final Set<String> candidates) { return candidates.stream() .flatMap(candidate -> findWordCombinationsFor(combinationWords, candidate).stream()) .collect(Collectors.toSet()); } private Set<WordCombination> findWordCombinationsFor(final List<String> combinationWords, final String candidate) { final Set<WordCombination> combinations = new HashSet<>(); final Set<String> prefixes = combinationWords.stream().filter(candidate::startsWith).collect(Collectors.toSet()); prefixes.forEach(prefix -> { final List<String> possibleCombinations = new ArrayList<>(combinationWords); possibleCombinations.remove(prefix); final Set<WordCombination> foundCombinations = possibleCombinations.stream() .filter(postfix -> String.join("", prefix, postfix).equals(candidate)) .map(postfix -> new WordCombination(candidate, prefix, postfix)) .collect(Collectors.toSet()); combinations.addAll(foundCombinations); }); return combinations; } }
/******************************************************************************* * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * * Port to the D programming language: * Jacob Carlborg <[email protected]> *******************************************************************************/ module dwt.widgets.Text; import dwt.dwthelper.utils; import dwt.DWT; import dwt.DWTException; import dwt.events.ModifyListener; import dwt.events.SelectionEvent; import dwt.events.SelectionListener; import dwt.events.VerifyListener; import dwt.graphics.Color; import dwt.graphics.Point; import dwt.graphics.Rectangle; import dwt.internal.cocoa.NSAttributedString; import dwt.internal.cocoa.NSCell; import dwt.internal.cocoa.NSColor; import dwt.internal.cocoa.NSControl; import dwt.internal.cocoa.NSEvent; import dwt.internal.cocoa.NSFont; import dwt.internal.cocoa.NSMutableString; import dwt.internal.cocoa.NSNotification; import dwt.internal.cocoa.NSRange; import dwt.internal.cocoa.NSRect; import dwt.internal.cocoa.NSScrollView; import dwt.internal.cocoa.NSSize; import dwt.internal.cocoa.NSString; import dwt.internal.cocoa.NSText; import dwt.internal.cocoa.NSTextContainer; import dwt.internal.cocoa.NSTextField; import dwt.internal.cocoa.NSTextFieldCell; import dwt.internal.cocoa.NSTextStorage; import dwt.internal.cocoa.NSTextView; import dwt.internal.cocoa.OS; import dwt.internal.cocoa.SWTScrollView; import dwt.internal.cocoa.SWTSearchField; import dwt.internal.cocoa.SWTSecureTextField; import dwt.internal.cocoa.SWTTextField; import dwt.internal.cocoa.SWTTextView; import Carbon = dwt.internal.c.Carbon; import dwt.internal.objc.cocoa.Cocoa; import objc = dwt.internal.objc.runtime; import dwt.widgets.Composite; import dwt.widgets.Event; import dwt.widgets.Scrollable; import dwt.widgets.TypedListener; /** * Instances of this class are selectable user interface * objects that allow the user to enter and modify text. * Text controls can be either single or multi-line. * When a text control is created with a border, the * operating system includes a platform specific inset * around the contents of the control. When created * without a border, an effort is made to remove the * inset such that the preferred size of the control * is the same size as the contents. * <p> * <dl> * <dt><b>Styles:</b></dt> * <dd>CANCEL, CENTER, LEFT, MULTI, PASSWORD, SEARCH, SINGLE, RIGHT, READ_ONLY, WRAP</dd> * <dt><b>Events:</b></dt> * <dd>DefaultSelection, Modify, Verify</dd> * </dl> * <p> * Note: Only one of the styles MULTI and SINGLE may be specified, * and only one of the styles LEFT, CENTER, and RIGHT may be specified. * </p><p> * IMPORTANT: This class is <em>not</em> intended to be subclassed. * </p> * * @see <a href="http://www.eclipse.org/swt/snippets/#text">Text snippets</a> * @see <a href="http://www.eclipse.org/swt/examples.php">DWT Example: ControlExample</a> * @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a> */ public class Text : Scrollable { alias Scrollable.computeSize computeSize; alias Scrollable.dragDetect dragDetect; alias Scrollable.setBackground setBackground; alias Scrollable.setFont setFont; alias Scrollable.setForeground setForeground; alias Scrollable.translateTraversal translateTraversal; int textLimit, tabs = 8; wchar echoCharacter = '\0'; bool doubleClick, receivingFocus; wchar[] hiddenText, message; NSRange* selectionRange; NSRange selectionRangeStruct; /** * The maximum number of characters that can be entered * into a text widget. * <p> * Note that this value is platform dependent, based upon * the native widget implementation. * </p> */ public static const int LIMIT; /** * The delimiter used by multi-line text widgets. When text * is queried and from the widget, it will be delimited using * this delimiter. */ public static const wchar[] DELIMITER; static const wchar PASSWORD = '\u2022'; /* * These values can be different on different platforms. * Therefore they are not initialized in the declaration * to stop the compiler from inlining. */ static this () { LIMIT = 0x7FFFFFFF; DELIMITER = "\r"; } /** * Constructs a new instance of this class given its parent * and a style value describing its behavior and appearance. * <p> * The style value is either one of the style constants defined in * class <code>DWT</code> which is applicable to instances of this * class, or must be built by <em>bitwise OR</em>'ing together * (that is, using the <code>int</code> "|" operator) two or more * of those <code>DWT</code> style constants. The class description * lists the style constants that are applicable to the class. * Style bits are also inherited from superclasses. * </p> * * @param parent a composite control which will be the parent of the new instance (cannot be null) * @param style the style of control to construct * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the parent is null</li> * </ul> * @exception DWTException <ul> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the parent</li> * <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass</li> * </ul> * * @see DWT#SINGLE * @see DWT#MULTI * @see DWT#READ_ONLY * @see DWT#WRAP * @see Widget#checkSubclass * @see Widget#getStyle */ public this (Composite parent, int style) { textLimit = LIMIT; super (parent, checkStyle (style)); if ((style & DWT.SEARCH) !is 0) { // int inAttributesToSet = (style & DWT.CANCEL) !is 0 ? OS.kHISearchFieldAttributesCancel : 0; // OS.HISearchFieldChangeAttributes (handle, inAttributesToSet, 0); /* * Ensure that DWT.CANCEL is set. * NOTE: CANCEL has the same value as H_SCROLL so it is * necessary to first clear these bits to avoid a scroll * bar and then reset the bit using the original style * supplied by the programmer. */ if ((style & DWT.CANCEL) !is 0) this.style |= DWT.CANCEL; } } /** * Adds the listener to the collection of listeners who will * be notified when the receiver's text is modified, by sending * it one of the messages defined in the <code>ModifyListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see ModifyListener * @see #removeModifyListener */ public void addModifyListener (ModifyListener listener) { checkWidget (); if (listener is null) error (DWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (DWT.Modify, typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when the control is selected by the user, by sending * it one of the messages defined in the <code>SelectionListener</code> * interface. * <p> * <code>widgetSelected</code> is not called for texts. * <code>widgetDefaultSelected</code> is typically called when ENTER is pressed in a single-line text, * or when ENTER is pressed in a search text. If the receiver has the <code>DWT.SEARCH | DWT.CANCEL</code> style * and the user cancels the search, the event object detail field contains the value <code>DWT.CANCEL</code>. * </p> * * @param listener the listener which should be notified when the control is selected by the user * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see SelectionListener * @see #removeSelectionListener * @see SelectionEvent */ public void addSelectionListener(SelectionListener listener) { checkWidget (); if (listener is null) error (DWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (DWT.Selection,typedListener); addListener (DWT.DefaultSelection,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when the receiver's text is verified, by sending * it one of the messages defined in the <code>VerifyListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see VerifyListener * @see #removeVerifyListener */ public void addVerifyListener (VerifyListener listener) { checkWidget (); if (listener is null) error (DWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (DWT.Verify, typedListener); } /** * Appends a string. * <p> * The new text is appended to the text at * the end of the widget. * </p> * * @param string the string to be appended * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the string is null</li> * </ul> * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void append (String stri) { wchar[] string = stri.toString16(); checkWidget (); //if (string is null) error (DWT.ERROR_NULL_ARGUMENT); if (hooks (DWT.Verify) || filters (DWT.Verify)) { int charCount = getCharCount (); string = verifyText (string, charCount, charCount, null); if (string is null) return; } NSString str = NSString.stringWith16 (string); if ((style & DWT.SINGLE) !is 0) { setSelection (getCharCount ()); insertEditText (string); } else { NSTextView widget = cast(NSTextView) view; NSMutableString mutableString = widget.textStorage ().mutableString (); mutableString.appendString (str); NSRange range = NSRange (); range.location = mutableString.length (); widget.scrollRangeToVisible (range); } if (string.length () !is 0) sendEvent (DWT.Modify); } bool becomeFirstResponder (objc.id id, objc.SEL sel) { receivingFocus = true; bool result = super.becomeFirstResponder (id, sel); receivingFocus = false; return result; } static int checkStyle (int style) { if ((style & DWT.SEARCH) !is 0) { style |= DWT.SINGLE | DWT.BORDER; style &= ~DWT.PASSWORD; } if ((style & DWT.SINGLE) !is 0 && (style & DWT.MULTI) !is 0) { style &= ~DWT.MULTI; } style = checkBits (style, DWT.LEFT, DWT.CENTER, DWT.RIGHT, 0, 0, 0); if ((style & DWT.SINGLE) !is 0) style &= ~(DWT.H_SCROLL | DWT.V_SCROLL | DWT.WRAP); if ((style & DWT.WRAP) !is 0) { style |= DWT.MULTI; style &= ~DWT.H_SCROLL; } if ((style & DWT.MULTI) !is 0) style &= ~DWT.PASSWORD; if ((style & (DWT.SINGLE | DWT.MULTI)) !is 0) return style; if ((style & (DWT.H_SCROLL | DWT.V_SCROLL)) !is 0) return style | DWT.MULTI; return style | DWT.SINGLE; } /** * Clears the selection. * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void clearSelection () { checkWidget (); Point selection = getSelection (); setSelection (selection.x); } public Point computeSize (int wHint, int hHint, bool changed) { checkWidget (); int width = 0, height = 0; if ((style & DWT.SINGLE) !is 0) { NSTextField widget = cast(NSTextField) view; NSRect rect = NSRect (); rect.width = rect.height = Float.MAX_VALUE; NSSize size = widget.cell ().cellSizeForBounds (rect); width = cast(int)Math.ceil (size.width); height = cast(int)Math.ceil (size.height); } else { NSTextView widget = cast(NSTextView) view; NSSize oldSize; NSTextContainer textContainer = widget.textContainer (); if ((style & DWT.WRAP) !is 0) { widget.setHorizontallyResizable (true); textContainer.setWidthTracksTextView (false); oldSize = textContainer.containerSize (); NSSize csize = NSSize (); csize.width = wHint !is DWT.DEFAULT ? wHint : Float.MAX_VALUE; csize.height = hHint !is DWT.DEFAULT ? hHint : Float.MAX_VALUE; textContainer.setContainerSize (csize); } NSRect oldRect = widget.frame (); widget.sizeToFit (); NSRect newRect = widget.frame (); widget.setFrame (oldRect); if ((style & DWT.WRAP) !is 0) { widget.setHorizontallyResizable (false); textContainer.setWidthTracksTextView (true); textContainer.setContainerSize (oldSize); } width = cast(int)(newRect.width + 1); height = cast(int)(newRect.height + 1); } if (width <= 0) width = DEFAULT_WIDTH; if (height <= 0) height = DEFAULT_HEIGHT; if (wHint !is DWT.DEFAULT) width = wHint; if (hHint !is DWT.DEFAULT) height = hHint; Rectangle trim = computeTrim (0, 0, width, height); width = trim.width; height = trim.height; return new Point (width, height); } /** * Copies the selected text. * <p> * The current selection is copied to the clipboard. * </p> * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void copy () { checkWidget (); if ((style & DWT.SINGLE) !is 0) { Point selection = getSelection (); if (selection.x is selection.y) return; copyToClipboard (getEditText (selection.x, selection.y - 1)); } else { NSText text = cast(NSText) view; if (text.selectedRange ().length is 0) return; text.copy (null); } } void createHandle () { if ((style & DWT.SINGLE) !is 0) { NSTextField widget; if ((style & DWT.PASSWORD) !is 0) { widget = cast(NSTextField) (new SWTSecureTextField ()).alloc (); } else if ((style & DWT.SEARCH) !is 0) { widget = cast(NSTextField) (new SWTSearchField ()).alloc (); } else { widget = cast(NSTextField) (new SWTTextField ()).alloc (); } widget.initWithFrame (NSRect ()); widget.setSelectable (true); widget.setEditable((style & DWT.READ_ONLY) is 0); if ((style & DWT.BORDER) is 0) { widget.setFocusRingType (OS.NSFocusRingTypeNone); widget.setBordered (false); } NSTextAlignment align_ = OS.NSLeftTextAlignment; if ((style & DWT.CENTER) !is 0) align_ = OS.NSCenterTextAlignment; if ((style & DWT.RIGHT) !is 0) align_ = OS.NSRightTextAlignment; widget.setAlignment (align_); // widget.setTarget(widget); // widget.setAction(OS.sel_sendSelection); view = widget; } else { NSScrollView scrollWidget = cast(NSScrollView) (new SWTScrollView ()).alloc (); scrollWidget.initWithFrame (NSRect ()); scrollWidget.setHasVerticalScroller ((style & DWT.VERTICAL) !is 0); scrollWidget.setHasHorizontalScroller ((style & DWT.HORIZONTAL) !is 0); scrollWidget.setAutoresizesSubviews (true); if ((style & DWT.BORDER) !is 0) scrollWidget.setBorderType (OS.NSBezelBorder); NSTextView widget = cast(NSTextView) (new SWTTextView ()).alloc (); widget.initWithFrame (NSRect ()); widget.setEditable ((style & DWT.READ_ONLY) is 0); NSSize size = NSSize (); size.width = size.height = Float.MAX_VALUE; widget.setMaxSize (size); widget.setAutoresizingMask (OS.NSViewWidthSizable | OS.NSViewHeightSizable); if ((style & DWT.WRAP) is 0) { NSTextContainer textContainer = widget.textContainer (); widget.setHorizontallyResizable (true); textContainer.setWidthTracksTextView (false); NSSize csize = NSSize (); csize.width = csize.height = Float.MAX_VALUE; textContainer.setContainerSize (csize); } NSTextAlignment align_ = OS.NSLeftTextAlignment; if ((style & DWT.CENTER) !is 0) align_ = OS.NSCenterTextAlignment; if ((style & DWT.RIGHT) !is 0) align_ = OS.NSRightTextAlignment; widget.setAlignment (align_); // widget.setTarget(widget); // widget.setAction(OS.sel_sendSelection); widget.setRichText (false); widget.setDelegate(widget); view = widget; scrollView = scrollWidget; } } void createWidget () { super.createWidget (); doubleClick = true; message = ""; } /** * Cuts the selected text. * <p> * The current selection is first copied to the * clipboard and then deleted from the widget. * </p> * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void cut () { checkWidget (); if ((style & DWT.READ_ONLY) !is 0) return; bool cut = true; wchar [] oldText = null; Point oldSelection = getSelection (); if (hooks (DWT.Verify) || filters (DWT.Verify)) { if (oldSelection.x !is oldSelection.y) { oldText = getEditText (oldSelection.x, oldSelection.y - 1); wchar[] newText = verifyText ("", oldSelection.x, oldSelection.y, null); if (newText is null) return; if (newText.length () !is 0) { copyToClipboard (oldText); if ((style & DWT.SINGLE) !is 0) { insertEditText (newText); } else { NSTextView widget = cast(NSTextView) view; widget.replaceCharactersInRange (widget.selectedRange (), NSString.stringWith16 (newText)); } cut = false; } } } if (cut) { if ((style & DWT.SINGLE) !is 0) { if (oldText is null) oldText = getEditText (oldSelection.x, oldSelection.y - 1); copyToClipboard (oldText); insertEditText (""); } else { (cast(NSTextView) view).cut (null); } } Point newSelection = getSelection (); if (!cut || !oldSelection.equals (newSelection)) sendEvent (DWT.Modify); } Color defaultBackground () { return display.getSystemColor (DWT.COLOR_LIST_BACKGROUND); } Color defaultForeground () { return display.getSystemColor (DWT.COLOR_LIST_FOREGROUND); } void deregister() { super.deregister(); if ((style & DWT.SINGLE) !is 0) { display.removeWidget((cast(NSControl)view).cell()); } } bool dragDetect (int x, int y, bool filter, bool [] consume) { if (filter) { Point selection = getSelection (); if (selection.x !is selection.y) { int position = getPosition (x, y); if (selection.x <= position && position < selection.y) { if (super.dragDetect (x, y, filter, consume)) { if (consume !is null) consume [0] = true; return true; } } } return false; } return super.dragDetect (x, y, filter, consume); } /** * Returns the line number of the caret. * <p> * The line number of the caret is returned. * </p> * * @return the line number * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public int getCaretLineNumber () { checkWidget (); if ((style & DWT.SINGLE) !is 0) return 0; return (getTopPixel () + getCaretLocation ().y) / getLineHeight (); } /** * Returns a point describing the receiver's location relative * to its parent (or its display if its parent is null). * <p> * The location of the caret is returned. * </p> * * @return a point, the location of the caret * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Point getCaretLocation () { checkWidget (); if ((style & DWT.SINGLE) !is 0) { //TODO - caret location for unicode text return new Point (0, 0); } // NSText // NSRange range = (cast(NSTextView)view).selectedRange(); return null; } /** * Returns the character position of the caret. * <p> * Indexing is zero based. * </p> * * @return the position of the caret * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public int getCaretPosition () { checkWidget (); if ((style & DWT.SINGLE) !is 0) { //TODO return 0; } else { NSRange range = (cast(NSTextView)view).selectedRange(); return cast(int)/*64*/range.location; } } /** * Returns the number of characters. * * @return number of characters in the widget * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public int getCharCount () { checkWidget (); if ((style & DWT.SINGLE) !is 0) { return cast(int)/*64*/(new NSCell ((cast(NSControl) view).cell ())).title ().length (); } else { return cast(int)/*64*/(cast(NSTextView) view).textStorage ().length (); } } /** * Returns the double click enabled flag. * <p> * The double click flag enables or disables the * default action of the text widget when the user * double clicks. * </p> * * @return whether or not double click is enabled * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public bool getDoubleClickEnabled () { checkWidget (); return doubleClick; } /** * Returns the echo character. * <p> * The echo character is the character that is * displayed when the user enters text or the * text is changed by the programmer. * </p> * * @return the echo character * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #setEchoChar */ public char getEchoChar () { checkWidget (); return toChar(echoCharacter); } /** * Returns the editable state. * * @return whether or not the receiver is editable * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public bool getEditable () { checkWidget (); return (style & DWT.READ_ONLY) is 0; } wchar [] getEditText () { NSString str = null; if ((style & DWT.SINGLE) !is 0) { str = (new NSTextFieldCell ((cast(NSTextField) view).cell ())).title (); } else { str = (cast(NSTextView)view).textStorage().string(); } NSUInteger length_ = str.length (); wchar [] buffer = new wchar [length_]; if (hiddenText !is null) { hiddenText.getChars (0, length_, buffer, 0); } else { NSRange range = NSRange (); range.length = length_; str.getCharacters (buffer.ptr, range); } return buffer;//.fromString16(); } wchar [] getEditText (int start, int end) { NSString str = null; if ((style & DWT.SINGLE) !is 0) { str = (new NSTextFieldCell ((cast(NSTextField) view).cell ())).title (); } else { str = (cast(NSTextView)view).textStorage().string(); } int length = cast(int)/*64*/str.length (); end = Math.min (end, length - 1); if (start > end) return new wchar [0]; start = Math.max (0, start); NSRange range = NSRange (); range.location = start; range.length = Math.max (0, end - start + 1); wchar [] buffer = new wchar [range.length]; if (hiddenText !is null) { hiddenText.getChars (cast(int)/*64*/range.location, cast(int)/*64*/(range.location + range.length), buffer, 0); } else { str.getCharacters (buffer.ptr, range); } return buffer;//.fromString16(); } /** * Returns the number of lines. * * @return the number of lines in the widget * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public int getLineCount () { checkWidget (); if ((style & DWT.SINGLE) !is 0) return 1; return cast(int)/*64*/(cast(NSTextView) view).textStorage ().paragraphs ().count (); } /** * Returns the line delimiter. * * @return a string that is the line delimiter * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #DELIMITER */ public String getLineDelimiter () { checkWidget (); return DELIMITER.fromString16(); } /** * Returns the height of a line. * * @return the height of a row of text * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public int getLineHeight () { checkWidget (); //TODO return 16; } /** * Returns the orientation of the receiver, which will be one of the * constants <code>DWT.LEFT_TO_RIGHT</code> or <code>DWT.RIGHT_TO_LEFT</code>. * * @return the orientation style * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 2.1.2 */ public int getOrientation () { checkWidget (); return style & (DWT.LEFT_TO_RIGHT | DWT.RIGHT_TO_LEFT); } /** * Returns the widget message. When the widget is created * with the style <code>DWT.SEARCH</code>, the message text * is displayed as a hint for the user, indicating the * purpose of the field. * <p> * Note: This operation is a <em>HINT</em> and is not * supported on platforms that do not have this concept. * </p> * * @return the widget message * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.3 */ public String getMessage () { checkWidget (); return message.fromString16(); } int getPosition (int x, int y) { // checkWidget (); //TODO return 0; } /*public*/ int getPosition (Point point) { checkWidget (); if (point is null) error (DWT.ERROR_NULL_ARGUMENT); return getPosition (point.x, point.y); } /** * Returns a <code>Point</code> whose x coordinate is the * character position representing the start of the selected * text, and whose y coordinate is the character position * representing the end of the selection. An "empty" selection * is indicated by the x and y coordinates having the same value. * <p> * Indexing is zero based. The range of a selection is from * 0..N where N is the number of characters in the widget. * </p> * * @return a point representing the selection start and end * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Point getSelection () { checkWidget (); if ((style & DWT.SINGLE) !is 0) { if (selectionRange is null) { NSString str = (new NSTextFieldCell ((cast(NSTextField) view).cell ())).title (); return new Point(cast(int)/*64*/str.length (), cast(int)/*64*/str.length ()); } return new Point (cast(int)/*64*/selectionRange.location, cast(int)/*64*/(selectionRange.location + selectionRange.length)); } else { NSTextView widget = cast(NSTextView) view; NSRange range = widget.selectedRange (); return new Point (cast(int)/*64*/range.location, cast(int)/*64*/(range.location + range.length)); } } /** * Returns the number of selected characters. * * @return the number of selected characters. * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public int getSelectionCount () { checkWidget (); if ((style & DWT.SINGLE) !is 0) { return selectionRange !is null ? cast(int)/*64*/selectionRange.length : 0; } else { NSTextView widget = cast(NSTextView) view; NSRange range = widget.selectedRange (); return cast(int)/*64*/range.length; } } /** * Gets the selected text, or an empty string if there is no current selection. * * @return the selected text * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public String getSelectionText () { checkWidget (); if ((style & DWT.SINGLE) !is 0) { Point selection = getSelection (); if (selection.x is selection.y) return ""; return new_String (getEditText (selection.x, selection.y - 1).fromString16()); } else { NSTextView widget = cast(NSTextView) view; NSRange range = widget.selectedRange (); NSString str = widget.textStorage ().string (); wchar[] buffer = new wchar [range.length]; str.getCharacters (buffer.ptr, range); return buffer.fromString16(); } } /** * Returns the number of tabs. * <p> * Tab stop spacing is specified in terms of the * space (' ') character. The width of a single * tab stop is the pixel width of the spaces. * </p> * * @return the number of tab characters * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public int getTabs () { checkWidget (); return tabs; } /** * Returns the widget text. * <p> * The text for a text widget is the characters in the widget, or * an empty string if this has never been set. * </p> * * @return the widget text * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public String getText () { checkWidget (); NSString str; if ((style & DWT.SINGLE) !is 0) { return new_String (getEditText ().fromString16()); } else { str = (cast(NSTextView)view).textStorage ().string (); } return str.getString(); } private wchar[] getText16 () { checkWidget (); NSString str; if ((style & DWT.SINGLE) !is 0) { return getEditText ().dup; } else { str = (cast(NSTextView)view).textStorage ().string (); } return str.getString16(); } /** * Returns a range of text. Returns an empty string if the * start of the range is greater than the end. * <p> * Indexing is zero based. The range of * a selection is from 0..N-1 where N is * the number of characters in the widget. * </p> * * @param start the start of the range * @param end the end of the range * @return the range of text * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public String getText (int start, int end) { checkWidget (); if (!(start <= end && 0 <= end)) return ""; //$NON-NLS-1$ if ((style & DWT.SINGLE) !is 0) { return new_String (getEditText (start, end).fromString16()); } NSTextStorage storage = (cast(NSTextView) view).textStorage (); end = Math.min (end, cast(int)/*64*/storage.length () - 1); if (start > end) return ""; //$NON-NLS-1$ start = Math.max (0, start); NSRange range = NSRange (); range.location = start; range.length = end - start + 1; NSAttributedString substring = storage.attributedSubstringFromRange (range); NSString string = substring.string (); return string.getString(); } /** * Returns the maximum number of characters that the receiver is capable of holding. * <p> * If this has not been changed by <code>setTextLimit()</code>, * it will be the constant <code>Text.LIMIT</code>. * </p> * * @return the text limit * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #LIMIT */ public int getTextLimit () { checkWidget (); return textLimit; } /** * Returns the zero-relative index of the line which is currently * at the top of the receiver. * <p> * This index can change when lines are scrolled or new lines are added or removed. * </p> * * @return the index of the top line * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public int getTopIndex () { checkWidget (); if ((style & DWT.SINGLE) !is 0) return 0; return getTopPixel () / getLineHeight (); } /** * Returns the top pixel. * <p> * The top pixel is the pixel position of the line * that is currently at the top of the widget. On * some platforms, a text widget can be scrolled by * pixels instead of lines so that a partial line * is displayed at the top of the widget. * </p><p> * The top pixel changes when the widget is scrolled. * The top pixel does not include the widget trimming. * </p> * * @return the pixel position of the top line * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public int getTopPixel () { checkWidget (); if ((style & DWT.SINGLE) !is 0) return 0; //TODO return 0; } /** * Inserts a string. * <p> * The old selection is replaced with the new text. * </p> * * @param string the string * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the string is <code>null</code></li> * </ul> * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void insert (String stri) { wchar[] string = stri.toString16(); checkWidget (); //if (string is null) error (DWT.ERROR_NULL_ARGUMENT); if (hooks (DWT.Verify) || filters (DWT.Verify)) { Point selection = getSelection (); string = verifyText (string, selection.x, selection.y, null); if (string is null) return; } if ((style & DWT.SINGLE) !is 0) { insertEditText (string); } else { NSString str = NSString.stringWith16 (string); NSTextView widget = cast(NSTextView) view; NSRange range = widget.selectedRange (); widget.textStorage ().replaceCharactersInRange (range, str); } if (string.length () !is 0) sendEvent (DWT.Modify); } void insertEditText (wchar[] string) { int length_ = string.length (); Point selection = getSelection (); if (hasFocus () && hiddenText is null) { if (textLimit !is LIMIT) { int charCount = getCharCount(); if (charCount - (selection.y - selection.x) + length_ > textLimit) { length_ = textLimit - charCount + (selection.y - selection.x); } } wchar [] buffer = new wchar [length_]; string.getChars (0, buffer.length, buffer, 0); NSString nsstring = NSString.stringWithCharacters (buffer.ptr, buffer.length); NSText editor = (cast(NSTextField) view).currentEditor (); editor.replaceCharactersInRange (editor.selectedRange (), nsstring); selectionRange = null; } else { wchar[] oldText = getText16 (); if (textLimit !is LIMIT) { int charCount = oldText.length (); if (charCount - (selection.y - selection.x) + length_ > textLimit) { string = string.substring(0, textLimit - charCount + (selection.y - selection.x)); } } wchar[] newText = oldText.substring (0, selection.x) ~ string ~ oldText.substring (selection.y); setEditText (newText); setSelection (selection.x + string.length ()); } } /** * Pastes text from clipboard. * <p> * The selected text is deleted from the widget * and new text inserted from the clipboard. * </p> * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void paste () { checkWidget (); if ((style & DWT.READ_ONLY) !is 0) return; bool paste = true; wchar[] oldText = null; if (hooks (DWT.Verify) || filters (DWT.Verify)) { oldText = getClipboardText16 (); if (oldText !is null) { Point selection = getSelection (); wchar[] newText = verifyText (oldText, selection.x, selection.y, null); if (newText is null) return; if (!newText.equals (oldText)) { if ((style & DWT.SINGLE) !is 0) { insertEditText (newText); } else { NSTextView textView = cast(NSTextView) view; textView.replaceCharactersInRange (textView.selectedRange (), NSString.stringWith16 (newText)); } paste = false; } } } if (paste) { if ((style & DWT.SINGLE) !is 0) { if (oldText is null) oldText = getClipboardText16 (); insertEditText (oldText); } else { //TODO check text limit (cast(NSTextView) view).paste (null); } } sendEvent (DWT.Modify); } void register() { super.register(); if ((style & DWT.SINGLE) !is 0) { display.addWidget((cast(NSControl)view).cell(), this); } } void releaseWidget () { super.releaseWidget (); hiddenText = message = null; selectionRange = null; } /** * Removes the listener from the collection of listeners who will * be notified when the receiver's text is modified. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see ModifyListener * @see #addModifyListener */ public void removeModifyListener (ModifyListener listener) { checkWidget (); if (listener is null) error (DWT.ERROR_NULL_ARGUMENT); if (eventTable is null) return; eventTable.unhook (DWT.Modify, listener); } /** * Removes the listener from the collection of listeners who will * be notified when the control is selected by the user. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see SelectionListener * @see #addSelectionListener */ public void removeSelectionListener(SelectionListener listener) { checkWidget (); if (listener is null) error (DWT.ERROR_NULL_ARGUMENT); if (eventTable is null) return; eventTable.unhook (DWT.Selection, listener); eventTable.unhook (DWT.DefaultSelection,listener); } /** * Removes the listener from the collection of listeners who will * be notified when the control is verified. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see VerifyListener * @see #addVerifyListener */ public void removeVerifyListener (VerifyListener listener) { checkWidget (); if (listener is null) error (DWT.ERROR_NULL_ARGUMENT); if (eventTable is null) return; eventTable.unhook (DWT.Verify, listener); } /** * Selects all the text in the receiver. * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void selectAll () { checkWidget (); if ((style & DWT.SINGLE) !is 0) { setSelection (0, getCharCount ()); } else { (cast(NSTextView) view).selectAll (null); } } bool sendKeyEvent (NSEvent nsEvent, int type) { bool result = super.sendKeyEvent (nsEvent, type); if (!result) return result; if (type !is DWT.KeyDown) return result; int stateMask = 0; NSUInteger modifierFlags = nsEvent.modifierFlags(); if ((modifierFlags & OS.NSAlternateKeyMask) !is 0) stateMask |= DWT.ALT; if ((modifierFlags & OS.NSShiftKeyMask) !is 0) stateMask |= DWT.SHIFT; if ((modifierFlags & OS.NSControlKeyMask) !is 0) stateMask |= DWT.CONTROL; if ((modifierFlags & OS.NSCommandKeyMask) !is 0) stateMask |= DWT.COMMAND; if (stateMask is DWT.COMMAND) { ushort keyCode = nsEvent.keyCode (); switch (keyCode) { case 7: /* X */ cut (); return false; case 8: /* C */ copy (); return false; case 9: /* V */ paste (); return false; default: } } if ((style & DWT.SINGLE) !is 0) { ushort keyCode = nsEvent.keyCode (); switch (keyCode) { case 76: /* KP Enter */ case 36: /* Return */ postEvent (DWT.DefaultSelection); default: } } if ((stateMask & DWT.COMMAND) !is 0) return result; wchar[] oldText = ""; int charCount = getCharCount (); Point selection = getSelection (); int start = selection.x, end = selection.y; ushort keyCode = nsEvent.keyCode (); NSString characters = nsEvent.charactersIgnoringModifiers(); wchar character = characters.characterAtIndex(0); switch (keyCode) { case 51: /* Backspace */ if (start is end) { if (start is 0) return true; start = Math.max (0, start - 1); } break; case 117: /* Delete */ if (start is end) { if (start is charCount) return true; end = Math.min (end + 1, charCount); } break; case 36: /* Return */ if ((style & DWT.SINGLE) !is 0) return true; oldText = DELIMITER; break; default: if (character !is '\t' && character < 0x20) return true; oldText = new_String ([character]); } wchar[] newText = verifyText (oldText, start, end, nsEvent); //if (newText is null) return false; // DWT extension, empty strings could be null if (charCount - (end - start) + newText.length () > textLimit) { return false; } result = newText == oldText; // DWT extension, Use "==" instead of "is" because newText can be null if (newText != oldText || hiddenText !is null) { if ((style & DWT.SINGLE) !is 0) { insertEditText (newText); } else { NSString str = NSString.stringWith16 (newText); NSTextView widget = cast(NSTextView) view; NSRange range = widget.selectedRange (); widget.textStorage ().replaceCharactersInRange (range, str); } if (newText.length () !is 0) sendEvent (DWT.Modify); } return result; } void setBackground (Carbon.CGFloat [] color) { NSColor nsColor; if (color is null) { return; // TODO reset to OS default } else { nsColor = NSColor.colorWithDeviceRed (color [0], color [1], color [2], 1); } if ((style & DWT.SINGLE) !is 0) { (cast(NSTextField) view).setBackgroundColor (nsColor); } else { (cast(NSTextView) view).setBackgroundColor (nsColor); } } /** * Sets the double click enabled flag. * <p> * The double click flag enables or disables the * default action of the text widget when the user * double clicks. * </p><p> * Note: This operation is a hint and is not supported on * platforms that do not have this concept. * </p> * * @param doubleClick the new double click flag * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setDoubleClickEnabled (bool doubleClick) { checkWidget (); this.doubleClick = doubleClick; } /** * Sets the echo character. * <p> * The echo character is the character that is * displayed when the user enters text or the * text is changed by the programmer. Setting * the echo character to '\0' clears the echo * character and redraws the original text. * If for any reason the echo character is invalid, * or if the platform does not allow modification * of the echo character, the default echo character * for the platform is used. * </p> * * @param echo the new echo character * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setEchoChar (char echo) { checkWidget (); if ((style & DWT.MULTI) !is 0) return; // if (txnObject is 0) { // if ((style & DWT.PASSWORD) is 0) { // Point selection = getSelection (); // String text = getText (); // echoCharacter = echo; // setEditText (text); // setSelection (selection); // } // } else { // OS.TXNEchoMode (txnObject, echo, OS.kTextEncodingMacUnicode, echo !is '\0'); // } echoCharacter = toWChar(echo); } /** * Sets the editable state. * * @param editable the new editable state * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setEditable (bool editable) { checkWidget (); if (editable) { style &= ~DWT.READ_ONLY; } else { style |= DWT.READ_ONLY; } if ((style & DWT.SINGLE) !is 0) { (cast(NSTextField) view).setEditable (editable); } else { (cast(NSTextView) view).setEditable (editable); } } void setEditText (wchar[] string) { wchar [] buffer; if ((style & DWT.PASSWORD) is 0 && echoCharacter !is '\0') { hiddenText = string; buffer = new wchar [Math.min(hiddenText.length (), textLimit)]; for (int i = 0; i < buffer.length; i++) buffer [i] = echoCharacter; } else { hiddenText = null; buffer = new wchar [Math.min(string.length (), textLimit)]; string.getChars (0, buffer.length, buffer, 0); } NSString nsstring = NSString.stringWithCharacters (buffer.ptr, buffer.length); (new NSCell ((cast(NSTextField) view).cell ())).setTitle (nsstring); selectionRange = null; } void setFont(NSFont font) { if ((style & DWT.MULTI) !is 0) { (cast(NSTextView) view).setFont (font); return; } super.setFont (font); } void setForeground (Carbon.CGFloat [] color) { NSColor nsColor; if (color is null) { return; // TODO reset to OS default } else { nsColor = NSColor.colorWithDeviceRed (color [0], color [1], color [2], 1); } if ((style & DWT.SINGLE) !is 0) { (cast(NSTextField) view).setTextColor (nsColor); } else { (cast(NSTextView) view).setTextColor (nsColor); } } /** * Sets the orientation of the receiver, which must be one * of the constants <code>DWT.LEFT_TO_RIGHT</code> or <code>DWT.RIGHT_TO_LEFT</code>. * <p> * Note: This operation is a hint and is not supported on * platforms that do not have this concept. * </p> * * @param orientation new orientation style * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 2.1.2 */ public void setOrientation (int orientation) { checkWidget (); } /** * Sets the widget message. When the widget is created * with the style <code>DWT.SEARCH</code>, the message text * is displayed as a hint for the user, indicating the * purpose of the field. * <p> * Note: This operation is a <em>HINT</em> and is not * supported on platforms that do not have this concept. * </p> * * @param message the new message * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the message is null</li> * </ul> * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.3 */ public void setMessage (String message) { checkWidget (); //if (message is null) error (DWT.ERROR_NULL_ARGUMENT); this.message = message.toString16(); // if ((style & DWT.SEARCH) !is 0) { // char [] buffer = new char [message.length ()]; // message.getChars (0, buffer.length, buffer, 0); // int ptr = OS.CFStringCreateWithCharacters (OS.kCFAllocatorDefault, buffer, buffer.length); // if (ptr is 0) error (DWT.ERROR_CANNOT_SET_TEXT); // OS.HISearchFieldSetDescriptiveText (handle, ptr); // OS.CFRelease (ptr); // } } /** * Sets the selection. * <p> * Indexing is zero based. The range of * a selection is from 0..N where N is * the number of characters in the widget. * </p><p> * Text selections are specified in terms of * caret positions. In a text widget that * contains N characters, there are N+1 caret * positions, ranging from 0..N. This differs * from other functions that address character * position such as getText () that use the * regular array indexing rules. * </p> * * @param start new caret position * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setSelection (int start) { checkWidget (); setSelection (start, start); } /** * Sets the selection to the range specified * by the given start and end indices. * <p> * Indexing is zero based. The range of * a selection is from 0..N where N is * the number of characters in the widget. * </p><p> * Text selections are specified in terms of * caret positions. In a text widget that * contains N characters, there are N+1 caret * positions, ranging from 0..N. This differs * from other functions that address character * position such as getText () that use the * usual array indexing rules. * </p> * * @param start the start of the range * @param end the end of the range * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setSelection (int start, int end) { checkWidget (); if ((style & DWT.SINGLE) !is 0) { NSString str = (new NSCell ((cast(NSTextField) view).cell ())).title (); int length = cast(int)/*64*/str.length (); int selStart = Math.min (Math.max (Math.min (start, end), 0), length); int selEnd = Math.min (Math.max (Math.max (start, end), 0), length); selectionRangeStruct = NSRange (); selectionRange = &selectionRangeStruct; selectionRange.location = selStart; selectionRange.length = selEnd - selStart; if (this is display.getFocusControl ()) { NSText editor = view.window ().fieldEditor (false, view); editor.setSelectedRange (selectionRangeStruct); } } else { int length = cast(int)/*64*/(cast(NSTextView) view).textStorage ().length (); int selStart = Math.min (Math.max (Math.min (start, end), 0), length); int selEnd = Math.min (Math.max (Math.max (start, end), 0), length); NSRange range = NSRange (); range.location = selStart; range.length = selEnd - selStart; (cast(NSTextView) view).setSelectedRange (range); } } /** * Sets the selection to the range specified * by the given point, where the x coordinate * represents the start index and the y coordinate * represents the end index. * <p> * Indexing is zero based. The range of * a selection is from 0..N where N is * the number of characters in the widget. * </p><p> * Text selections are specified in terms of * caret positions. In a text widget that * contains N characters, there are N+1 caret * positions, ranging from 0..N. This differs * from other functions that address character * position such as getText () that use the * usual array indexing rules. * </p> * * @param selection the point * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the point is null</li> * </ul> * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setSelection (Point selection) { checkWidget (); if (selection is null) error (DWT.ERROR_NULL_ARGUMENT); setSelection (selection.x, selection.y); } /** * Sets the number of tabs. * <p> * Tab stop spacing is specified in terms of the * space (' ') character. The width of a single * tab stop is the pixel width of the spaces. * </p> * * @param tabs the number of tabs * * </ul> * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setTabs (int tabs) { checkWidget (); if (this.tabs is tabs) return; // if (txnObject is 0) return; // this.tabs = tabs; // TXNTab tab = new TXNTab (); // tab.value = cast(short) (textExtent (new char[]{' '}, 0).x * tabs); // int [] tags = new int [] {OS.kTXNTabSettingsTag}; // int [] datas = new int [1]; // OS.memmove (datas, tab, TXNTab.sizeof); // OS.TXNSetTXNObjectControls (txnObject, false, tags.length, tags, datas); } /** * Sets the contents of the receiver to the given string. If the receiver has style * SINGLE and the argument contains multiple lines of text, the result of this * operation is undefined and may vary from platform to platform. * * @param string the new text * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the string is null</li> * </ul> * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setText (String stri) { wchar[] string = stri.toString16(); checkWidget (); //if (string is null) error (DWT.ERROR_NULL_ARGUMENT); if (hooks (DWT.Verify) || filters (DWT.Verify)) { string = verifyText (string, 0, getCharCount (), null); if (string is null) return; } if ((style & DWT.SINGLE) !is 0) { setEditText (string); } else { NSString str = NSString.stringWith16 (string); (cast(NSTextView) view).setString (str); } sendEvent (DWT.Modify); } /** * Sets the maximum number of characters that the receiver * is capable of holding to be the argument. * <p> * Instead of trying to set the text limit to zero, consider * creating a read-only text widget. * </p><p> * To reset this value to the default, use <code>setTextLimit(Text.LIMIT)</code>. * Specifying a limit value larger than <code>Text.LIMIT</code> sets the * receiver's limit to <code>Text.LIMIT</code>. * </p> * * @param limit new text limit * * @exception IllegalArgumentException <ul> * <li>ERROR_CANNOT_BE_ZERO - if the limit is zero</li> * </ul> * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #LIMIT */ public void setTextLimit (int limit) { checkWidget (); if (limit is 0) error (DWT.ERROR_CANNOT_BE_ZERO); textLimit = limit; } /** * Sets the zero-relative index of the line which is currently * at the top of the receiver. This index can change when lines * are scrolled or new lines are added and removed. * * @param index the index of the top item * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setTopIndex (int index) { checkWidget (); if ((style & DWT.SINGLE) !is 0) return; //TODO no working // NSTextView widget = cast(NSTextView) view; // NSRange range = NSRange (); // NSRect rect = widget.firstRectForCharacterRange (range); // view.scrollRectToVisible (rect); } /** * Shows the selection. * <p> * If the selection is already showing * in the receiver, this method simply returns. Otherwise, * lines are scrolled until the selection is visible. * </p> * * @exception DWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void showSelection () { checkWidget (); if ((style & DWT.SINGLE) !is 0) { setSelection (getSelection ()); } else { NSTextView widget = cast(NSTextView) view; widget.scrollRangeToVisible (widget.selectedRange ()); } } void textViewDidChangeSelection(objc.id id, objc.SEL sel, objc.id aNotification) { NSNotification notification = new NSNotification (aNotification); NSText editor = new NSText (notification.object ().id); selectionRangeStruct = editor.selectedRange (); selectionRange = &selectionRangeStruct; } void textDidChange (objc.id id, objc.SEL sel, objc.id aNotification) { postEvent (DWT.Modify); } NSRange textView_willChangeSelectionFromCharacterRange_toCharacterRange (objc.id id, objc.SEL sel, objc.id aTextView, objc.id oldSelectedCharRange, objc.id newSelectedCharRange) { /* * If the selection is changing as a result of the receiver getting focus * then return the receiver's last selection range, otherwise the full * text will be automatically selected. */ if (receivingFocus && selectionRange !is null) return selectionRangeStruct; /* allow the selection change to proceed */ NSRange result = NSRange (); OS.memmove(&result, newSelectedCharRange, NSRange.sizeof); return result; } int traversalCode (int key, NSEvent theEvent) { int bits = super.traversalCode (key, theEvent); if ((style & DWT.READ_ONLY) !is 0) return bits; if ((style & DWT.MULTI) !is 0) { bits &= ~DWT.TRAVERSE_RETURN; if (key is 48 /* Tab */ && theEvent !is null) { NSUInteger modifiers = theEvent.modifierFlags (); bool next = (modifiers & OS.NSShiftKeyMask) is 0; if (next && (modifiers & OS.NSControlKeyMask) is 0) { bits &= ~(DWT.TRAVERSE_TAB_NEXT | DWT.TRAVERSE_TAB_PREVIOUS); } } } return bits; } wchar[] verifyText (wchar[] string, int start, int end, NSEvent keyEvent) { Event event = new Event (); if (keyEvent !is null) setKeyState(event, DWT.MouseDown, keyEvent); event.text = string.fromString16(); event.start = start; event.end = end; /* * It is possible (but unlikely), that application * code could have disposed the widget in the verify * event. If this happens, answer null to cancel * the operation. */ sendEvent (DWT.Verify, event); if (!event.doit || isDisposed ()) return null; return event.text.toString16(); } }
<!-- 新增alert 元件進來--> <app-alert *ngIf="showAlert" [color]="alertColor"> {{ alertMsg }} </app-alert> <!-- Registration Form --> <!--使用ngsubmit event ,來避免頁面刷新,跟e.preventDefault()--> <form [formGroup]="registerForm" (ngSubmit)="register()"> <!-- Name --> <div class="mb-3"> <label class="inline-block mb-2">Name</label> <app-input [control]="name" placeholder="輸入名稱"></app-input> </div> <!-- Email --> <div class="mb-3"> <label class="inline-block mb-2">Email</label> <app-input [control]="email" type="email" placeholder="輸入電子郵件" ></app-input> </div> <!-- Age --> <div class="mb-3"> <label class="inline-block mb-2">Age</label> <app-input [control]="age" type="number" placeholder="輸入年齡"></app-input> </div> <!-- Password --> <div class="mb-3"> <label class="inline-block mb-2">Password</label> <app-input [control]="password" type="password" placeholder="輸入密碼" ></app-input> </div> <!-- Confirm Password --> <div class="mb-3"> <label class="inline-block mb-2">Confirm Password</label> <app-input [control]="confirm_password" type="password" placeholder="填寫密碼" ></app-input> </div> <!-- Phone Number --> <div class="mb-3"> <label class="inline-block mb-2">Phone Number</label> <app-input [control]="phoneNumber" placeholder="輸入手機" format="0000-000-000" ></app-input> </div> <button type="submit" class="block w-full bg-indigo-400 text-white py-1.5 px-3 rounded transition hover:bg-indigo-500 disabled:opacity-50 disabled:bg-indigo-400" [disabled]="registerForm.invalid || inSubmission" > Submit </button> </form>
#!/bin/bash # Библиотека цветов https://wiki.archlinux.org/index.php/Bash/Prompt_customization_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9) # Функции и прочие примеры http://dotshare.it/category/shells/bash/ # Цвета папок dircolors https://github.com/trapd00r/LS_COLORS # Сброс Color_Off='\e[0m' # Text Reset ## Обычные цвета Black='\e[0;30m' # Black Red='\e[0;31m' # Red Green='\e[0;32m' # Green Yellow='\e[0;33m' # Yellow Blue='\e[0;34m' # Blue Purple='\e[0;35m' # Purple Cyan='\e[0;36m' # Cyan White='\e[0;37m' # White ## Жирные BBlack='\e[1;30m' # Black BRed='\e[1;31m' # Red BGreen='\e[1;32m' # Green BYellow='\e[1;33m' # Yellow BBlue='\e[1;34m' # Blue BPurple='\e[1;35m' # Purple BCyan='\e[1;36m' # Cyan BWhite='\e[1;37m' # White ## Подчёркнутые UBlack='\e[4;30m' # Black URed='\e[4;31m' # Red UGreen='\e[4;32m' # Green UYellow='\e[4;33m' # Yellow UBlue='\e[4;34m' # Blue UPurple='\e[4;35m' # Purple UCyan='\e[4;36m' # Cyan UWhite='\e[4;37m' # White ## Фоновые белый шрифт On_WBlack='\e[40m' # Black On_WRed='\e[41m' # Red On_WGreen='\e[42m' # Green On_WYellow='\e[43m' # Yellow On_WBlue='\e[44m' # Blue On_WPurple='\e[45m' # Purple On_WCyan='\e[46m' # Cyan On_WWhite='\e[47m' # White ## Фоновые черный шрифт On_BBlack='\e[30;40m' # Black On_BRed='\e[30;41m' # Red On_BGreen='\e[30;42m' # Green On_BYellow='\e[30;43m' # Yellow On_BBlue='\e[30;44m' # Blue On_BPurple='\e[30;45m' # Purple On_BCyan='\e[30;46m' # Cyan On_BWhite='\e[30;47m' # White ## Высоко Интенсивные IBlack='\e[0;90m' # Black IRed='\e[0;91m' # Red IGreen='\e[0;92m' # Green IYellow='\e[0;93m' # Yellow IBlue='\e[0;94m' # Blue IPurple='\e[0;95m' # Purple ICyan='\e[0;96m' # Cyan IWhite='\e[0;97m' # White ## Жирные Высоко Интенсивные BIBlack='\e[1;90m' # Black BIRed='\e[1;91m' # Red BIGreen='\e[1;92m' # Green BIYellow='\e[1;93m' # Yellow BIBlue='\e[1;94m' # Blue BIPurple='\e[1;95m' # Purple BICyan='\e[1;96m' # Cyan BIWhite='\e[1;97m' # White ## Высоко Интенсивные фоновые On_IBlack='\e[0;100m' # Black On_IRed='\e[0;101m' # Red On_IGreen='\e[0;102m' # Green On_IYellow='\e[0;103m' # Yellow On_IBlue='\e[0;104m' # Blue On_IPurple='\e[0;105m' # Purple On_ICyan='\e[0;106m' # Cyan On_IWhite='\e[0;107m' # White # Задаем параметры истории и отображения HISTCONTROL=ignoreboth:erasedups PROMPT_COMMAND='history -a' HISTSIZE=100000 HISTFILESIZE=30000 shopt -s histappend # история команд будет добавлена в файл $HISTFILE shopt -s checkwinsize # обновляет переменные LINES shopt -s cmdhist # все строки многострочной команды как одна в истории shopt -s autocd # переход в каталог без cd unset MAILCHECK # отключить инфломацию о почте [ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)" # Автодополнение bash-completion if ! shopt -oq posix; then if [ -f /usr/share/bash-completion/bash_completion ]; then # shellcheck source=/dev/null . /usr/share/bash-completion/bash_completion elif [ -f /etc/bash_completion ]; then # shellcheck source=/dev/null . /etc/bash_completion fi fi # Пути до исполняемых файлов профиля ~/.bin if [ -d "$HOME/bin" ]; then PATH="$HOME/bin:$PATH" fi # Пути до исполняемых файлов профиля ~/.local/bin if [ -d "$HOME/.local/bin" ]; then PATH="$HOME/.local/bin:$PATH" fi # Включаем дополнительный файл алисов если такой есть ~/.bashrc_aliases if [ -f "$HOME/.bashrc_aliases" ]; then # shellcheck source=/dev/null . "$HOME/.bashrc_aliases" fi {% if env_ps1_style == "modern" %} # Проверка на консоль if [[ $(tty) =~ "tty" ]]; then # Конфигурация без значков parse_git_branch() { git branch 2>/dev/null | grep "\*" | awk '{print "» "$2" "}' } parse_git_status() { git_status=$(git status --porcelain --ignore-submodules 2>/dev/null | wc -l) if [[ "$git_status" != 0 ]]; then printf "(±%s)" "$git_status" fi } parse_git_push() { git_push=$(git status --long 2>/dev/null | grep -c 'git push') if [[ "$git_push" != 0 ]]; then printf "(×)" fi } show_git="${IPurple}\$(parse_git_branch)${IGreen}\$(parse_git_push)${IRed}\$(parse_git_status)${Color_Off}" # Задаем приглашение для пользователя и опеределение рута if [ "$(id -un)" = root ]; then PS1="┌ ${BRed}• \u ${Color_Off}${BYellow}• \H ${Color_Off}${BCyan}• \w ${Color_Off}${show_git}\n└─ > " else PS1="┌${Color_Off} ${BGreen}• \u ${Color_Off}${BYellow}• \H ${Color_Off}${BCyan}• \w ${Color_Off}${show_git}\n└─ > " fi else # Конфигурация со значками parse_git_branch() { git branch 2>/dev/null | grep "\*" | awk '{print "🛠 "$2" "}' } parse_git_status() { git_status=$(git status --porcelain --ignore-submodules 2>/dev/null | wc -l) if [[ "$git_status" != 0 ]]; then printf "(±%s)" "$git_status" fi } parse_git_push() { git_push=$(git status --long 2>/dev/null | grep -c 'git push') if [[ "$git_push" != 0 ]]; then printf "(✗)" fi } show_git="${BPurple}\$(parse_git_branch)${BGreen}\$(parse_git_push)${BRed}\$(parse_git_status)${Color_Off}" # Задаем приглашение для пользователя и опеределение рута if [ "$(id -un)" = root ]; then PS1="┌ ${BRed}🔓 \u ${Color_Off}${BYellow}💻 \H ${Color_Off}${BCyan}📂 \w ${Color_Off}${show_git}\n└─ ➤ " else PS1="┌${Color_Off} ${BGreen}🏠 \u ${Color_Off}${BYellow}💻 \H ${Color_Off}${BCyan}📂 \w ${Color_Off}${show_git}\n└─ ➤ " fi fi {% endif %} {% if env_ps1_style == "on_modern" %} # Конфигурация для локльного ПК с git parse_git_branch() { git branch 2>/dev/null | grep "\*" | awk '{print " 🛠 "$2" "}' } parse_git_status() { git_status=$(git status --porcelain --ignore-submodules 2>/dev/null | wc -l) if [[ "$git_status" != 0 ]]; then printf " ±%s " "$git_status" fi } parse_git_push() { git_push=$(git status --long 2>/dev/null | grep 'git push' | wc -l) if [[ "$git_push" != 0 ]]; then printf " ✗ " fi } show_git="${On_BPurple}\$(parse_git_branch)${On_BGreen}\$(parse_git_push)${On_BRed}\$(parse_git_status)${Color_Off}" # Задаем приглашение для пользователя и опеределение рута if [ "$(id -un)" = root ]; then PS1="┌ ${On_BRed} 🔓 \u ${Color_Off}${On_BYellow} 💻 \H ${Color_Off}${On_BCyan} 📂 \w ${Color_Off}${show_git}\n└─ ➤ " else PS1="${BGreen}┌${Color_Off} ${On_BGreen} 🏠 \u ${Color_Off}${On_BYellow} 💻 \H ${Color_Off}${On_BCyan} 📂 \w ${Color_Off}${show_git}\n${BGreen}└─ ➤${Color_Off} " fi {% endif %} {% if env_ps1_style == "simple" %} # Конфигурация без значков parse_git_branch() { git branch 2>/dev/null | grep "\*" | awk '{print "~>["$2"]"}' } parse_git_status() { git_status=$(git status --porcelain --ignore-submodules 2>/dev/null | wc -l) if [[ "$git_status" != 0 ]]; then printf "[±%s]" "$git_status" fi } parse_git_push() { git_push=$(git status --long 2>/dev/null | grep 'git push' | wc -l) if [[ "$git_push" != 0 ]]; then printf "[*]" fi } show_git="${IPurple}\$(parse_git_branch)${IGreen}\$(parse_git_push)${IRed}\$(parse_git_status)${Color_Off}" if [ "$(id -un)" = root ]; then PS1="┌─╼[${IRed}\u${Color_Off}]╾╼[${IYellow}\H${Color_Off}]╾╼[${ICyan}\w${Color_Off}]${show_git}\n└───╼ " else PS1="┌─╼[${IGreen}\u${Color_Off}]╾╼[${IYellow}\H${Color_Off}]╾╼[${ICyan}\w${Color_Off}]${show_git}\n└───╼ " fi {% endif %} {% if env_ps1_style == "shell" %} # Конфигурация imbicile/shell_colors parse_git_branch() { git branch 2>/dev/null | grep "\*" | awk '{print "["$2"]"}' } parse_git_status() { git_status=$(git status --porcelain --ignore-submodules 2>/dev/null | wc -l) if [[ "$git_status" != 0 ]]; then printf "[±%s]" "$git_status" fi } parse_git_push() { git_push=$(git status --long 2>/dev/null | grep -c 'git push') if [[ "$git_push" != 0 ]]; then printf "[*]" fi } show_git="${On_WPurple}\$(parse_git_branch)${On_WGreen}\$(parse_git_push)${On_WRed}\$(parse_git_status)${Color_Off}" # Задаем приглашение для пользователя и опеределение рута if [ "$(id -un)" = root ]; then PS1="┌ [${IRed}\u${Color_Off}][${IYellow}\H${Color_Off}][${ICyan}\w${Color_Off}]${show_git}\n└─ > " else PS1="┌ [${IGreen}\u${Color_Off}][${IYellow}\H${Color_Off}][${ICyan}\w${Color_Off}]${show_git}\n└─ > " fi {% endif %} {% if env_ps1_style == "server" %} # Конфигурация для серверов. if [ "$(id -un)" = root ]; then PS1="[${IRed}\u${Color_Off}][${IYellow}\H${Color_Off}][${ICyan}\w${Color_Off}]\n# " else PS1="[${IGreen}\u${Color_Off}][${IYellow}\H${Color_Off}][${ICyan}\w${Color_Off}]\n# " fi {% endif %} # Предотвращает случайное удаление файлов. alias mkdir='mkdir -p' # Подключаем dircolors if [ -x /usr/bin/dircolors ]; then if [ -r ~/.dircolors ]; then eval "$(dircolors -b ~/.dircolors)" else eval "$(dircolors -b)" fi # Цвета auto alias ls='ls --color' alias dmesg='dmesg --color' alias gcc='gcc -fdiagnostics-color=auto' alias dir='dir --color' alias diff='diff --color' alias grep='grep --color' alias fgrep='fgrep --color' alias egrep='egrep --color' fi # Раскрашиваем man export LESS_TERMCAP_mb=$'\e[0;36m' # начало мигания (Cyan) export LESS_TERMCAP_md=$'\e[1;36m' # начало жирного шрифта (BCyan) export LESS_TERMCAP_me=$'\e[0m' # сброс (Color_Off) export LESS_TERMCAP_se=$'\e[0m' # сброс выделения (Color_Off) export LESS_TERMCAP_so=$'\e[0;36m' # начало выделения - информация (Cyan) export LESS_TERMCAP_ue=$'\e[0m' # конец подчеркивания (Color_Off) export LESS_TERMCAP_us=$'\e[0;93m' # начало подчеркивания (IYellow) # Алиасы LS alias ll='ls -alF' # показать скрытые файлы с индикатором alias la='ls -Al' # показать скрытые файлы alias lx='ls -lXB' # сортировка по расширению alias lk='ls -lSr' # сортировка по размеру alias lc='ls -lcr' # сортировка по времени изменения alias lu='ls -lur' # сортировка по времени последнего обращения alias lr='ls -lR' # рекурсивный обход подкаталогов alias lt='ls -ltr' # сортировка по дате alias lm='ls -al |more' # вывод через 'more' # Цветной cat # Посмотреть все стили # pygmentize -L styles --json | jq alias ccat='pygmentize -g -O full,style=monokai' # Цветные команды alias ping="grc --colour=auto ping" alias traceroute="grc --colour=auto traceroute" alias netstat="grc --colour=auto netstat" alias stat="grc --colour=auto stat" alias ss="grc --colour=auto ss" alias diff="grc --colour=auto diff" alias wdiff="grc --colour=auto wdiff" alias last="grc --colour=auto last" alias mount="grc --colour=auto mount" alias ps="grc --colour=auto ps" alias dig="grc --colour=auto dig" alias ifconfig="grc --colour=auto ifconfig" alias mount="grc --colour=auto mount" alias df="grc --colour=auto df" alias du="grc --colour=auto du" alias ip="grc --colour=auto ip" alias env="grc --colour=auto env" alias iptables="grc --colour=auto iptables" alias lspci="grc --colour=auto lspci" alias lsblk="grc --colour=auto lsblk" alias lsof="grc --colour=auto lsof" alias blkid="grc --colour=auto blkid" alias id="grc --colour=auto id" alias fdisk="grc --colour=auto fdisk" alias free="grc --colour=auto free" alias systemctl="grc --colour=auto systemctl" alias journalctl="grc --colour=auto journalctl" alias sysctl="grc --colour=auto sysctl" alias tcpdump="grc --colour=auto tcpdump" alias tune2fs="grc --colour=auto tune2fs" alias lsmod="grc --colour=auto lsmod" alias lsattr="grc --colour=auto lsattr" alias nmap="grc --colour=auto nmap" alias uptime="grc --colour=auto uptime" alias getfacl="grc --colour=auto getfacl" alias iwconfig="grc --colour=auto iwconfig" alias whois="grc --colour=auto whois" # Функция распаковки extract function extract { if [ -z "$1" ]; then echo "Usage: extract <path/file_name>.<zip|rar|bz2|gz|tar|tbz2|tgz|Z|7z|xz|ex|tar.bz2|tar.gz|tar.xz>" else if [ -f "$1" ]; then case "$1" in *.tar.bz2) tar xvjf ./"$1" ;; *.tar.gz) tar xvzf ./"$1" ;; *.tar.xz) tar xvJf ./"$1" ;; *.lzma) unlzma ./"$1" ;; *.bz2) bunzip2 ./"$1" ;; *.rar) unrar x -ad ./"$1" ;; *.gz) gunzip ./"$1" ;; *.tar) tar xvf ./"$1" ;; *.tbz) tar xvjf ./"$1" ;; *.tbz2) tar xvjf ./"$1" ;; *.tgz) tar xvzf ./"$1" ;; *.zip) unzip ./"$1" ;; *.Z) uncompress ./"$1" ;; *.7z) 7z x ./"$1" ;; *.xz) unxz ./"$1" ;; *.exe) cabextract ./"$1" ;; *) echo "extract: '$1' - неизвестный архив" ;; esac else echo "$1 - файл не существует" fi fi }
import { NIVEAUX_POUR_LBA } from "../constants/recruteur" import { z } from "../helpers/zodWithOpenApi" export const zCallerParam = z .string() .openapi({ // Duplicated description because we have description when used in queryparams vs body param: { description: "Votre raison sociale ou le nom de votre produit qui fait appel à l'API idéalement préfixé par une adresse email de contact", }, description: "Votre raison sociale ou le nom de votre produit qui fait appel à l'API idéalement préfixé par une adresse email de contact", example: "contact@domaine nom_de_societe", }) .optional() export const zGetFormationOptions = z .literal("with_description") .openapi({ param: { description: "Ajoute la description au résultat de retour", }, example: "with_description", }) .optional() export const zRefererHeaders = z .object({ referer: z.string().optional(), }) .passthrough() export const zRomesParams = (imcompatibleWith: "romeDomain" | "rncp") => z .string() .optional() .openapi({ param: { description: `Une liste de codes ROME séparés par des virgules correspondant au(x) métier(s) recherché(s). Maximum 20.<br />rome et ${imcompatibleWith} sont incompatibles.<br/><strong>Au moins un des deux doit être renseigné.</strong>`, }, example: "F1603,I1308", }) export const zRncpsParams = z .string() .optional() .openapi({ param: { description: "Un code RNCP. <br />rome et rncp sont incompatibles.<br /><strong>Au moins un des deux doit être renseigné.</strong>", }, }) export const ZLatitudeParam = z.coerce .number() .optional() .openapi({ param: { description: "La latitude du centre de recherche. Nécessaire avec insee et longitude pour une recherche localisée.", }, example: 48.845, }) export const ZLongitudeParam = z.coerce .number() .optional() .openapi({ param: { description: "La longitude du centre de recherche. Nécessaire avec latitude et insee pour une recherche localisée.", }, example: 2.3752, }) export const ZRadiusParam = z.coerce .number() .optional() .openapi({ param: { description: "Le rayon de recherche en kilomètres", }, example: 30, }) export const zInseeParams = z .string() .optional() .openapi({ param: { description: "search center insee code", }, }) export const zSourcesParams = z .string() .optional() .openapi({ param: { description: 'comma separated list of job opportunities sources and trainings (possible values : "formations", "lba", "matcha", "offres")', }, }) const diplomaLevels = Object.keys(NIVEAUX_POUR_LBA) export const zDiplomaParam = z .enum([diplomaLevels[0], ...diplomaLevels.slice(1)]) .optional() .openapi({ param: { description: "Le niveau de diplôme visé en fin d'études", }, }) export const zOpcoParams = z .string() .optional() .openapi({ param: { description: "filter opportunities on opco name", }, }) export const zOpcoUrlParams = z .string() .optional() .openapi({ param: { description: "filter opportunities on opco url", }, })
[Shell 명령어 모음] 1. 터미널 툴 종류 cmd : windows 기본 powershell 도구 : windows 기본, powershell 언어 전용 cmder : windows 추천 (기능이 더 많고, 깃이 기본으로 포함되서 설치됨) iTerm : mac 기본 iTerm2 : mac 추천 (기능이 더 많고, 깃 브랜치 등의 시각화 및 테마 적용으로 보기에 더 편함) 1. 터미널 언어 종류 bash : Linux 기본 (Mac에서도 사용하기도 하고, Windows는 Git 다룰 때 Bash에서 사용하기도 함) shell : Mac 기본 zsh (zshell) : Mac 기본 (oh-my-zsh로 업그레이드하는 것을 추천) powershell : Windows 10 이후 기본 (Windows에서는 cmd가 기능이 후져서, 새로 shell 만든 것) cmd : Windows 기본 1. 공통 shell 명령어 cd : 현재 디렉토리를 바꾼다. (change directory) ls : 디렉토리에 있는 파일과 하위 목록을 가로 리스트로 보여준다. echo : 출력한다. ctrl + c : 명령을 중단한다. (모든 터미널 공통) mkdir [폴더명] : 폴더를 만든다. echo 텍스트 > output.txt : 앞단의 실행결과(echo 텍스트)를 output.txt 파일에 저장한다. touch output.txt : 아무것도 들어있지 않은 output.txt 파일을 만든다. 1. 특정 shell 명령어 : 예시 - cmd에서만 가능 color a : 콘솔색을 변경한다. - zsh에서만 가능 ls -al : 디렉토리에 있는 파일과 하위 목록을 세로 리스트로 보여준다. vi [파일명] : 해당 파일의 수정 모드로 vi 에디터 실행 - powershell에서만 가능 date : 날짜를 보여준다. calc : 계산기 실행 control : 제어판 실행 explorer . : 탐색기 실행 code . : vscode 실행 java -version : 자바 버전 확인 mspaint : 그림판 실행 ipconfig -all : IP 구성 ping : 네트워크 상태 확인 tracert : 네트워크 경로 추적 mstsc : 원격 데스크톱 실행
package com.serviceImplementation.Wallet.CustomException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import java.time.LocalDateTime; @ControllerAdvice public class GlobalExceptionHandler { public GlobalExceptionHandler() { System.out.println("4"); } @ExceptionHandler(value = {WalletNotFoundException.class}) public ResponseEntity<ErrorResponse> handleWalletNotFoundException (WalletNotFoundException walletNotFoundException,WebRequest req) { ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setTimestamp(LocalDateTime.now()); errorResponse.setMessage(walletNotFoundException.getMessage()); errorResponse.setDescription(req.getDescription(false)); return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.NOT_FOUND); } @ExceptionHandler(value = {UserNotFoundException.class}) public ResponseEntity<ErrorResponse> handleResourceNotFoundException (UserNotFoundException resourceNotFoundException, WebRequest req) { ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setTimestamp(LocalDateTime.now()); errorResponse.setMessage(resourceNotFoundException.getMessage()); errorResponse.setDescription(req.getDescription(false)); return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.NOT_FOUND); } @ExceptionHandler(value = {TopUpLimitExceededException.class}) public ResponseEntity<ErrorResponse> handleTopUpLimitExceededException (TopUpLimitExceededException topUpLimitExceededException,WebRequest req) { ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setTimestamp(LocalDateTime.now()); errorResponse.setMessage(topUpLimitExceededException.getMessage()); errorResponse.setDescription(req.getDescription(false)); return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.BAD_REQUEST); } @ExceptionHandler(value = {TransactionNotFoundException.class}) public ResponseEntity<ErrorResponse> handleTransactionNotFoundException (TransactionNotFoundException transactionNotFoundException,WebRequest req) { ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setTimestamp(LocalDateTime.now()); errorResponse.setMessage(transactionNotFoundException.getMessage()); errorResponse.setDescription(req.getDescription(false)); return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.NOT_FOUND); } @ExceptionHandler(value = {InsufficientBalanceException.class}) public ResponseEntity<ErrorResponse> handleInsufficientBalanceException (InsufficientBalanceException insufficientBalanceException,WebRequest req) { ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setTimestamp(LocalDateTime.now()); errorResponse.setMessage(insufficientBalanceException.getMessage()); errorResponse.setDescription(req.getDescription(false)); return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.BAD_REQUEST); } @ExceptionHandler(value = {IllegalArgumentException.class}) public ResponseEntity<ErrorResponse> handleIllegalArgumentException (IllegalArgumentException illegalArgumentException,WebRequest req) { ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setTimestamp(LocalDateTime.now()); errorResponse.setMessage(illegalArgumentException.getMessage()); errorResponse.setDescription(req.getDescription(false)); return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.BAD_REQUEST); } @ExceptionHandler(value = {UserAlreadyExistException.class}) public ResponseEntity<ErrorResponse> handle (UserAlreadyExistException userAlreadyExistException,WebRequest req) { ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setTimestamp(LocalDateTime.now()); errorResponse.setMessage(userAlreadyExistException.getMessage()); errorResponse.setDescription(req.getDescription(false)); return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.BAD_REQUEST); } }
#include "compiler.h" #include <math.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "common.h" #include "lexer.h" #include "memory.h" #include "utils.h" #if DEBUG_PRINT_CODE # include "debug.h" #endif typedef struct { // The most recently lexed token Token current; // The most recently consumed token. Token previous; // The module being parsed. ObjModule* module; // How many of the following dedent tokens will be ignored. int ignoreDedents; // Print the value returned by the code. bool printResult; // If an expression was parsed most recently. bool onExpression; // If a compiler error has appeared. bool hadError; bool panicMode; } Parser; typedef enum { BP_NONE, BP_ASSIGNMENT, // = BP_IF, // if ... else BP_NOT, // not BP_OR, // or BP_AND, // and BP_EQUALITY, // == != BP_COMPARISON, // < > <= >= BP_IS, // is BP_IN, // in BP_BIT_OR, // | BP_BIT_XOR, // ^ BP_BIT_AND, // & BP_BIT_SHIFT, // shl shr BP_RANGE, // .. : BP_TERM, // + - BP_FACTOR, // * / % BP_EXPONENT, // ** BP_UNARY, // - BP_CALL, // . () BP_PRIMARY } BindingPower; typedef enum { SIG_METHOD, SIG_ATTRIBUTE } SignatureType; typedef struct { const char* name; int length; SignatureType type; int arity; bool* asProperty; } Signature; typedef void (*ParseFn)(bool canAssign); typedef void (*SignatureFn)(Signature* signature); typedef struct { ParseFn prefix; ParseFn infix; BindingPower bp; const char* name; SignatureFn signatureFn; } ParseRule; typedef struct { // The name of the local variable. Token name; // The scope depth that this variable was declared in. int depth; // If this local is being used as an upvalue. bool isCaptured; } Local; typedef struct { // The index of the local or upvalue, specific to the current function. uint8_t index; // If the upvalue is capturing a local variable from the enclosing function. bool isLocal; } Upvalue; typedef struct Loop { // The instruction that the loop should jump back to. int start; // The index of the jump instruction used to exit the loop. int exitJump; // Depth of the scope that is exited by a break statement. int scopeDepth; // The count and capacity of the break stack. int breakCount; int breakCapacity; // The indices of breaks in the loop body, to be patched at the end. int* breaks; // The label for the loop, used with break and continue statements. Token* label; // The loop enclosing this one. NULL if this is the outermost. struct Loop* enclosing; } Loop; typedef enum { TYPE_FUNCTION, TYPE_LAMBDA, TYPE_INITIALIZER, TYPE_METHOD, TYPE_STATIC_METHOD, TYPE_SCRIPT } FunctionType; typedef struct Compiler { // The compiler for the enclosing function. struct Compiler* enclosing; // The innermost loop being compiled. Loop* loop; // The function being compiled. ObjFunction* function; FunctionType type; // The local variables in scope. Local locals[UINT8_COUNT]; // The number of locals in scope currently. int localCount; // The upvalues that have been captured from outside scopes. Upvalue upvalues[UINT8_COUNT]; // The array the compiler is writing bytecode to, NULL if the // compiler is writing to the main chunk. ByteArray* customWrite; IntArray* customLine; // The level of block scope nesting. int scopeDepth; } Compiler; typedef struct ClassCompiler { bool hasInitializer; struct ClassCompiler* enclosing; } ClassCompiler; Parser parser; Compiler* current = NULL; ClassCompiler* currentClass = NULL; static inline Chunk* currentChunk() { return &current->function->chunk; } static void errorAt(Token* token, const char* format, va_list args) { if (parser.panicMode) return; parser.panicMode = true; fprintf(stderr, "\033[1m%s:%d:\033[0m ", parser.module->name->chars, token->line); if (token->type == TOKEN_EOF) { fprintf(stderr, "error at end"); } else if (token->type == TOKEN_LINE) { fprintf(stderr, "error at newline"); } else if (token->type == TOKEN_INDENT || token->type == TOKEN_DEDENT) { fprintf(stderr, "error at indentation"); } else if (token->type == TOKEN_ERROR) { fprintf(stderr, "error"); } else { fprintf(stderr, "error at '%.*s'", token->length, token->start); } fprintf(stderr, ": "); vfprintf(stderr, format, args); fprintf(stderr, "\n"); parser.hadError = true; } static void error(const char* format, ...) { va_list args; va_start(args, format); errorAt(&parser.previous, format, args); va_end(args); } static void errorAtCurrent(const char* format, ...) { va_list args; va_start(args, format); errorAt(&parser.current, format, args); va_end(args); } static void advance() { parser.previous = parser.current; for (;;) { parser.current = nextToken(); if (parser.ignoreDedents > 0 && parser.current.type == TOKEN_DEDENT) { parser.ignoreDedents--; continue; } if (parser.current.type != TOKEN_ERROR) break; errorAtCurrent(parser.current.start); } } static void expect(TokenType type, const char* message) { if (parser.current.type == type) { advance(); return; } errorAtCurrent(message); } static bool check(TokenType type) { return parser.current.type == type; } static bool match(TokenType type) { if (!check(type)) return false; advance(); return true; } static bool matchLine() { if (!match(TOKEN_LINE)) return false; while (match(TOKEN_LINE)); return true; } static void expectLine(const char* message) { if (!matchLine()) { errorAtCurrent(message); } } static bool ignoreIndentation() { if (!match(TOKEN_INDENT)) { if (!match(TOKEN_DEDENT)) return false; while (match(TOKEN_DEDENT)); } return true; } static void expectStatementEnd(const char* message) { // If the parser has just synchronized after an error, it might have // already consumed a newline token. That's why we check for it here. if (parser.previous.type == TOKEN_LINE || parser.previous.type == TOKEN_DEDENT || parser.previous.type == TOKEN_INDENT) return; if (match(TOKEN_SEMICOLON)) { matchLine(); return; } if (!matchLine()) errorAtCurrent(message); } static void emitByte(uint8_t byte) { if (current->customWrite != NULL) { byteArrayWrite(current->customWrite, byte); intArrayWrite(current->customLine, parser.previous.line); return; } writeChunk(currentChunk(), byte, parser.previous.line); } static void emitVariableBytes(int arg) { if (arg < 0x80) { emitByte((uint8_t)arg); } else { emitByte(((arg >> 8) & 0xff) | 0x80); emitByte(arg & 0xff); } } static void emitVariableArg(uint8_t instruction, int arg) { emitByte(instruction); emitVariableBytes(arg); } static void emitBytes(uint8_t byte1, uint8_t byte2) { emitByte(byte1); emitByte(byte2); } static void emitLoop(int loopStart) { emitByte(OP_LOOP); int offset = currentChunk()->count - loopStart + 2; if (offset > UINT16_MAX) error("Loop body is too large"); emitByte((offset >> 8) & 0xff); emitByte(offset & 0xff); } static int emitJump(uint8_t instruction) { emitByte(instruction); emitByte(0xff); emitByte(0xff); return currentChunk()->count - 2; } static void emitReturn() { if (current->type == TYPE_INITIALIZER) { emitBytes(OP_GET_LOCAL, 0); } else { emitByte(OP_NONE); } emitByte(OP_RETURN); } static int makeConstant(Value value) { int constant = addConstant(currentChunk(), value); if (constant > MAX_CONSTANTS) { error("A function can only contain %d constants", MAX_CONSTANTS); return 0; } return constant; } static void emitConstant(Value value) { emitByte(OP_CONSTANT); emitVariableBytes(makeConstant(value)); } static void emitConstantArg(uint8_t instruction, Value arg) { emitByte(instruction); emitVariableBytes(makeConstant(arg)); } static inline void callMethod(int argCount, const char* name, int length) { emitConstantArg(OP_INVOKE_0 + argCount, OBJ_VAL(copyStringLength(name, length))); } static void patchJump(int offset) { // -2 to account for the bytecode for the jump offset itself. int jump = currentChunk()->count - offset - 2; if (jump > UINT16_MAX) { error("Too much code to jump over"); } currentChunk()->code[offset] = (jump >> 8) & 0xff; currentChunk()->code[offset + 1] = jump & 0xff; } static void startLoop(Loop* loop) { loop->enclosing = current->loop; loop->start = currentChunk()->count; loop->scopeDepth = current->scopeDepth; loop->breakCount = 0; loop->breakCapacity = 0; loop->breaks = NULL; current->loop = loop; } static void endLoop() { emitLoop(current->loop->start); // Just in case you want to know the label of the loop: // // if (current->loop->label != NULL) { // Token* label = current->loop->label; // char* chars = ALLOCATE(char, label->length + 1); // memcpy(chars, label->start, label->length); // chars[label->length] = '\0'; // } if (current->loop->exitJump != -1) { patchJump(current->loop->exitJump); emitByte(OP_POP); // Pop the condition. } while (current->loop->breakCount > 0) { int breakJump = current->loop->breaks[--current->loop->breakCount]; patchJump(breakJump); } current->loop = current->loop->enclosing; } static void initCompiler(Compiler* compiler, FunctionType type) { compiler->enclosing = current; compiler->loop = NULL; compiler->function = NULL; compiler->type = type; compiler->localCount = 0; compiler->scopeDepth = 0; compiler->customWrite = NULL; compiler->function = newFunction(parser.module); current = compiler; if (type == TYPE_LAMBDA) { current->function->name = copyStringLength("\b", 1); } else if (type != TYPE_SCRIPT) { current->function->name = copyStringLength(parser.previous.start, parser.previous.length); } Local* local = &current->locals[current->localCount++]; local->depth = 0; local->isCaptured = false; if (type != TYPE_FUNCTION) { local->name.start = "this"; local->name.length = 4; } else { local->name.start = ""; local->name.length = 0; } } static ObjFunction* endCompiler() { if (current->scopeDepth == 0 && parser.onExpression && parser.printResult) { emitByte(OP_RETURN_OUTPUT); emitByte(OP_RETURN); } else { emitReturn(); } ObjFunction* function = current->function; # if DEBUG_PRINT_CODE == 2 if (!parser.hadError) { disassembleChunk(currentChunk(), function->name != NULL ? function->name->chars : "main"); } # elif DEBUG_PRINT_CODE == 1 if (!parser.hadError && !parser.module->isCore) { disassembleChunk(currentChunk(), function->name != NULL ? function->name->chars : "main"); } # endif while (current->loop != NULL) { if (current->loop->breaks != NULL) free(current->loop->breaks); current->loop = current->loop->enclosing; } current = current->enclosing; return function; } static void pushScope() { current->scopeDepth++; } static int discardLocals(int depth) { ASSERT(current->scopeDepth >= 0, "Cannot exit top level scope"); int local = current->localCount - 1; while (local >= 0 && current->locals[local].depth >= depth) { // To print out discarded locals: // // Token token = current->locals[local].name; // char* chars = ALLOCATE(char, token.length + 1); // memcpy(chars, token.start, token.length); // chars[token.length] = '\0'; // printf("discarding %s (%d >= %d)\n", chars, current->locals[local].depth, depth); if (current->locals[local].isCaptured) { emitByte(OP_CLOSE_UPVALUE); } else { emitByte(OP_POP); } local--; } return current->localCount - local - 1; } static void popScope() { int popped = discardLocals(current->scopeDepth); current->localCount -= popped; current->scopeDepth--; } static void expression(); static void statement(); static void declaration(); static void lambda(bool canAssign); static ParseRule* getRule(TokenType type); static void expressionBp(BindingPower bp); static int identifierConstant(Token* name) { return makeConstant(OBJ_VAL(copyStringLength(name->start, name->length))); } static bool identifiersEqual(Token* a, Token* b) { if (a->length != b->length) return false; return memcmp(a->start, b->start, a->length) == 0; } static int resolveLocal(Compiler* compiler, Token* name) { for (int i = compiler->localCount - 1; i >= 0; i--) { Local* local = &compiler->locals[i]; if (identifiersEqual(name, &local->name)) { if (local->depth == -1) { error("Can't use local variable in its own initializer"); } return i; } } return -1; } static int addUpvalue(Compiler* compiler, uint8_t index, bool isLocal) { int upvalueCount = compiler->function->upvalueCount; for (int i = 0; i < upvalueCount; i++) { Upvalue* upvalue = &compiler->upvalues[i]; if (upvalue->index == index && upvalue->isLocal == isLocal) { return i; } } if (upvalueCount == UINT8_COUNT) { error("Too many closure variables in function"); return 0; } compiler->upvalues[upvalueCount].isLocal = isLocal; compiler->upvalues[upvalueCount].index = index; return compiler->function->upvalueCount++; } static int resolveUpvalue(Compiler* compiler, Token* name) { if (compiler->enclosing == NULL) return -1; int local = resolveLocal(compiler->enclosing, name); if (local != -1) { compiler->enclosing->locals[local].isCaptured = true; return addUpvalue(compiler, (uint8_t)local, true); } int upvalue = resolveUpvalue(compiler->enclosing, name); if (upvalue != -1) { return addUpvalue(compiler, (uint8_t)upvalue, false); } return -1; } static void addLocal(Token name) { if (current->localCount == UINT8_COUNT) { error("Too many local variables in one function"); return; } Local* local = &current->locals[current->localCount++]; local->name = name; local->depth = -1; local->isCaptured = false; } static void declareVariable() { if (current->scopeDepth == 0) return; Token* name = &parser.previous; for (int i = current->localCount - 1; i >= 0; i--) { Local* local = &current->locals[i]; if (local->depth != -1 && local->depth < current->scopeDepth) { break; } if (identifiersEqual(name, &local->name)) { error("Variable has been declared previously"); } } addLocal(*name); } static int parseVariable(const char* errorMessage) { expect(TOKEN_IDENTIFIER, errorMessage); declareVariable(); if (current->scopeDepth > 0) return 0; return identifierConstant(&parser.previous); } static void markInitialized() { if (current->scopeDepth == 0) return; current->locals[current->localCount - 1].depth = current->scopeDepth; } static void defineVariable(int global) { if (current->scopeDepth > 0) { markInitialized(); return; } emitVariableArg(OP_DEFINE_GLOBAL, global); } static void signatureParameterList(char name[MAX_METHOD_SIGNATURE], int* length, int arity) { name[(*length)++] = '('; if (arity > 0) { int digits = ceil(log10(arity + 1)); char* chars = ALLOCATE(char, digits); sprintf(chars, "%d", arity); memcpy(name + *length, chars, digits); *length += digits; FREE_ARRAY(char, chars, digits); } name[(*length)++] = ')'; } static void signatureToString(Signature* signature, char name[MAX_METHOD_SIGNATURE], int* length) { *length = 0; memcpy(name, signature->name, signature->length); *length += signature->length; if (signature->type != SIG_ATTRIBUTE) { signatureParameterList(name, length, signature->arity); } name[*length] = '\0'; } static Signature signatureFromToken(SignatureType type) { Signature signature; Token* token = &parser.previous; signature.name = token->start; signature.length = token->length; signature.type = type; signature.arity = 0; signature.asProperty = NULL; if (signature.length > MAX_METHOD_NAME) { error("Method names cannot be longer than %d characters", MAX_METHOD_NAME); signature.length = MAX_METHOD_NAME; } return signature; } static void validateParameterCount(const char* type, int num) { if (num == MAX_PARAMETERS + 1) { error("%ss cannot have more than %d parameters", type, MAX_PARAMETERS); } } static void finishParameterList(Signature* signature) { signature->asProperty = ALLOCATE(bool, MAX_PARAMETERS); do { matchLine(); validateParameterCount("Method", ++signature->arity); signature->asProperty[signature->arity - 1] = match(TOKEN_PLUS); int constant = parseVariable("Expecting a parameter name"); defineVariable(constant); } while (match(TOKEN_COMMA)); } static void finishArgumentList(Signature* signature, const char* type, TokenType end) { if (!check(end)) { do { if (matchLine() && match(TOKEN_INDENT)) { parser.ignoreDedents++; } validateParameterCount(type, ++signature->arity); expression(); } while (match(TOKEN_COMMA)); matchLine(); } if (end == TOKEN_RIGHT_PAREN) { expect(end, "Expecting ')' after arguments"); } else { expect(end, (signature->arity == 1 ? "Expecting ']' after subscript value" : "Expecting ']' after subscript values")); } } static inline void emitSignatureArg(uint8_t instruction, Signature* signature) { char method[MAX_METHOD_SIGNATURE]; int length; signatureToString(signature, method, &length); emitConstantArg(instruction, OBJ_VAL(copyStringLength(method, length))); } static inline void callSignature(int argCount, Signature* signature) { emitSignatureArg(OP_INVOKE_0 + argCount, signature); } void binarySignature(Signature* signature) { signature->type = SIG_METHOD; signature->arity = 1; signature->asProperty = NULL; expect(TOKEN_LEFT_PAREN, "Expecting '(' after operator name"); int constant = parseVariable("Expecting a parameter name"); defineVariable(constant); expect(TOKEN_RIGHT_PAREN, "Expecting ')' after parameter name"); } void unarySignature(Signature* signature) { signature->type = SIG_METHOD; expect(TOKEN_LEFT_PAREN, "Expecting '(' after method name"); expect(TOKEN_RIGHT_PAREN, "Expecting ')' after opening parenthesis"); } void mixedSignature(Signature* signature) { signature->type = SIG_METHOD; if (match(TOKEN_LEFT_PAREN)) { signature->type = SIG_METHOD; signature->arity = 1; signature->asProperty = NULL; int constant = parseVariable("Expecting a parameter name"); defineVariable(constant); expect(TOKEN_RIGHT_PAREN, "Expecting ')' after parameter name"); } } void namedSignature(Signature* signature) { expect(TOKEN_LEFT_PAREN, "Expecting '(' after method name"); signature->type = SIG_METHOD; matchLine(); if (match(TOKEN_RIGHT_PAREN)) return; finishParameterList(signature); expect(TOKEN_RIGHT_PAREN, "Expecting ')' after parameters"); } void attributeSignature(Signature* signature) { signature->type = SIG_ATTRIBUTE; } static Token syntheticToken(const char* text) { Token token; token.start = text; token.length = (int)strlen(text); return token; } static void namedVariable(Token name, bool canAssign) { uint8_t getOp, setOp; int arg = resolveLocal(current, &name); if (arg != -1) { getOp = OP_GET_LOCAL; setOp = OP_SET_LOCAL; } else if ((arg = resolveUpvalue(current, &name)) != -1) { getOp = OP_GET_UPVALUE; setOp = OP_SET_UPVALUE; } else { arg = identifierConstant(&name); getOp = OP_GET_GLOBAL; setOp = OP_SET_GLOBAL; } if (canAssign && match(TOKEN_EQ)) { // bool modifier = false; // if (match(TOKEN_GT)) { // if (getOp == OP_GET_GLOBAL) emitVariableArg(getOp, arg); // else emitBytes(getOp, (uint8_t)arg); // modifier = true; // } if (matchLine() && match(TOKEN_INDENT)) { parser.ignoreDedents++; } // if (modifier) { // advance(); // ParseFn infixRule = getRule(parser.previous.type)->infix; // if (infixRule == NULL) { // error("Expecting an infix operator to modify variable"); // } else { // infixRule(false); // } // } else ... expression(); if (setOp == OP_SET_GLOBAL) { emitVariableArg(setOp, arg); } else { emitBytes(setOp, (uint8_t)arg); } } else { if (getOp == OP_GET_GLOBAL) emitVariableArg(getOp, arg); else emitBytes(getOp, (uint8_t)arg); } } static void variable(bool canAssign) { namedVariable(parser.previous, canAssign); } static void call(bool canAssign) { Signature signature = { NULL, 0, SIG_METHOD, 0 }; finishArgumentList(&signature, "Function", TOKEN_RIGHT_PAREN); emitByte(OP_CALL_0 + signature.arity); } static void callFunction(bool canAssign) { lambda(false); emitByte(OP_CALL_1); } static void callable(bool canAssign) { advance(); ParseRule* rule = getRule(parser.previous.type); if (rule->signatureFn == NULL) { error("Expecting a method name after '::'"); } Signature signature = signatureFromToken(SIG_METHOD); if (match(TOKEN_LEFT_PAREN)) { if (match(TOKEN_RIGHT_PAREN)) { signature.arity = 0; } else { expect(TOKEN_NUMBER, "Expecting a parameter count"); double num = AS_NUMBER(parser.previous.value); signature.arity = (int)trunc(num); if (num != signature.arity) { error("Parameter count must be an integer"); } expect(TOKEN_RIGHT_PAREN, "Expecting ')' after parameter count"); } } else { signature.type = SIG_ATTRIBUTE; } emitSignatureArg(OP_BIND_METHOD, &signature); } static void dot(bool canAssign) { expect(TOKEN_IDENTIFIER, "Expecting a property name after '.'"); int name = identifierConstant(&parser.previous); Signature signature = signatureFromToken(SIG_METHOD); if (canAssign && match(TOKEN_EQ)) { if (matchLine() && match(TOKEN_INDENT)) { parser.ignoreDedents++; } expression(); emitVariableArg(OP_SET_PROPERTY, name); } else if (match(TOKEN_LEFT_PAREN) || match(TOKEN_LEFT_BRACE)) { if (parser.previous.type == TOKEN_LEFT_BRACE) { lambda(false); signature.arity = 1; } else { finishArgumentList(&signature, "Method", TOKEN_RIGHT_PAREN); } callSignature(signature.arity, &signature); } else { emitVariableArg(OP_GET_PROPERTY, name); } } static void super_(bool canAssign) { if (currentClass == NULL) { error("Can't use 'super' outside of a class"); } Signature signature; uint8_t instruction; if (match(TOKEN_COLON_COLON)) { advance(); ParseRule* rule = getRule(parser.previous.type); if (rule->signatureFn == NULL) { error("Expecting a method name after '::'"); } signature = signatureFromToken(SIG_METHOD); if (match(TOKEN_LEFT_PAREN)) { if (match(TOKEN_RIGHT_PAREN)) { signature.arity = 0; } else { expect(TOKEN_NUMBER, "Expecting a parameter count"); double num = AS_NUMBER(parser.previous.value); signature.arity = (int)trunc(num); if (num != signature.arity) { error("Parameter count must be an integer"); } expect(TOKEN_RIGHT_PAREN, "Expecting ')' after parameter count"); } } else { signature.type = SIG_ATTRIBUTE; } instruction = OP_BIND_SUPER; } else { expect(TOKEN_DOT, "Expecting '.' after 'super'"); expect(TOKEN_IDENTIFIER, "Expecting a superclass method name"); signature = signatureFromToken(SIG_METHOD); namedVariable(syntheticToken("this"), false); if (match(TOKEN_LEFT_PAREN) || match(TOKEN_LEFT_BRACE)) { if (parser.previous.type == TOKEN_LEFT_BRACE) { lambda(false); signature.arity = 1; } else { finishArgumentList(&signature, "Method", TOKEN_RIGHT_PAREN); } } else { signature.type = SIG_ATTRIBUTE; } namedVariable(syntheticToken("super"), false); instruction = OP_SUPER_0 + signature.arity; } emitSignatureArg(instruction, &signature); } static void this_(bool canAssign) { if (currentClass == NULL) { error("Can't use 'this' outside of a class"); return; } if (current->type == TYPE_STATIC_METHOD) { error("Can't use 'this' in a static method"); return; } namedVariable(parser.previous, false); } static void literal(bool canAssign) { switch (parser.previous.type) { case TOKEN_FALSE: emitByte(OP_FALSE); break; case TOKEN_NONE: emitByte(OP_NONE); break; case TOKEN_TRUE: emitByte(OP_TRUE); break; case TOKEN_NUMBER: case TOKEN_STRING: emitConstant(parser.previous.value); default: return; // Unreachable } } static void grouping(bool canAssign) { expression(); expect(TOKEN_RIGHT_PAREN, "Expecting ')' after expressions"); } static void or_(bool canAssign) { matchLine(); int jump = emitJump(OP_JUMP_TRUTHY); emitByte(OP_POP); expressionBp(BP_OR); patchJump(jump); } static void and_(bool canAssign) { matchLine(); int jump = emitJump(OP_JUMP_FALSY); emitByte(OP_POP); expressionBp(BP_AND); patchJump(jump); } static void if_(bool canAssign) { expression(); int endJump = emitJump(OP_JUMP_TRUTHY_POP); expect(TOKEN_ELSE, "Expecting an else clause after condition"); expression(); patchJump(endJump); } static void stringInterpolation(bool canAssign) { emitConstantArg(OP_GET_GLOBAL, OBJ_VAL(copyStringLength("List", 4))); emitByte(OP_CALL_0); int addConstant = makeConstant(OBJ_VAL(copyStringLength("addCore(1)", 10))); do { emitConstant(parser.previous.value); emitVariableArg(OP_INVOKE_1, addConstant); matchLine(); expression(); emitVariableArg(OP_INVOKE_1, addConstant); matchLine(); } while (match(TOKEN_INTERPOLATION)); expect(TOKEN_STRING, "Expecting an end to string interpolation"); emitConstant(parser.previous.value); emitVariableArg(OP_INVOKE_1, addConstant); emitConstant(OBJ_VAL(copyStringLength("", 0))); callMethod(1, "joinToString(1)", 15); } static void collection(bool canAssign) { if (match(TOKEN_RIGHT_BRACKET)) { emitConstantArg(OP_GET_GLOBAL, OBJ_VAL(copyStringLength("List", 4))); emitByte(OP_CALL_0); return; } else if (match(TOKEN_RIGHT_ARROW)) { expect(TOKEN_RIGHT_BRACKET, "Expecting ']' to end empty map"); emitConstantArg(OP_GET_GLOBAL, OBJ_VAL(copyStringLength("Map", 3))); emitByte(OP_CALL_0); return; } bool indented = false; if (matchLine()) { expect(TOKEN_INDENT, "Expecting indentation to increase before collection body"); indented = true; } ByteArray code; IntArray lines; byteArrayInit(&code); intArrayInit(&lines); current->customWrite = &code; current->customLine = &lines; expression(); current->customWrite = NULL; current->customLine = NULL; bool isMap = match(TOKEN_RIGHT_ARROW); bool first = true; emitConstantArg(OP_GET_GLOBAL, isMap ? OBJ_VAL(copyStringLength("Map", 3)) : OBJ_VAL(copyStringLength("List", 4))); emitByte(OP_CALL_0); do { if (matchLine()) { if (!indented) { expect(TOKEN_INDENT, "Expecting indentation to increase before collection body"); indented = true; } else { if (match(TOKEN_DEDENT)) indented = false; } } if (check(TOKEN_RIGHT_BRACKET)) break; if (first) { // Transfer all the code that makes up the first item into the current chunk. for (int i = 0; i < code.count; i++) { writeChunk(currentChunk(), code.data[i], lines.data[i]); } byteArrayFree(&code); intArrayFree(&lines); } else { expression(); } if (isMap) { if (!first) expect(TOKEN_RIGHT_ARROW, "Expecting '->' after map key"); expression(); callMethod(2, "addCore(2)", 10); } else { callMethod(1, "addCore(1)", 10); } first = false; } while (match(TOKEN_COMMA)); matchLine(); if (indented && match(TOKEN_DEDENT)) indented = false; expect(TOKEN_RIGHT_BRACKET, isMap ? "Expecting ']' after map literal" : "Expecting ']' after list literal"); if (indented) { matchLine(); expect(TOKEN_DEDENT, "Expecting indentation to decrease"); } } static void subscript(bool canAssign) { Signature signature = { "get", 3, SIG_METHOD, 0, NULL }; finishArgumentList(&signature, "Method", TOKEN_RIGHT_BRACKET); if (canAssign && match(TOKEN_EQ)) { if (matchLine() && match(TOKEN_INDENT)) { parser.ignoreDedents++; } expression(); validateParameterCount("Method", ++signature.arity); signature.name = "set"; } callSignature(signature.arity, &signature); } static void binary(bool canAssign) { TokenType operatorType = parser.previous.type; ParseRule* rule = getRule(operatorType); bool negate = (operatorType == TOKEN_IS && match(TOKEN_NOT)); if (matchLine() && match(TOKEN_INDENT)) { parser.ignoreDedents++; } if (operatorType == TOKEN_STAR_STAR) { expressionBp((BindingPower)(rule->bp)); } else { expressionBp((BindingPower)(rule->bp + 1)); } Signature signature = { rule->name, (int)strlen(rule->name), SIG_METHOD, 1 }; callSignature(1, &signature); if (negate) { callMethod(0, "not()", 5); } } static void unary(bool canAssign) { TokenType operatorType = parser.previous.type; ParseRule* rule = getRule(operatorType); if (matchLine() && match(TOKEN_INDENT)) { parser.ignoreDedents++; } // Compile the operand. expressionBp(operatorType == TOKEN_NOT ? BP_NOT : BP_UNARY); Signature signature = { rule->name, (int)strlen(rule->name), SIG_METHOD, 0 }; callSignature(0, &signature); } #define UNUSED { NULL, NULL, BP_NONE, NULL, NULL } #define INFIX(fn, bp) { NULL, fn, bp, NULL, NULL } #define INFIX_OPERATOR(bp, name) { NULL, binary, bp, name, binarySignature } #define PREFIX(fn, bp) { fn, NULL, bp, NULL, NULL } #define PREFIX_OPERATOR(bp, name) { unary, NULL, bp, name, unarySignature } #define BOTH(prefix, infix, bp) { prefix, infix, bp, NULL, NULL } #define OPERATOR(bp, name) { unary, binary, bp, name, mixedSignature } ParseRule rules[] = { /* TOKEN_LEFT_PAREN */ BOTH(grouping, call, BP_CALL), /* TOKEN_RIGHT_PAREN */ UNUSED, /* TOKEN_LEFT_BRACKET */ BOTH(collection, subscript, BP_CALL), /* TOKEN_RIGHT_BRACKET */ UNUSED, /* TOKEN_LEFT_BRACE */ BOTH(lambda, callFunction, BP_CALL), /* TOKEN_RIGHT_BRACE */ UNUSED, /* TOKEN_SEMICOLON */ UNUSED, /* TOKEN_COMMA */ UNUSED, /* TOKEN_PLUS */ INFIX_OPERATOR(BP_TERM, "+"), /* TOKEN_SLASH */ INFIX_OPERATOR(BP_FACTOR, "/"), /* TOKEN_PERCENT */ INFIX_OPERATOR(BP_FACTOR, "%"), /* TOKEN_PIPE */ INFIX_OPERATOR(BP_BIT_OR, "|"), /* TOKEN_CARET */ INFIX_OPERATOR(BP_BIT_XOR, "^"), /* TOKEN_AMPERSAND */ INFIX_OPERATOR(BP_BIT_AND, "&"), /* TOKEN_TILDE */ PREFIX_OPERATOR(BP_UNARY, "~"), /* TOKEN_DOT */ INFIX(dot, BP_CALL), /* TOKEN_DOT_DOT */ INFIX_OPERATOR(BP_RANGE, ".."), /* TOKEN_DOT_DOT_LT */ INFIX_OPERATOR(BP_RANGE, "..<"), /* TOKEN_COLON */ UNUSED, /* TOKEN_COLON_COLON */ INFIX(callable, BP_CALL), /* TOKEN_STAR */ INFIX_OPERATOR(BP_FACTOR, "*"), /* TOKEN_STAR_STAR */ INFIX_OPERATOR(BP_EXPONENT, "**"), /* TOKEN_MINUS */ OPERATOR(BP_TERM, "-"), /* TOKEN_RIGHT_ARROW */ UNUSED, /* TOKEN_BANG */ UNUSED, /* TOKEN_BANG_EQ */ INFIX_OPERATOR(BP_EQUALITY, "!="), /* TOKEN_EQ */ UNUSED, /* TOKEN_EQ_EQ */ INFIX_OPERATOR(BP_EQUALITY, "=="), /* TOKEN_GT */ INFIX_OPERATOR(BP_COMPARISON, ">"), /* TOKEN_GT_EQ */ INFIX_OPERATOR(BP_COMPARISON, ">="), /* TOKEN_LT */ INFIX_OPERATOR(BP_COMPARISON, "<"), /* TOKEN_LT_EQ */ INFIX_OPERATOR(BP_COMPARISON, "<="), /* TOKEN_IDENTIFIER */ { variable, NULL, BP_NONE, NULL, namedSignature }, /* TOKEN_STRING */ PREFIX(literal, BP_NONE), /* TOKEN_INTERPOLATION */ PREFIX(stringInterpolation, BP_NONE), /* TOKEN_NUMBER */ PREFIX(literal, BP_NONE), /* TOKEN_AND */ INFIX(and_, BP_AND), /* TOKEN_ATTRIBUTE */ UNUSED, /* TOKEN_BREAK */ UNUSED, /* TOKEN_CLASS */ UNUSED, /* TOKEN_CONTINUE */ UNUSED, /* TOKEN_DO */ UNUSED, /* TOKEN_EACH */ UNUSED, /* TOKEN_ELIF */ UNUSED, /* TOKEN_ELSE */ UNUSED, /* TOKEN_FALSE */ PREFIX(literal, BP_NONE), /* TOKEN_FOR */ UNUSED, /* TOKEN_FUN */ UNUSED, /* TOKEN_IF */ INFIX(if_, BP_IF), /* TOKEN_IN */ UNUSED, /* TOKEN_IS */ INFIX_OPERATOR(BP_IS, "is"), /* TOKEN_NONE */ PREFIX(literal, BP_NONE), /* TOKEN_NOT */ PREFIX_OPERATOR(BP_NOT, "not"), /* TOKEN_OR */ INFIX(or_, BP_OR), /* TOKEN_PASS */ UNUSED, /* TOKEN_PRINT */ UNUSED, /* TOKEN_PRINT_ERROR */ UNUSED, /* TOKEN_RETURN */ UNUSED, /* TOKEN_SHL */ INFIX_OPERATOR(BP_BIT_SHIFT, "shl"), /* TOKEN_SHR */ INFIX_OPERATOR(BP_BIT_SHIFT, "shr"), /* TOKEN_STATIC */ UNUSED, /* TOKEN_SUPER */ PREFIX(super_, BP_NONE), /* TOKEN_THIS */ PREFIX(this_, BP_NONE), /* TOKEN_TRUE */ PREFIX(literal, BP_NONE), /* TOKEN_USE */ UNUSED, /* TOKEN_VAR */ UNUSED, /* TOKEN_WHEN */ UNUSED, // TODO: When expressions /* TOKEN_WHILE */ UNUSED, /* TOKEN_INDENT */ UNUSED, /* TOKEN_DEDENT */ UNUSED, /* TOKEN_LINE */ UNUSED, /* TOKEN_ERROR */ UNUSED, /* TOKEN_EOF */ UNUSED, /* TOKEN_NULL */ UNUSED, // The compiler should never see a null token. }; static void expressionBp(BindingPower bp) { advance(); ParseFn prefixRule = getRule(parser.previous.type)->prefix; if (prefixRule == NULL) { error("Expecting an expression"); return; } bool canAssign = bp <= BP_ASSIGNMENT; prefixRule(canAssign); while (bp <= getRule(parser.current.type)->bp) { advance(); ParseFn infixRule = getRule(parser.previous.type)->infix; infixRule(canAssign); } // The equals sign should be handled already. if (canAssign && match(TOKEN_EQ)) { error("Invalid assignment target"); } } static inline ParseRule* getRule(TokenType type) { return &rules[type]; } static void expression() { expressionBp(BP_ASSIGNMENT); } // indentationBased is to help with this weird case: // // if (variable == 2) { // if (otherVar == 4) // print "yes" // } static void block() { matchLine(); while (!check(TOKEN_DEDENT) && !check(TOKEN_EOF)) { declaration(); if (!check(TOKEN_EOF)) { expectStatementEnd("Expecting a newline after statement"); } matchLine(); } if (!check(TOKEN_EOF)) expect(TOKEN_DEDENT, "Expecting indentation to decrease after block"); } static void lambdaBlock() { if (matchLine()) ignoreIndentation(); parser.onExpression = false; while (!check(TOKEN_RIGHT_BRACE) && !check(TOKEN_EOF)) { if (parser.onExpression) { emitByte(OP_POP); parser.onExpression = false; } declaration(); if (!check(TOKEN_RIGHT_BRACE) && !check(TOKEN_EOF)) { expectStatementEnd("Expecting a newline after statement"); ignoreIndentation(); } } expect(TOKEN_RIGHT_BRACE, "Expecting '}' after lambda"); } static void scopedBlock() { pushScope(); block(); popScope(); } static void function(FunctionType type) { Compiler compiler; initCompiler(&compiler, type); pushScope(); expect(TOKEN_LEFT_PAREN, "Expecting '(' after function name"); if (!check(TOKEN_RIGHT_PAREN)) { do { matchLine(); // TODO: We almost always want function parameters indented. validateParameterCount("Function", ++current->function->arity); int constant = parseVariable("Expecting a parameter name"); defineVariable(constant); } while (match(TOKEN_COMMA)); } expect(TOKEN_RIGHT_PAREN, "Expecting ')' after parameters"); if (match(TOKEN_EQ)) { expression(); emitByte(OP_RETURN); } else { expectLine("Expecting a linebreak before function body"); expect(TOKEN_INDENT, "Expecting an indent before function body"); block(); } ObjFunction* function = endCompiler(); emitConstantArg(OP_CLOSURE, OBJ_VAL(function)); for (int i = 0; i < function->upvalueCount; i++) { emitByte(compiler.upvalues[i].isLocal ? 1 : 0); emitByte(compiler.upvalues[i].index); } } static void lambda(bool canAssign) { Compiler compiler; initCompiler(&compiler, TYPE_LAMBDA); pushScope(); if (matchLine()) ignoreIndentation(); if (match(TOKEN_PIPE)) { if (!match(TOKEN_PIPE)) { do { if (matchLine()) ignoreIndentation(); validateParameterCount("Lambda", ++current->function->arity); int constant = parseVariable("Expecting a parameter name"); defineVariable(constant); } while (match(TOKEN_COMMA)); expect(TOKEN_PIPE, "Expecting '|' after parameters"); if (matchLine()) ignoreIndentation(); } } lambdaBlock(); // If the lambda is just an expression, return its value. if (parser.onExpression) { emitByte(OP_RETURN); parser.onExpression = false; } ObjFunction* function = endCompiler(); emitConstantArg(OP_CLOSURE, OBJ_VAL(function)); for (int i = 0; i < function->upvalueCount; i++) { emitByte(compiler.upvalues[i].isLocal ? 1 : 0); emitByte(compiler.upvalues[i].index); } if ((parser.printResult && current->scopeDepth == 0) || current->type == TYPE_LAMBDA) { parser.onExpression = true; } } static void method() { bool isStatic = match(TOKEN_STATIC); bool isAttribute = match(TOKEN_ATTRIBUTE); if (isAttribute && match(TOKEN_STATIC)) error("Keyword 'static' must come before 'attribute'"); SignatureFn parseSignature = isAttribute ? attributeSignature : getRule(parser.current.type)->signatureFn; advance(); if (parseSignature == NULL) { error("Expecting a method definition"); return; } Signature signature = signatureFromToken(SIG_METHOD); FunctionType type = isStatic ? TYPE_STATIC_METHOD : TYPE_METHOD; if (parser.previous.length == 4 && memcmp(parser.previous.start, "init", 4) == 0) { if (isStatic) error("Initializers cannot be static"); if (currentClass->hasInitializer) error("Classes can only have one initializer"); type = TYPE_INITIALIZER; currentClass->hasInitializer = true; } Compiler compiler; initCompiler(&compiler, type); pushScope(); parseSignature(&signature); current->function->arity = signature.arity; if (signature.asProperty != NULL) { for (int i = 0; i < current->function->arity; i++) { if (signature.asProperty[i]) { if (isStatic) { error("Can only store fields through non-static methods"); break; } emitBytes(OP_GET_LOCAL, 0); emitBytes(OP_GET_LOCAL, i + 1); Local local = current->locals[i + 1]; emitVariableArg(OP_SET_PROPERTY, identifierConstant(&local.name)); emitByte(OP_POP); } } FREE_ARRAY(bool, signature.asProperty, MAX_PARAMETERS); } if (match(TOKEN_EQ)) { if (current->type == TYPE_INITIALIZER) { error("Can't return a value from an initializer"); emitBytes(OP_GET_LOCAL, 0); } else { expression(); } emitByte(OP_RETURN); } else { expectLine("Expecting a linebreak before method body"); expect(TOKEN_INDENT, "Expecting an indent before method body"); block(); } ObjFunction* result = endCompiler(); emitConstantArg(OP_CLOSURE, OBJ_VAL(result)); for (int i = 0; i < result->upvalueCount; i++) { emitByte(compiler.upvalues[i].isLocal ? 1 : 0); emitByte(compiler.upvalues[i].index); } if (type == TYPE_INITIALIZER) { emitByte(OP_INITIALIZER); } else { emitSignatureArg(OP_METHOD_INSTANCE + isStatic, &signature); } } static void classDeclaration() { expect(TOKEN_IDENTIFIER, "Expecting a class name"); Token className = parser.previous; int nameConstant = identifierConstant(&parser.previous); declareVariable(); if (match(TOKEN_LT)) { expect(TOKEN_IDENTIFIER, "Expecting a superclass name"); variable(false); if (identifiersEqual(&className, &parser.previous)) { error("A class can't inherit from itself"); } } else { emitConstantArg(OP_GET_GLOBAL, OBJ_VAL(copyString("Object"))); } emitVariableArg(OP_CLASS, nameConstant); defineVariable(nameConstant); ClassCompiler classCompiler; classCompiler.hasInitializer = false; classCompiler.enclosing = currentClass; currentClass = &classCompiler; pushScope(); addLocal(syntheticToken("super")); defineVariable(0); namedVariable(className, false); bool empty = match(TOKEN_LEFT_BRACKET) && match(TOKEN_RIGHT_BRACKET); empty = empty || match(TOKEN_SEMICOLON); if (!empty) { expectLine("Expecting a linebreak before class body"); expect(TOKEN_INDENT, "Expecting an indent before class body"); matchLine(); while (!check(TOKEN_DEDENT) && !check(TOKEN_EOF)) { method(); matchLine(); } if (!check(TOKEN_EOF)) expect(TOKEN_DEDENT, "Expecting indentation to decrease after class body"); } emitByte(OP_POP); // Class popScope(); currentClass = currentClass->enclosing; } static void funDeclaration() { int global = parseVariable("Expecting a function name"); markInitialized(); function(TYPE_FUNCTION); defineVariable(global); } static void varDeclaration() { if (match(TOKEN_LEFT_PAREN)) { IntArray vars; intArrayInit(&vars); do { intArrayWrite(&vars, parseVariable("Expecting a variable name")); } while (match(TOKEN_COMMA)); if (vars.count > UINT8_MAX) { error("Cannot define more than %d variables with one statement", UINT8_MAX); } expect(TOKEN_RIGHT_PAREN, "Expecting ')' after variable names"); bool isNone = false; if (match(TOKEN_EQ)) { if (matchLine() && match(TOKEN_INDENT)) { parser.ignoreDedents++; } expression(); } else { isNone = true; emitByte(OP_NONE); } if (!isNone) { emitByte(OP_DUP); callMethod(0, "count", 5); emitConstant(NUMBER_VAL((uint8_t)vars.count)); callMethod(1, "==(1)", 5); int jump = emitJump(OP_JUMP_TRUTHY_POP); if (vars.count == 1) { emitConstant(OBJ_VAL(copyStringLength("Must have exactly 1 value to unpack", 35))); } else { emitConstant(OBJ_VAL(stringFormat("Must have exactly $ values to unpack", numberToCString(vars.count)))); } emitByte(OP_ERROR); patchJump(jump); } for (int i = 0; i < vars.count; i++) { emitByte(OP_DUP); if (!isNone) { emitConstant(NUMBER_VAL((uint8_t)i)); callMethod(1, "get(1)", 6); } defineVariable(vars.data[i]); } intArrayFree(&vars); emitByte(OP_POP); // The value was duplicated, so pop the original. } else { int global = parseVariable("Expecting a variable name"); if (match(TOKEN_EQ)) { if (matchLine() && match(TOKEN_INDENT)) parser.ignoreDedents++; expression(); } else { emitByte(OP_NONE); } defineVariable(global); } } static void useStatement() { int variableCount = 0; IntArray sourceConstants; IntArray nameConstants; if (!check(TOKEN_STRING)) { intArrayInit(&sourceConstants); intArrayInit(&nameConstants); do { matchLine(); expect(TOKEN_IDENTIFIER, "Expecting a variable name"); variableCount++; int sourceConstant = identifierConstant(&parser.previous); int nameConstant = sourceConstant; if (match(TOKEN_RIGHT_ARROW)) { nameConstant = parseVariable("Expecting a variable name alias"); } else { declareVariable(); } intArrayWrite(&sourceConstants, sourceConstant); intArrayWrite(&nameConstants, nameConstant); } while (match(TOKEN_COMMA)); expect(TOKEN_IDENTIFIER, "Expecting 'from' after import variables"); if (parser.previous.length != 4 || memcmp(parser.previous.start, "from", 4) != 0) { error("Expecting 'from' after import variables"); } } expect(TOKEN_STRING, "Expecting a module to import"); emitConstantArg(OP_IMPORT_MODULE, parser.previous.value); // Pop the return value from the module emitByte(OP_POP); if (variableCount > 0) { for (int i = 0; i < variableCount; i++) { emitVariableArg(OP_IMPORT_VARIABLE, sourceConstants.data[i]); defineVariable(nameConstants.data[i]); } } } static void expressionStatement() { expression(); emitByte(OP_POP); } static void printStatement() { expression(); callMethod(0, "toString()", 10); emitByte(OP_PRINT); } static void errorStatement() { expression(); callMethod(0, "toString()", 10); emitByte(OP_ERROR); } static void breakStatement() { if (current->loop == NULL) { error("Can't use 'break' outside of a loop"); } Token* label = NULL; if (match(TOKEN_COLON)) { expect(TOKEN_IDENTIFIER, "Expecting a label after ':'"); label = ALLOCATE(Token, 1); memcpy(label, &parser.previous, sizeof(Token)); } Loop* loop = current->loop; if (label != NULL) { for (;;) { if (loop->label != NULL && identifiersEqual(loop->label, label)) break; loop = loop->enclosing; if (loop == NULL) { error("Can't find loop with this label"); return; } } } discardLocals(loop->scopeDepth + 1); if (loop->breakCapacity < loop->breakCount + 1) { loop->breakCapacity = GROW_CAPACITY(loop->breakCapacity); loop->breaks = (int*)realloc(loop->breaks, sizeof(int) * loop->breakCapacity); } loop->breaks[loop->breakCount++] = emitJump(OP_JUMP); FREE(Token, label); } static void continueStatement() { if (current->loop == NULL) { error("Can't use 'continue' outside of a loop"); } Token* label = NULL; if (match(TOKEN_COLON)) { expect(TOKEN_IDENTIFIER, "Expecting a label after ':'"); label = ALLOCATE(Token, 1); memcpy(label, &parser.previous, sizeof(Token)); } Loop* loop = current->loop; if (label != NULL) { for (;;) { if (loop->label != NULL && identifiersEqual(loop->label, label)) break; loop = loop->enclosing; if (loop == NULL) { error("Can't find loop with this label"); return; } } } discardLocals(loop->scopeDepth + 1); // Jump to the top of the loop. emitLoop(loop->start); FREE(Token, label); } static void returnStatement() { if (check(TOKEN_LINE) || check(TOKEN_SEMICOLON)) { emitReturn(); } else { if (current->type == TYPE_INITIALIZER) { error("Can't return a value from an initializer"); } int values = 0; do { values++; expression(); if (matchLine() && match(TOKEN_INDENT)) parser.ignoreDedents++; } while (match(TOKEN_COMMA)); if (values >= UINT8_MAX) { error("Cannot return more than %d values", UINT8_MAX); } if (values > 1) emitBytes(OP_TUPLE, (uint8_t)values); emitByte(OP_RETURN); } } static void whileStatement() { Token* label = NULL; if (match(TOKEN_COLON)) { expect(TOKEN_IDENTIFIER, "Expecting a loop label"); label = ALLOCATE(Token, 1); memcpy(label, &parser.previous, sizeof(Token)); } Loop loop; startLoop(&loop); current->loop->label = label; expression(); // Condition current->loop->exitJump = emitJump(OP_JUMP_FALSY); emitByte(OP_POP); if (match(TOKEN_DO) && !check(TOKEN_LINE)) { statement(); } else { expectLine("Expecting a linebreak after condition"); expect(TOKEN_INDENT, "Expecting an indent before body"); scopedBlock(); } endLoop(); FREE(Token, label); } static void forStatement() { pushScope(); Token* label = NULL; if (match(TOKEN_COLON)) { expect(TOKEN_IDENTIFIER, "Expecting a loop label"); label = ALLOCATE(Token, 1); memcpy(label, &parser.previous, sizeof(Token)); } if (match(TOKEN_SEMICOLON)) { // No initializer. } else if (match(TOKEN_VAR)) { varDeclaration(); expectStatementEnd("Expecting ';' after loop initializer"); } else { expressionStatement(); expectStatementEnd("Expecting ';' after loop initializer"); } Loop loop; startLoop(&loop); current->loop->label = label; current->loop->exitJump = -1; if (!match(TOKEN_SEMICOLON)) { expression(); expectStatementEnd("Expecting ';' after loop condition"); // Jump out of the loop if the condition is false. current->loop->exitJump = emitJump(OP_JUMP_FALSY); emitByte(OP_POP); } if (!check(TOKEN_DO) && !check(TOKEN_LINE)) { int bodyJump = emitJump(OP_JUMP); int incrementStart = currentChunk()->count; expressionStatement(); emitLoop(current->loop->start); current->loop->start = incrementStart; patchJump(bodyJump); } if (match(TOKEN_DO) && !check(TOKEN_LINE)) { statement(); } else { expectLine("Expecting a linebreak after condition"); expect(TOKEN_INDENT, "Expecting an indent before body"); scopedBlock(); } endLoop(); popScope(); FREE(Token, label); } static void eachStatement() { pushScope(); // Scope for hidden iterator variables expect(TOKEN_IDENTIFIER, "Expecting a loop variable"); Token name = parser.previous; Token index; bool hasIndex = false; if (match(TOKEN_LEFT_BRACKET)) { hasIndex = true; expect(TOKEN_IDENTIFIER, "Expecting an index variable"); index = parser.previous; expect(TOKEN_RIGHT_BRACKET, "Expecting ']' after index variable"); } expect(TOKEN_IN, "Expecting 'in' after loop variable"); matchLine(); expression(); if (current->localCount + 2 > UINT8_COUNT) { error("Cannot declare any more locals."); return; } addLocal(syntheticToken("`seq")); markInitialized(); int seqSlot = current->localCount - 1; emitByte(OP_NONE); addLocal(syntheticToken("`iter")); markInitialized(); int iterSlot = current->localCount - 1; Loop loop; startLoop(&loop); emitBytes(OP_GET_LOCAL, seqSlot); emitBytes(OP_GET_LOCAL, iterSlot); callMethod(1, "iterate(1)", 10); emitBytes(OP_SET_LOCAL, iterSlot); current->loop->exitJump = emitJump(OP_JUMP_FALSY); emitByte(OP_POP); emitBytes(OP_GET_LOCAL, seqSlot); emitBytes(OP_GET_LOCAL, iterSlot); callMethod(1, "iteratorValue(1)", 16); pushScope(); // Loop variable addLocal(name); markInitialized(); if (hasIndex) { emitBytes(OP_GET_LOCAL, iterSlot); addLocal(index); markInitialized(); } if (match(TOKEN_DO) && !check(TOKEN_LINE)) { statement(); } else { expectLine("Expecting a linebreak after condition"); expect(TOKEN_INDENT, "Expecting an indent before body"); block(); } popScope(); // Loop variable endLoop(); popScope(); // `seq and `iter variables } static void ifStatement() { expression(); int thenJump = emitJump(OP_JUMP_FALSY); emitByte(OP_POP); if (match(TOKEN_DO) && !check(TOKEN_LINE)) { statement(); } else { expectLine("Expecting a linebreak after condition"); expect(TOKEN_INDENT, "Expecting an indent before body"); scopedBlock(); } int elseJump = emitJump(OP_JUMP); patchJump(thenJump); emitByte(OP_POP); if (match(TOKEN_ELIF)) ifStatement(); else if (match(TOKEN_ELSE)) { if (match(TOKEN_DO) && !check(TOKEN_LINE)) { statement(); } else { expectLine("Expecting a linebreak after 'else'"); expect(TOKEN_INDENT, "Expecting an indent before body"); scopedBlock(); } } patchJump(elseJump); } #define MAX_WHEN_CASES 256 // TODO: Review when statements, the code is old and unpolished. static void whenStatement() { expression(); match(TOKEN_DO); // TODO: Possibly make custom operators, like this: // // when var // >= 3 do something() // == 3 do somethingElse() // 3 do somethingElse() # same as == expectLine("Expecting a newline before cases"); expect(TOKEN_INDENT, "Expecting an indent before cases"); matchLine(); int state = 0; // 0 at very start, 1 before default, 2 after default int caseEnds[MAX_WHEN_CASES]; int caseCount = 0; int previousCaseSkip = -1; if (check(TOKEN_DEDENT)) errorAtCurrent("When statement must have at least one case"); while (!check(TOKEN_DEDENT) && !check(TOKEN_EOF)) { if (match(TOKEN_IS) || match(TOKEN_ELSE)) { TokenType caseType = parser.previous.type; if (state == 2) { error("Can't have any cases after the default case"); } if (state == 1) { if (caseCount == MAX_WHEN_CASES) { error("When statements cannot have more than %d cases", MAX_WHEN_CASES); } caseEnds[caseCount++] = emitJump(OP_JUMP); patchJump(previousCaseSkip); emitByte(OP_POP); } if (caseType == TOKEN_IS) { state = 1; emitByte(OP_DUP); expression(); // TODO: Add multiple expressions to compare to, like this: // // when var // is 3 | 4 do print "3 or 4" callMethod(1, "==(1)", 5); previousCaseSkip = emitJump(OP_JUMP_FALSY); // Pop the comparison result emitByte(OP_POP); if (match(TOKEN_DO) && !check(TOKEN_LINE)) { statement(); expectLine("Expecting a newline after statement"); } else { expectLine("Expecting a linebreak after case"); expect(TOKEN_INDENT, "Expecting an indent before body"); scopedBlock(); } } else { if (state == 0) { error("Can't have a default case first"); } state = 2; previousCaseSkip = -1; if (match(TOKEN_DO) && !check(TOKEN_LINE)) { statement(); expectLine("Expecting a newline after statement"); } else { expectLine("Expecting a linebreak after condition"); expect(TOKEN_INDENT, "Expecting an indent before body"); scopedBlock(); } } } else { if (state == 0) { error("Can't have statements before any case"); } statement(); if (!check(TOKEN_EOF)) expectStatementEnd("Expecting a newline after statement"); } } if (!check(TOKEN_EOF)) expect(TOKEN_DEDENT, "Expecting indentation to decrease after cases"); // If there is no default case, patch the jump. if (state == 1) { patchJump(previousCaseSkip); emitByte(OP_POP); } for (int i = 0; i < caseCount; i++) { patchJump(caseEnds[i]); } emitByte(OP_POP); // The switch value } static void synchronize() { parser.panicMode = false; while (parser.current.type != TOKEN_EOF) { if (parser.previous.type == TOKEN_SEMICOLON) return; switch (parser.current.type) { case TOKEN_CLASS: case TOKEN_ATTRIBUTE: case TOKEN_STATIC: case TOKEN_FUN: case TOKEN_VAR: case TOKEN_FOR: case TOKEN_EACH: case TOKEN_WHILE: case TOKEN_WHEN: case TOKEN_BREAK: case TOKEN_CONTINUE: case TOKEN_PRINT: case TOKEN_PRINT_ERROR: case TOKEN_RETURN: return; default:; // Do nothing. } advance(); } } static void declaration() { if (match(TOKEN_CLASS)) classDeclaration(); else if (match(TOKEN_FUN)) funDeclaration(); else if (match(TOKEN_VAR)) varDeclaration(); else if (match(TOKEN_USE)) useStatement(); else statement(); if (parser.panicMode) synchronize(); } static void statement() { if (match(TOKEN_PRINT)) printStatement(); else if (match(TOKEN_PRINT_ERROR)) errorStatement(); else if (match(TOKEN_PASS)) return; else if (match(TOKEN_BREAK)) breakStatement(); else if (match(TOKEN_CONTINUE)) continueStatement(); else if (match(TOKEN_RETURN)) returnStatement(); else if (match(TOKEN_WHILE)) whileStatement(); else if (match(TOKEN_FOR)) forStatement(); else if (match(TOKEN_EACH)) eachStatement(); else if (match(TOKEN_IF)) ifStatement(); else if (match(TOKEN_WHEN)) whenStatement(); else { if ((parser.printResult && current->scopeDepth == 0) || current->type == TYPE_LAMBDA) { parser.onExpression = true; expression(); } else expressionStatement(); } } ObjFunction* compile(const char* source, ObjModule* module, bool printResult) { parser.module = module; parser.printResult = printResult; parser.hadError = false; parser.panicMode = false; parser.onExpression = false; parser.ignoreDedents = 0; initLexer(source); Compiler compiler; initCompiler(&compiler, TYPE_SCRIPT); advance(); # if DEBUG_PRINT_TOKENS == 1 if (!module->isCore) { do { printf("%d\n", parser.current.type); advance(); } while (!match(TOKEN_EOF)); return NULL; } # elif DEBUG_PRINT_TOKENS == 2 do { printf("%d\n", parser.current.type); advance(); } while (!match(TOKEN_EOF)); return NULL; # endif matchLine(); if (match(TOKEN_INDENT)) error("Unexpected indentation"); while (!match(TOKEN_EOF)) { if (parser.onExpression) { emitByte(OP_POP); parser.onExpression = false; } declaration(); if (parser.previous.type != TOKEN_DEDENT) { if (!match(TOKEN_SEMICOLON) && !matchLine()) { matchLine(); expect(TOKEN_EOF, "Expecting end of file"); break; } matchLine(); } } emitByte(OP_END_MODULE); ObjFunction* function = endCompiler(); return parser.hadError ? NULL : function; } void markCompilerRoots() { markObject((Obj*)parser.module); Compiler* compiler = current; while (compiler != NULL) { markObject((Obj*)compiler->function); compiler = compiler->enclosing; } }
package com.unpi.asika.activity import android.graphics.Color import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.github.razir.progressbutton.attachTextChangeAnimator import com.github.razir.progressbutton.bindProgressButton import com.github.razir.progressbutton.hideProgress import com.github.razir.progressbutton.showProgress import com.unpi.asika.GlideApp import com.unpi.asika.R import com.unpi.asika.presenter.ForgotPasswordPresenter import com.unpi.asika.view.ForgotPasswordView import kotlinx.android.synthetic.main.activity_forgot_pass.* class ForgotPassActivity : AppCompatActivity() , ForgotPasswordView.View { private lateinit var mEmail: String private lateinit var presenter: ForgotPasswordView.Presenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_forgot_pass) prepare() btn_reset.setOnClickListener { mEmail = input_email.text.toString() presenter.requestForgotPassword(mEmail) } } override fun onSuccess(message: String) { Toast.makeText( this, message, Toast.LENGTH_SHORT ).show() } override fun handleResponse(message: String) { Toast.makeText( this, message, Toast.LENGTH_SHORT ).show() } override fun showProgressBar() { btn_reset.showProgress { progressColor = Color.WHITE } } override fun hideProgressBar() { btn_reset.hideProgress(R.string.btn_reset) } override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } private fun prepare() { GlideApp.with(this) .load(R.drawable.header) .into(img_header) presenter = ForgotPasswordPresenter(this, this) bindProgressButton(btn_reset) btn_reset.attachTextChangeAnimator() } }
import { NavLink } from 'react-router-dom'; import { useSelector } from 'react-redux'; import { getUser } from '../../redux/auth/authSelectors'; import UserAvatarIcon from './UserAvatarIcon/UserAvatarIcon'; import UserDefaultIcon from 'icons/UserDefaultIcon'; import styles from './UserNav.module.scss'; export default function UserNav({ isMobile, style, onClick }) { const user = useSelector(getUser); // console.log(user.avatarURL); return ( <div className={styles.container} style={style}> <NavLink className={styles.link} onClick={onClick} to="/user"> {user.avatarURL ? ( <UserAvatarIcon src={user.avatarURL} /> ) : ( <UserDefaultIcon style={{ marginRight: 12 }} /> )} {!isMobile && ( <p className={styles.text}>{user.name ? user.name : user.email}</p> )} </NavLink> </div> ); }
import numpy as np from shapely.geometry.polygon import orient def gpd_geographic_area(geodf): if not geodf.crs and geodf.crs.is_geographic: raise TypeError('geodataframe should have geographic coordinate system') geod = geodf.crs.get_geod() def area_calc(geom): if geom.geom_type not in ['MultiPolygon', 'Polygon']: return np.nan # For MultiPolygon do each separately if geom.geom_type == 'MultiPolygon': return np.sum([area_calc(p) for p in geom.geoms]) # orient to ensure a counter-clockwise traversal. # See https://pyproj4.github.io/pyproj/stable/api/geod.html # geometry_area_perimeter returns (area, perimeter) return geod.geometry_area_perimeter(orient(geom, 1))[0] return geodf.geometry.apply(area_calc) from shapely.geometry import Polygon def line_integral_polygon_area(geom, radius=6378137): """ Computes area of spherical polygon, assuming spherical Earth. Returns result in ratio of the sphere's area if the radius is specified. Otherwise, in the units of provided radius. lats and lons are in degrees. from https://stackoverflow.com/a/61184491/6615512 """ if geom.geom_type not in ['MultiPolygon', 'Polygon']: return np.nan # For MultiPolygon do each separately if geom.geom_type == 'MultiPolygon': return np.sum([line_integral_polygon_area(p) for p in geom.geoms]) # parse out interior rings when present. These are "holes" in polygons. if len(geom.interiors) > 0: interior_area = np.sum([line_integral_polygon_area(Polygon(g)) for g in geom.interiors]) geom = Polygon(geom.exterior) else: interior_area = 0 # Convert shapely polygon to a 2 column numpy array of lat/lon coordinates. geom = np.array(geom.boundary.coords) lats = np.deg2rad(geom[:, 1]) lons = np.deg2rad(geom[:, 0]) # Line integral based on Green's Theorem, assumes spherical Earth # close polygon if lats[0] != lats[-1]: lats = np.append(lats, lats[0]) lons = np.append(lons, lons[0]) # colatitudes relative to (0,0) a = np.sin(lats / 2) ** 2 + np.cos(lats) * np.sin(lons / 2) ** 2 colat = 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) # azimuths relative to (0,0) az = np.arctan2(np.cos(lats) * np.sin(lons), np.sin(lats)) % (2 * np.pi) # Calculate diffs # daz = np.diff(az) % (2*pi) daz = np.diff(az) daz = (daz + np.pi) % (2 * np.pi) - np.pi deltas = np.diff(colat) / 2 colat = colat[0:-1] + deltas # Perform integral integrands = (1 - np.cos(colat)) * daz # Integrate area = abs(sum(integrands)) / (4 * np.pi) area = min(area, 1 - area) if radius is not None: # return in units of radius return (area * 4 * np.pi * radius ** 2) - interior_area else: # return in ratio of sphere total area return area - interior_area # a wrapper to apply the method to a geo data.frame def gpd_geographic_area_line_integral(geodf): return geodf.geometry.apply(line_integral_polygon_area)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Portfolio Website</title> <!-- font awesome kit link --> <script src="https://kit.fontawesome.com/6ebb309f55.js" crossorigin="anonymous" ></script> <!-- poppin font from the google font --> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700;800;900&display=swap" rel="stylesheet" /> <!-- adding the css file to html document --> <link rel="stylesheet" href="../style.css" /> <link rel="stylesheet" href="./contact.css"> </head> <body> <!-- Header Portion --> <header> <!-- Creating the Navigation Menu --> <nav> <!-- Logo Area --> <div class="logo">LOGO</div> <!-- Navigation Links --> <ul> <li><a href="../index.html">Home</a></li> <li><a href="../about/about.html">About</a></li> <li><a href="./contact.html">Contact</a></li> </ul> <!-- Search Area --> <div class="search-field"> <input type="text" placeholder="Search" /> <button>Search</button> </div> </nav> </header> <!-- creating the main content area --> <main class="mainWrapper"> <!-- left div for showing the submitted response --> <div class="mainLeft"> <h2>User Output Board</h2> <form class="mainLeftDetails"> <input class="enterName" type="text" readonly placeholder="User Entered Name"> <input class="enterMail" type="email" readonly placeholder="User Entered Email"> <textarea class="enterMessage" readonly placeholder="User Entered Message"></textarea> <button type="reset">Reset</button> </form> </div> <!-- right div for accepting the user input through the form --> <div class="mainRight"> <h2>User Input Board</h2> <form> <input class="userName" type="text" placeholder="Enter Your Name" required> <input class="userEmail" type="email" placeholder="Enter Your Email" required> <textarea class="userMessage" placeholder="Message" required></textarea> <button type="submit" id="submit">Submit</button> </form> </div> </main> <script> let form1 = document.querySelector(".mainRight"); let userName = document.querySelector(".userName"); let enterName = document.querySelector(".enterName") let userEmail = document.querySelector(".userEmail"); let enterMail = document.querySelector(".enterMail"); let userMessage = document.querySelector(".userMessage"); let enterMessage = document.querySelector(".enterMessage"); form1.addEventListener("submit" , function(event){ event.preventDefault(); enterName.value = userName.value; enterMail.value = userEmail.value; enterMessage.value = userMessage.value; }); // let x = document.getElementById("userName"); // x.style.backgroundColor = "red"; // let y = document.getElementById("submit"); // y.addEventListener("submit", ()=>{ // x.style.backgroundColor = "blue"; // }); // function submit(){ // // x.style.backgroundColor = "white"; // // console.log(x); // // console.log(2+2); // } </script> </body> </html>
import Foundation import RxSwift /// Copyright (c) 2020 Razeware LLC /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// This project and source code may use libraries or frameworks that are /// released under various Open-Source licenses. Use of those libraries and /// frameworks are governed by their own individual licenses. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. example(of: "ignoreElements") { let strikes = PublishSubject<String>() let disposeBag = DisposeBag() strikes .ignoreElements() .subscribe { _ in print("You´re out!") } .disposed(by: disposeBag) strikes.onNext("X") strikes.onNext("X") strikes.onNext("X") strikes.onCompleted() } example(of: "elementAt") { let strikes = PublishSubject<String>() let disposeBag = DisposeBag() strikes .elementAt(2) .subscribe( onNext: { _ in print("Tou´re out!") } ) .disposed(by: disposeBag) strikes.onNext("X") strikes.onNext("X") strikes.onNext("X") } example(of: "filter") { let disposeBag = DisposeBag() Observable.of(1,2,3,4,5,6) .filter { $0.isMultiple(of: 2) } .subscribe( onNext: { print($0) } ) .disposed(by: disposeBag) } example(of: "skip") { let disposeBag = DisposeBag() Observable.of("A", "B", "C", "D", "E", "F") .skip(3) .subscribe( onNext: { print($0) } ) .disposed(by: disposeBag) } example(of: "skipWhile") { let disposeBag = DisposeBag() Observable.of(2,2,3,4,4) .skipWhile { $0.isMultiple(of: 2) } .subscribe( onNext: { print($0) } ) .disposed(by: disposeBag) } example(of: "skipUntil") { let disposeBag = DisposeBag() let subject = PublishSubject<String>() let trigger = PublishSubject<String>() subject .skipUntil(trigger) .subscribe( onNext: { print($0) } ) .disposed(by: disposeBag) subject.onNext("A") subject.onNext("B") trigger.onNext("1") subject.onNext("C") } example(of: "take") { let disposeBag = DisposeBag() Observable.of(1,2,3,4,5,6) .take(3) .subscribe( onNext: { print($0) } ) .disposed(by: disposeBag) } example(of: "takeWhile") { let disposeBag = DisposeBag() Observable.of(2,2,4,4,4,6) .enumerated() .takeWhile { index, integer in integer.isMultiple(of: 2) && index < 3 } .map(\.element) .subscribe( onNext: { print($0) } ) .disposed(by: disposeBag) } example(of: "takeUntil") { let disposeBag = DisposeBag() Observable.of(1,2,3,4,5) .takeUntil(.exclusive) { $0.isMultiple(of: 4) } .subscribe( onNext: { print($0) } ) .disposed(by: disposeBag) } example(of: "takeUntil trigger") { let disposeBag = DisposeBag() let subject = PublishSubject<String>() let trigger = PublishSubject<String>() subject .takeUntil(trigger) .subscribe( onNext: { print($0) } ) .disposed(by: disposeBag) subject.onNext("Hola") subject.onNext("Como") trigger.onNext("Interumpir") subject.onNext("Estas") } example(of: "distinctUntilChanged") { let disposeBag = DisposeBag() Observable.of("A", "A", "B", "B", "A") .distinctUntilChanged() .subscribe( onNext: { print($0) } ) .disposed(by: disposeBag) } example(of: "distinctUntilChanged(_:)") { let disposeBag = DisposeBag() let formatter = NumberFormatter() formatter.numberStyle = .spellOut Observable<NSNumber>.of(10,110,20,200,210,310) .distinctUntilChanged { a, b in guard let aWords = formatter.string(from: a)?.components(separatedBy: " "), let bWords = formatter.string(from: b)?.components(separatedBy: " ") else { return false } var containsMatch = false for aWord in aWords where bWords.contains(aWord) { containsMatch = true break } return containsMatch } .subscribe( onNext: { print($0) } ) .disposed(by: disposeBag) }
use isocountry::CountryCode; use rocket_okapi::okapi::schemars; use rocket_okapi::okapi::schemars::JsonSchema; use serde::{Deserialize, Serialize}; /// TODO! the usage location should be part of the cloud_inventory model (region names are tied to a specific cloud provider) #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct UsageLocation { pub aws_region: String, /// The 3-letters ISO country code corresponding to the country of the aws_region pub iso_country_code: String, } impl From<&str> for UsageLocation { fn from(aws_region: &str) -> Self { UsageLocation { aws_region: String::from(aws_region), iso_country_code: get_country_from_aws_region(aws_region).alpha3().to_owned(), } } } /// Converts aws region into country code, returns FRA if not found fn get_country_from_aws_region(aws_region: &str) -> CountryCode { let cc: CountryCode = match aws_region { "eu-central-1" => CountryCode::DEU, "eu-east-1" => CountryCode::IRL, "eu-north-1" => CountryCode::SWE, "eu-south-1" => CountryCode::ITA, "eu-west-1" => CountryCode::IRL, "eu-west-2" => CountryCode::GBR, "eu-west-3" => CountryCode::FRA, "us-east-1" => CountryCode::USA, "us-east-2" => CountryCode::USA, "us-west-1" => CountryCode::USA, "us-west-2" => CountryCode::USA, _ => { error!("Unsupported region: Unable to match aws region [{}] to country code, defaulting to FRA !", aws_region); CountryCode::FRA } }; cc } #[cfg(test)] mod tests { //use super::*; use super::UsageLocation; #[test] fn test_get_country_code_for_supported_aws_region() { let location = UsageLocation::from("eu-west-1"); assert_eq!("IRL", location.iso_country_code); let location = UsageLocation::from("eu-west-2"); assert_eq!("GBR", location.iso_country_code); let location = UsageLocation::from("eu-west-3"); assert_eq!("FRA", location.iso_country_code); } #[test] fn test_get_country_code_of_unsupported_aws_region_returns_fra() { let location = UsageLocation::from("ap-south-1"); assert_eq!("FRA", location.iso_country_code); let location = UsageLocation::from(""); assert_eq!("FRA", location.iso_country_code); } }
public with sharing class ObjectInfoController { public String objectName{get; set;} public Boolean canRead{get; set;} public Boolean canCreate{get; set;} public Boolean canEdit{get; set;} public Boolean canDelete{get; set;} public List<WrappedFields> fields{get; set;} public void getObjectInfo() { List<String> objName = new List<String>(); objName.add(objectName); Map<String, SObjectType> objects = Schema.getGlobalDescribe(); try { System.debug(objectName); DescribeSObjectResult describe = objects.get(objectName).getDescribe(); canRead = describe.isAccessible(); canCreate = describe.isCreateable(); canEdit = describe.isUpdateable(); canDelete = describe.isDeletable(); fields = new List<ObjectInfoController.WrappedFields>(); for (SObjectField field :Schema.describeSObjects(objName)[0].fields.getMap().values()) { fields.add(new WrappedFields(field)); } } catch (NullPointerException ex) { ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Object not found')); // throw new VisualforceException(ex.getMessage()); } } public class WrappedFields { public String Name{get; set;} public Boolean Read{get; set;} public Boolean Edit{get; set;} public WrappedFields(SObjectField field) { Name = field.getDescribe().name; Read = field.getDescribe().isAccessible(); Edit = field.getDescribe().isUpdateable(); } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="./images/favicon.ico" rel="icon" type="image/x-icon" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous" defer></script> <link rel="stylesheet" href="./css/style.css"> <link rel="stylesheet" href="./css/mq.css"> <script src="./js/search.js" type="module"></script> <script src="./js/browse.js" type="module"></script> <title>Browse Movies</title> </head> <body> <div class="offcanvas offcanvas-5 offcanvas-top text-bg-dark" tabindex="-1" id="offcanvasTop" aria-labelledby="offcanvasTopLabel"> <div class="offcanvas-header"> <a href="#" class="search-btn"> <i class="bi bi-search d-block"></i> </a> <div id="search-component"> <input id="search-input" type="search" name="search" placeholder="search for a movie" autocomplete="off"> </div> <button type="button" class="btn-close btn-close-white me-3 p-3" data-bs-dismiss="offcanvas" aria-label="Close"></button> </div> <div class="offcanvas-search-body"> <div id="search-results" class="hide"> <ul class="list-group"> <div data-search-lis> </div> </ul> </div> </div> </div> <div class="app"> <div class="sticky-sidenav fs-4"> <ul class="sidebar-items"> <li> <a href="/" class="side-links"> <i class="bi bi-house"></i> </a> </li> <li> <a href="/browse.html" class="side-links"> <i class="bi bi-tv selected"></i> </a> </li> <li> <a href="#" class="side-links" data-bs-toggle="offcanvas" data-bs-target="#offcanvasTop" aria-controls="offcanvasTop"> <i class="bi bi-search"></i> </a> </li> </ul> <a href="https://github.com/khaleed-dev" target="_blank" class="side-links link-light p-1 mb-1 k-dev" style="font-size: 12px"> @khaleed-dev </a> </div> <section id="browse-movies" class="container mt-0 mt-xl-4 p-xl-5 p-3"> <h2>Browse Movies <span class="page-count fs-5"></span></h2> <div class="card text-bg-dark border-around mt-3"> <div class="card-header p-3"> <ul class="list-group d-flex flex-row justify-content-center"> <li class="pure-material-button-text activated list-group-item" data-hash="popular">Popular</li> <li class="pure-material-button-text list-group-item" data-hash="now-playing">Now Playing</li> <li class="pure-material-button-text list-group-item" data-hash="best">Best All Time</li> </ul> </div> <div class="card-body"> <div class="mb-3 d-flex justify-content-center align-items-center"> <!-- dropdowns go here --> <form class = "filters d-flex justify-content-center align-items-center"> <select id="year-filter" class="form-select form-select-sm me-2 filter" title="year-filter" style="max-width: 100px;" > <option selected value="0" class="text-muted">Year</option> </select> <select id="genre-filter" class="form-select form-select-sm me-2 filter" title="genre-filter" style="max-width: 110px;"> <option selected value="" class="text-muted">Genre</option> <option value="28">action</option> <option value="10752">war</option> <option value="12">adventure</option> <option value="16">animation</option> <option value="35">comedy</option> <option value="80">crime</option> <option value="99">documentary</option> <option value="18">drama</option> <option value="10751">family</option> <option value="14">fantasy</option> <option value="36">history</option> <option value="27">horror</option> <option value="10402">music</option> <option value="9648">mystery</option> <option value="10749">romance</option> <option value="878">science-fiction</option> <option value="53">thriller</option> </select> <select id="language-filter" class="form-select form-select-sm me-2 filter" title="language-filter" style="max-width: 120px;"> <option selected value="" class="text-muted">Language</option> </select> <button class="btn btn-sm btn-outline-light ms-2" type="submit" style="width: 120px;">Filter</button> </form> </div> <div class="browse-movies-list d-flex flex-wrap justify-content-center"> <!-- movies go here --> </div> </div> </div> </section> </div> </body> </html>
import { useState } from "react"; const Button = ({ handleClick, text }) => { return <button onClick={handleClick}>{text}</button>; }; const StatisticLine = (props) => { return ( <tr> <td>{props.text}</td> <td>{props.value}</td> </tr> ); }; const Statistics = ({ all, good, neutral, bad }) => { const average = (good * 1 + neutral * 0 + bad * -1) / all; const positive = ((good * 1) / all) * 100 + " %"; if (all === 0) { return <div>No feedback given</div>; } return ( <table> <tbody> <StatisticLine text="good" value={good} /> <StatisticLine text="neutral" value={neutral} /> <StatisticLine text="bad" value={bad} /> <StatisticLine text="all" value={all} /> <StatisticLine text="average" value={average} /> <StatisticLine text="positive" value={positive} /> </tbody> </table> ); }; const App = () => { // save clicks of each button to its own state const [good, setGood] = useState(0); const [neutral, setNeutral] = useState(0); const [bad, setBad] = useState(0); const [all, setToAll] = useState(0); const handleGoodClick = () => { const updatedGood = good + 1; setGood(updatedGood); setToAll(updatedGood + neutral + bad); }; const handleNeutralClick = () => { const updatedNeutral = neutral + 1; setNeutral(updatedNeutral); setToAll(good + updatedNeutral + bad); }; const handleBadClick = () => { const updatedBad = bad + 1; setBad(updatedBad); setToAll(good + neutral + updatedBad); }; return ( <div> <h1>give feedback</h1> <Button handleClick={handleGoodClick} text="good" /> <Button handleClick={handleNeutralClick} text="neutral" /> <Button handleClick={handleBadClick} text="bad" /> <h1>statistics</h1> <Statistics all={all} good={good} neutral={neutral} bad={bad} /> </div> ); }; export default App;
import express from "express"; import { Request, Response, NextFunction } from "express"; import { UserModel } from "../database/models/user"; import { QueryFindOneAndUpdateOptions } from 'mongoose'; const router = express.Router(); import userRoute from './user/user.routing'; import MessageRoute from './message/message.routing'; router.use('/user/',userRoute); router.use('/message/',MessageRoute); router.get("/test", express.json(), (req, res, next) => { res.send(JSON.stringify(req.body)); }); router.get("/error", (req, res, next) => { next("error page."); }); router.post("/post", express.json(), (req, res, next) => { res.send(JSON.stringify(req.body)); }); const errorHandler = ( func: (req: Request, res: Response, next: NextFunction) => Promise<void> ) => (req: Request, res: Response, next: NextFunction) => func(req, res, next).catch(next); // database 的 CRUD // C router.post( "/user", express.json(), errorHandler(async (req, res, next) => { const { username, email } = req.body; const user = new UserModel({ username, email }); const data = await user.save(); res.send(data); }) ); //R router.get( "/users", errorHandler(async (req, res, next) => { const documents = await UserModel.findOne({ username: req.query.username }); res.send(documents); }) ); //U router.patch( "/users/:id", express.json(), errorHandler(async (req, res, next) => { await UserModel.updateOne( { _id: req.params.id }, { username: req.body.username }, { runValidators: true } ); res.send("成功"); }) ); //U會回傳修改直 router.patch( "/users/:id", express.json(), errorHandler(async (req, res, next) => { const options: QueryFindOneAndUpdateOptions = { new: true, runValidators: true, }; const document = await UserModel.findByIdAndUpdate( req.params.id, { username: req.body.username }, options ); res.send(document); }) ); //D router.delete( "/users/:id", errorHandler(async (req, res, next) => { await UserModel.findByIdAndRemove(req.params.id); res.send("刪除成功"); }) ); router.get("/data/error", (req, res, next) => { // Fake API const getProfile = new Promise((resolve, reject) => { setTimeout(() => resolve({ name: "HAO", age: 22 }), 100); }); const getFriends = new Promise((resolve, reject) => { setTimeout(() => resolve([]), 120); }); const errorRequest = new Promise((resolve, reject) => { setTimeout(() => reject("Oops!"), 2000); }); getProfile .then((profile) => getFriends) .then((friends) => errorRequest) .then(() => res.send("GoGoGo!")) .catch((err) => next(err)); }); router.get( "/data/error/promise", errorHandler(async (req, res, next) => { // Fake API const getProfile = new Promise((resolve, reject) => { setTimeout(() => resolve({ name: "HAO", age: 22 }), 100); }); const getFriends = new Promise((resolve, reject) => { setTimeout(() => resolve([]), 120); }); const errorRequest = new Promise((resolve, reject) => { setTimeout(() => reject("Oops!"), 2000); }); const profile = await getProfile; const friends = await getFriends; const none = await errorRequest; res.send("GoGoGo!"); }) ); export default router;